最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to get the current location of the user? - Stack Overflow

programmeradmin0浏览0评论

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.

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.

Share Improve this question edited Jul 18, 2023 at 19:26 Brian Tompsett - 汤莱恩 5,88372 gold badges61 silver badges133 bronze badges asked Jan 28, 2019 at 16:06 Suman KalyanSuman Kalyan 431 gold badge1 silver badge3 bronze badges 1
  • Take a look at the Geolocation API developer.mozilla.org/en-US/docs/Web/API/Geolocation_API – Daniel Doblado Commented Jan 28, 2019 at 16:13
Add a comment  | 

5 Answers 5

Reset to default 11

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

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
}));

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>

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 :)
});

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 (
发布评论

评论列表(0)

  1. 暂无评论