簡體   English   中英

檢測到當前位置后如何在mapbox中獲取經度和緯度?

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

我使用此參考https: //docs.mapbox.com/mapbox-gl-js/example/locate-user/ 為我的 web 應用程序實現了 Mapbox。

我試過這個

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

但仍然無法正常工作。

我想問一下,用戶點擊定位按鈕后如何獲取當前的經緯度?

謝謝

您正在尋找的是我為您創建的這個代碼筆

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM