rob*_*bby 4 javascript google-maps geolocation
我正在使用带有地理定位功能的 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!");
}
Run Code Online (Sandbox Code Playgroud)
我的成功处理程序:
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!"
});
}
Run Code Online (Sandbox Code Playgroud)
然后我在我的 body 标签中初始化地图 <body id="map" onload="initialize()">
地图渲染良好,一切都按预期工作。当我登录position.coords
到我的控制台时,我得到了一个干净的读数。为什么我一直收到这个错误?
谷歌和 SO 搜索没有结果......
干杯
加载文档时,将调用 initialize 方法,不带参数。这就是您收到错误的原因。
试试这种方式:
function initCoords() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(initialize, locationError);
} else {
showError("Your browser does not support Geolocation!");
}
}
Run Code Online (Sandbox Code Playgroud)
并在您的 html 代码中:
<body id="map" onload="initCoords()">
保持initialize
功能不变。
归档时间: |
|
查看次数: |
15750 次 |
最近记录: |