I am setting up a map which will have the store locations nearer to the current location of the user. But I am unable to get that done. I went through the documentation but I couldn't find anything helpful regarding my problem. What I want If I click on the find the location then it should show me the stores nearer to me.
I have already tried putting a static longitude and latitude and it works fine. I want it to be dynamic.
mapboxgl.accessToken = 'THE_ACCESS_TOKEN';
// This adds the map to your page
var map = new mapboxgl.Map({
// container id specified in the HTML
container: 'map',
// style URL
style: 'mapbox://styles/mapbox/light-v10',
// initial position in [lon, lat] format
center: [78.3430302, 17.449968],
// initial zoom
zoom: 14
});
In the Center, I want dynamic longitude and latitude value (Current location). So that it will show me the stores nearer to my location.
Javascript has a geolocation API that you can use without importing additional dependencies, which will provide you with the user's location in terms of latitude and longitude, you can check more information here.
User will have to give permissions to the web app to access to their location. A quick sample of how you can get coordinates in your code:
if ("geolocation" in navigator) {
navigator.geolocation.getCurrentPosition(position => {
console.log(position.coords.latitude, position.coords.longitude);
});
} else { /* geolocation IS NOT available, handle it */ }
UPDATE: Incorporating the geolocation code to your code would be something like this (check if it goes as latitude, longitude or the other way around):
mapboxgl.accessToken = 'YOUR_ACCESS_TOKEN';
// This adds the map to your page
if ("geolocation" in navigator) {
navigator.geolocation.getCurrentPosition(position => {
var map = new mapboxgl.Map({
// container id specified in the HTML
container: 'map',
// style URL
style: 'mapbox://styles/mapbox/light-v10',
// initial position in [lon, lat] format
center: [position.coords.longitude, position.coords.latitude],
// initial zoom
zoom: 14
});
});
} else { /* geolocation IS NOT available, handle it */ }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With