Suman Kalyan
Suman Kalyan

Reputation: 43

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.

Upvotes: 4

Views: 14025

Answers (5)

Shub
Shub

Reputation: 555

Mapbox's offers a GeolocateControl plugin that uses JS's geolocation API under the hood.

Eg from the docs:

const geolocate = new mapboxgl.GeolocateControl({
    positionOptions: {
        enableHighAccuracy: true
    },
    trackUserLocation: true
});

// add the geolocate control to the map (𖦏 icon)
map.addControl(geolocate);

// once the map is loaded, trigger the geolocation control which will center the map on user's current position
map.on('load', () => {
    geolocate.trigger();

});

// log the coordinates after trigger
geolocate.on('geolocate', (e) => {
    console.log(e.coords.longitude, e.coords.latitude);
})

Upvotes: 0

Johnvh
Johnvh

Reputation: 21

I've got the same issue. The solution is not in the docs of Mapbox (or I didn't find them):

const geolocateControl = new mapboxgl.GeolocateControl({
  positionOptions: {
    enableHighAccuracy: true
  },
  trackUserLocation: true,
  showUserHeading: true
});

map.addControl(
  geolocateControl,
  'bottom-left'
);

geolocateControl.on('geolocate', (event) => {
  const latitude = event.coords.latitude;
  const longitude = event.coords.longitude;

  console.log(latitude, longitude);
  // Do something more with lat & long here :)
});

Upvotes: 0

Oscar Calderon
Oscar Calderon

Reputation: 999

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 */ }

Upvotes: 11

antelove
antelove

Reputation: 3358

if ( navigator.geolocation ) 
{
    navigator.geolocation.getCurrentPosition( function(position) {

        var lng = position.coords.longitude;
        var lat = position.coords.latitude;                    

        mapboxgl.accessToken = 'pk.eyJ1IjoiYW50ZWxvdmUxOSIsImEiOiJja2d1azl4ZmgwY3dvMnJueGljMnp6YnprIn0.aIRE0Ii2AmWYWCW5Z3cEFg';

        var map = new mapboxgl.Map({
            container: 'map',          
            style: 'mapbox://styles/mapbox/streets-v11',
            center: [ lng, lat ], // [ lng, lat ]
            zoom: 12
        });

    });
}
body { margin: 0; padding: 0; }
#map { position: absolute; top: 0; bottom: 0; width: 100%; }
<div id="map" ></div>

Upvotes: 0

Steve Bennett
Steve Bennett

Reputation: 126637

The other solutions are fine, but the easiest way is using Mapbox's GeolocateControl plugin. There's a complete example here: https://docs.mapbox.com/mapbox-gl-js/example/locate-user/

After the initial setup it's as simple as:

map.addControl(new mapboxgl.GeolocateControl({
  positionOptions: {
    enableHighAccuracy: true
  },
    trackUserLocation: true
}));

Upvotes: 4

Related Questions