Reputation: 2449
How do you set a mapbox map to the user's location at initialization? I understand that you can go to the user's location programmatically like this:
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(e => {
map.jumpTo({center: [e.coords.longitude, e.coords.latitude]})
})
}
But this first initializes the map at some default location, and then goes to the user's location. I've also tried moving this call to navigator.geolocation to before the map gets initialized, but since this calls navigator.geolocation that takes a little longer and the result is still that the map loads momentarily showing the default location, then going to where the user is. Trying to get the lat and lng from navigator and then passing those to the map constructor should work, but I'm having trouble getting the map to wait for those variables without causing issues. More importantly, this seems like a feature that would have broad appeal so I feel like I'm overcomplicating it. How do you start the map at the user's location?
Upvotes: 2
Views: 1414
Reputation: 126205
Just don't create the map until you know the location.
function initMap(lngLat) {
window.map = new mapboxgl.Map({
center: lngLat,
// ...
});
// more initialization
});
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(e => {
initMap([e.coords.longitude, e.coords.latitude])
})
} else {
initMap([ /* default location */ ]);
}
You will obviously also have to disable any other functionality that depends on the map being loaded, until that point.
Upvotes: 3