简体   繁体   中英

How to get longitude and latitude in mapbox after detect current location?

I implemented Mapbox for my web apps using this reference https://docs.mapbox.com/mapbox-gl-js/example/locate-user/ .

I tried this

mapboxgl.accessToken = '<your access token here>';
var map = new mapboxgl.Map({
container: 'map', // container id
style: 'mapbox://styles/mapbox/streets-v11',
center: [-96, 37.8], // starting position
zoom: 3 // starting zoom
});

// Add geolocate control to the map.
        let geolocate = new mapboxgl.GeolocateControl({
                positionOptions: {
                    enableHighAccuracy: true
                },
                trackUserLocation: true
            })
        map.addControl(geolocate);

        geolocate.on('click', function(e) {
            // The event object (e) contains information like the
            // coordinates of the point on the map that was clicked.
            let latitude = e.lngLat.lat;
            let longitude = e.lngLat.lng;
            alert("Clicked");
            $("#latitude").text(latitude);
            $("#longitude").text(longitude);
            console.log('Latitude: ' + latitude + '\n Longitude: ' + longitude);
        });

But still not working.

I want to ask, how to get current latitude and longitude after user clicked the locate button?

Thank you

What you are looking for is this codepen I created for you :

let map = new mapboxgl.Map({
  container: "map", // container id
  style: "mapbox://styles/mapbox/streets-v11",
  center: [-96, 37.8], // starting position
  zoom: 3 // starting zoom
});

// Add geolocate control to the map.
// Initialize the geolocate control.
let geolocate = new mapboxgl.GeolocateControl({
  positionOptions: {
    enableHighAccuracy: true
  },
  trackUserLocation: true
});
// Add the control to the map.
map.addControl(geolocate);
map.on("load", function () {
  geolocate.trigger(); // add this if you want to fire it by code instead of the button
});
geolocate.on("geolocate", locateUser);

function locateUser(e) {
  console.log("A geolocate event has occurred.");
  console.log("lng:" + e.coords.longitude + ", lat:" + e.coords.latitude);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM