地理位置未捕获类型错误:无法读取未定义的属性“坐标”

Posted

技术标签:

【中文标题】地理位置未捕获类型错误:无法读取未定义的属性“坐标”【英文标题】:Geolocation Uncaught TypeError: Cannot read property 'coords' of undefined 【发布时间】:2012-11-15 21:55:00 【问题描述】:

我在搞乱 Google Maps API 和 Geolocation。一切都按预期工作,但是我在控制台中不断收到此错误:

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标签<body id="map" onload="initialize()">中初始化地图

地图渲染良好,一切正常。当我将position.coords 登录到我的控制台时,我得到了一个干净的读数。为什么我不断收到此错误消息?

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

干杯

【问题讨论】:

【参考方案1】:

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

试试这个方法:

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 函数不变。

【讨论】:

【参考方案2】:

错误可能就在这里

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

您正在调用没有参数的初始化函数。因此'position'参数是未定义的

function initialize(position) 
    var lat = position.coords.latitude;

好像你打来的一样

var lat = undefined.coords.latitude

【讨论】:

【参考方案3】:

如果您在使用地图对象之前在 cordova/phonegap 中的 google 地图上遇到错误,请确保存在 google map html data-lat 和 data-long 属性。

这是一个示例,

没有 data-lat 和 data-long,并且作为 web 应用程序进行测试,在谷歌地图初始化期间将失败

【讨论】:

以上是关于地理位置未捕获类型错误:无法读取未定义的属性“坐标”的主要内容,如果未能解决你的问题,请参考以下文章

未捕获的类型错误:无法读取未定义的属性“名称”

未捕获的类型错误:无法读取未定义的属性“authenticateClientAndRetrieveSessionId”

未捕获的类型错误:无法读取未定义的属性“区域”?

错误:`未捕获(承诺中)类型错误:无法读取未定义的属性'doc'`

未捕获的类型错误:无法读取未定义的属性 toLowerCase

JQuery:未捕获的类型错误:无法读取未定义的属性“调用”