【问题标题】: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 搜索没有结果...

干杯

【问题讨论】:

    标签: javascript google-maps geolocation


    【解决方案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 应用程序进行测试,在谷歌地图初始化期间将失败

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2021-04-03
          • 2019-09-28
          • 1970-01-01
          • 2014-04-13
          • 2016-01-25
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多