I am reading in my current location using Geolocation correctly, & now want to render a Leaflet map which centers around those co-ordinates.
The problem that I’m facing is that both getLoc()
& initMap()
are being called in ngAfterViewInit()
.
Even though I’m calling getLoc()
first, it looks as my longitude & latitude variables aren’t being populated before the map is initiated.
Can someone please tell me how I can ensure my current location is read in before the map is initiated, so I can use those co-ordinates to center the map?
Here is ngAfterViewInit()
:
ngAfterViewInit(): void {
this.getLoc();
this.initMap();
}
Here is getLoc()
:
getLoc() {
this.geolocation.getCurrentPosition(
{
maximumAge: 1000, timeout: 5000,
enableHighAccuracy: true
}
).then((resp) => {
this.lat = resp.coords.latitude
this.lng = resp.coords.longitude
}, er => {
alert('Can not retrieve Location')
}).catch((error) => {
alert('Error getting location - ' + JSON.stringify(error))
});
}
And here is initMap()
:
private initMap(): void {
console.log(this.lat + " : " + this.lng);
this.map = L.map('map', {
center: [this.lat, this.lng],
zoom: 3
});
const tiles = L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
maxZoom: 19,
attribution: '© <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>'
});
tiles.addTo(this.map);
}