Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the current location of the user?

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.

like image 988
Suman Kalyan Avatar asked Oct 26 '25 15:10

Suman Kalyan


1 Answers

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 */ }
like image 57
Oscar Calderon Avatar answered Oct 28 '25 03:10

Oscar Calderon