我是编程新手,我正在尝试使用天气和地理位置API运行代码。
我创建了一个位置函数getLocation(position),这样我就可以获得要在apiUrl中显示的纬度和经度,但是我找不到哪里出了问题!它在控制台上显示不能读取未定义的“坐标”。谁能帮帮我?:)
let apiKey = "6ae49199fbcb90f6780234a44e9b9db4";
let unit = "metric";
function getLocation(position) {
let geo = new Array();
let latitude = position.coords.latitude;
let longitude = position.coords.longitude;
return geo = [latitude, longitude]
}
//let apiUrl = `https://api.openweathermap.org/data/2.5/weather?lat=${latitude}&lon=${longitude}&appid=${apiKey}&units=${unit}`;
function getPosition() {
navigator.geolocation.getCurrentPosition(getLocation);
}
发布于 2020-11-07 01:21:17
未定义的值可以指示用户不同意发送位置数据。此外,将错误回调传递给getCurrentPosition也很好。在此回调中,您可以检查错误的原因。你的代码可以简化一点。我给出了两个例子。第二个使用箭头函数语法。
下面我准备了一个小例子:
<html>
<head>
<title>Test</title>
<script>
function onSuccessCallback(position) {
let lastLocation=[position.coords.latitude, position.coords.longitude];
document.getElementById("location").innerText=lastLocation;
}
function onErrorCallback(err){
document.getElementById("location").innerText=err.message;
}
//navigator.geolocation.getCurrentPosition(onSuccessCallback, onErrorCallback);
//example using arrow functions
navigator.geolocation.getCurrentPosition(
d => {
let lastLocation=[d.coords.latitude, d.coords.longitude];
document.getElementById("location").innerText=lastLocation;
}, err => {
document.getElementById("location").innerText=err.message;
});
</script>
</head>
<body>
<h1 id="location"></h1>>
</body>
</html>
https://stackoverflow.com/questions/64717867
复制相似问题