首页 > 解决方案 > 无法将 1 个函数中的变量用于另一个函数

问题描述

我想在我的标记中使用 getLocation() 函数中的 lat 和 lng,但它不起作用。

我添加了警报,因为如果那个有效,一切都会。

I tried var lat = ...
I tried world.lat = ...

有返回值的东西

function getLocation() {
var onSuccess = function (position) {
    console.log('Latitude: ' + position.coords.latitude + '\n' +
        'Longitude: ' + position.coords.longitude + '\n' +
        'Altitude: ' + position.coords.altitude + '\n' +
        'Accuracy: ' + position.coords.accuracy + '\n' +
        'Altitude Accuracy: ' + position.coords.altitudeAccuracy + '\n' +
        'Heading: ' + position.coords.heading + '\n' +
        'Speed: ' + position.coords.speed + '\n' +
        'Timestamp: ' + position.timestamp + '\n');

    lat = position.coords.latitude;
    $('.locationLatitude').text(lat);
    lng = position.coords.longitude;
    $('.locationLongitude').text(lng);
    console.log(`latitude: ${lat} longitude: ${lng}`);
};

function onError(error) {
    console.log('code: ' + error.code + '\n' +
        'message: ' + error.message + '\n');
    alert(`code: ${error.code}
    message: ${error.message}
    Please turn on your GPS`);
}

navigator.geolocation.getCurrentPosition(onSuccess, onError);
}
alert(lat, lng);
function meOnMap() {
    marker2 = L.marker([lat, lng]).addTo(map).bindPopup('Your Location').openPopup();
}

我希望 lat 和 lng 值从另一个函数中返回它们的值,但它们没有。

标签: javascriptjquery

解决方案


在您的函数中引用时,看起来您想要lat并且lng在范围内。meOnMap注释在正确的轨道上,您可以将它们声明为全局变量。为此,只需将其放在var lat, lng;文件的顶部即可。

或者你可以在你的meOnMap函数声明中添加一些参数并在你的成功回调函数中调用它,在它完成所有处理之后:

function meOnMap(lat, lng) {
    marker2 = L.marker([lat, lng]).addTo(map).bindPopup('Your Location').openPopup();
}
var onSuccess = function (position) {
    ...
    meOnMap(lat,lng);
};

推荐阅读