gpt4 book ai didi

javascript - Javascript 中变量值未定义

转载 作者:行者123 更新时间:2023-12-02 21:32:42 25 4
gpt4 key购买 nike

我正在尝试使用 HTML5 地理定位来获取用户位置。纬度和经度值已成功接收,我可以将其显示在 map 上。我想保存用户位置以便稍后使用,因此我定义了 origin 变量,并连接了 lat 和 lng 变量,然后将连接值分配给 origin。当我稍后尝试使用原始值时,其值未定义。有人可以告诉我问题出在代码中吗?我想这个问题很愚蠢,但我无法解决。我认为问题与变量范围无关。

这是代码:

let map ;

// initialize the map and show it on the dashboard.
function initMap()
{
// Map options.
let options =
{
center :
{
lat : 41.015137,
lng : 28.979530
},
zoom : 12
}

// New map.
map = new google.maps.Map
(
document.getElementById('map'),
options
);
};

$(document).ready
(
function()
{
$("#order_and_show").click
(
function()
{
// Change the text of the title and the button when get order from the user.
$('#order_title').text('Cancel the order right now') ;
$('#order_and_show').text('Cancel Now') ;

// Get user location from browser using HTML geolocation.
let origin ;

// HTML5 geolocation.
if (navigator.geolocation)
{
navigator.geolocation.getCurrentPosition
(
function(position)
{
let pos =
{
lat: position.coords.latitude,
lng: position.coords.longitude
} ;

origin = position.coords.latitude + ',' + position.coords.longitude ;

// Add marker.
let marker = new google.maps.Marker
(
{
position : pos,
map : map,
}
) ;

// Center the map according to user location.
map.setCenter(pos);

// Add popup window for user location information
let infoWindow = new google.maps.InfoWindow
(
{
content : '<h6>Your Location</h6>'
}
) ;

marker.addListener
(
'click',
() =>
{
infoWindow.open(map, marker) ;
}
) ;
},
function()
{
handleLocationError(true, infoWindow, map.getCenter());
}
);
}

else
{
// Browser doesn't support Geolocation
handleLocationError(false, infoWindow, map.getCenter());
}

// Handle Geolocation errors.
function handleLocationError(browserHasGeolocation, infoWindow, pos)
{
infoWindow.setPosition(pos);

infoWindow.setContent
(
browserHasGeolocation ? 'Error: The Geolocation service failed.' : 'Error: Your browser does not support geolocation.'
) ;

infoWindow.open(map);
}

console.log(origin) ;


}
) ;


}
) ;

最佳答案

当前代码的问题是您尝试在设置它的回调之外访问origingetCurrentPosition 回调可能是异步执行的,因此当您尝试在回调之外访问 origin 时,回调函数尚未执行,从而导致 origin > 值未定义。您可以使用 promisesasync/await来解决这个问题。这样的解决方案可能如下所示:

$(document).ready(function () {
const map = new google.maps.Map(
document.getElementById("map"),
{ center: { lat: 41.015137, lng: 28.979530 }, zoom: 12 }
);

function handleLocationError(infoWindow, msg) {
infoWindow.setPosition(map.getCenter());
infoWindow.setContent(msg);
infoWindow.open(map);
}

$("#order_and_show").click(async function () {
// notice the async keyword ^
$('#order_title').text('Cancel the order right now');
$('#order_and_show').text('Cancel Now');

let position, origin;
if (navigator.geolocation) {
try {
// await the position before continuing
position = await new Promise((resolve, reject) => {
navigator.geolocation.getCurrentPosition(resolve, reject);
});
let pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
origin = position.coords.latitude + ',' + position.coords.longitude;
let marker = new google.maps.Marker({position: pos, map: map});
let infoWindow = new google.maps.InfoWindow({
content: '<h6>Your Location</h6>'
});

map.setCenter(position);
marker.addListener('click', () => infoWindow.open(map, marker));
} catch (error) {
// I'm not sure how you are able to access infoWindow here since it's
// created in the try block after the error is thrown.
handleLocationError(infoWindow, 'Error: The Geolocation service failed.')
}
} else {
// Same here, you don't have access to infoWindow, since it's not created
// yet. However both the above and this are present to mimic the question
// structure.
handleLocationError(infoWindow, 'Error: Your browser does not support geolocation.');
}

// origin should be available unless geolocation isn't supported or
// getCurrentPosisiton failed to execute successfully
console.log(origin);
});
});

有关使用异步行为的更多信息,我建议查看 MDN Using Promises指南。

关于javascript - Javascript 中变量值未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60580466/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com