gpt4 book ai didi

javascript - 地理位置未捕获类型错误 : Cannot read property 'coords' of undefined

转载 作者:行者123 更新时间:2023-11-29 09:55:16 24 4
gpt4 key购买 nike

我正在使用带有地理定位功能的 Google Maps API。一切都按预期工作,但我的控制台中不断出现此错误:

Uncaught TypeError: Cannot read property 'coords' of undefined

这是我的地理检查:

// Does this browser support geolocation?
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(initialize, locationError);
} else {
showError("Your browser does not support Geolocation!");
}

我的成功处理者:

function initialize(position) {
var lat = position.coords.latitude;
var lon = position.coords.longitude;
var acc = position.coords.accuracy;

// Debugging
console.log(position.coords);
console.log("Accuracy: "+acc+"\nLatitude: "+lat+"\nLongitude: "+lon);

// Google Maps API
var myLatlng = new google.maps.LatLng(lat,lon);
var mapOptions = {
center: new google.maps.LatLng(lat, lon),
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title:"Hello World!"
});
}

然后我在我的 body 标签中初始化 map <body id="map" onload="initialize()">

map 渲染良好,一切都按预期工作。当我登录 position.coords到我的控制台,我得到一个干净的读数。为什么我不断收到此错误?

Google 和 SO 搜索没有结果...

干杯

最佳答案

加载文档时,会调用不带参数的初始化方法。这就是您收到错误的原因。

试试这个方法:

function initCoords() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(initialize, locationError);
} else {
showError("Your browser does not support Geolocation!");
}
}

在您的 html 代码中:

<body id="map" onload="initCoords()">

保留 initialize按原样运行。

关于javascript - 地理位置未捕获类型错误 : Cannot read property 'coords' of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13406914/

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