簡體   English   中英

如何在 JS 中獲取用戶的位置,然后將響應作為坐標傳遞給 Google 地圖?

[英]How can I get the user's location in JS and then pass the response to the Google map as coordinates?

我正在嘗試使用地理定位成功獲取 JS 中的用戶位置,並且 2 個日志語句打印出坐標。 如何將 startPos 傳入 Google 地圖功能?

錯誤:

未捕獲(承諾)類型錯誤:無法讀取未定義的屬性“坐標”

在 initMap (dashboard.js:20)

謝謝!

代碼:

var startPos;

window.onload = function() {
    var geoSuccess = function(position) {
        startPos = position;
        //document.getElementById('startLat').innerHTML = startPos.coords.latitude;
        console.log(startPos.coords.latitude);
        //document.getElementById('startLon').innerHTML = startPos.coords.longitude;
        console.log(startPos.coords.longitude);
    };
    navigator.geolocation.getCurrentPosition(geoSuccess);
    return startPos;

    // Initialize and add the map

};
function initMap() {
    // The location of user

    var lat = startPos.coords.latitude;
    var long = startPos.coords.longitude;

    const userLocation = { lat: lat, lng: long };
    // The map, centered at Uluru
    const map = new google.maps.Map(document.getElementById("map"), {
        zoom: 4,
        center: userLocation,
    });
    // The marker, positioned at Uluru
    const marker = new google.maps.Marker({
        position: userLocation,
        map: map,
    });
}

initMap(startPos);

initMap 訪問未定義的 startPos 的原因是它在 onload 事件開始之前執行,並且位置數據到達調用 geoSuccess 回調之前

所以它應該看起來更像:

var startPos;

window.onload = function() {
    var geoSuccess = function(position) {
        startPos = position;
        //document.getElementById('startLat').innerHTML = startPos.coords.latitude;
        console.log(startPos.coords.latitude);
        //document.getElementById('startLon').innerHTML = startPos.coords.longitude;
        console.log(startPos.coords.longitude);

        initMap(); // Call it here!
    };
    navigator.geolocation.getCurrentPosition(geoSuccess);
};
function initMap() {
    // The location of user

    var lat = startPos.coords.latitude;
    var long = startPos.coords.longitude;

    const userLocation = { lat: lat, lng: long };
    // The map, centered at Uluru
    const map = new google.maps.Map(document.getElementById("map"), {
        zoom: 4,
        center: userLocation,
    });
    // The marker, positioned at Uluru
    const marker = new google.maps.Marker({
        position: userLocation,
        map: map,
    });
}

暫無
暫無

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

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