【问题标题】:Combining Google Maps Geocoder and Leaflet Map Receiving Error: Invalid LatLng object结合谷歌地图地理编码器和传单地图接收错误:无效的 LatLng 对象
【发布时间】:2012-09-28 05:17:52
【问题描述】:

我正在使用 Google Maps Geocoder 来获取地址的纬度和经度。然后,我使用该地址并使用 Leaflet 并将地图平移到纬度 + 经度坐标。但是,我收到来自 Firebug 的错误消息 Error: Invalid LatLng object: (-33.8674869, 151.20699020000006, undefined)。我知道我的变量 geolocation 返回 -33.8674869, 151.20699020000006 但不是未定义的。是什么导致了问题?

 <body onload="initialize()">
  <div id="result"></div>
 <div>
  <input id="address" type="textbox" value="Sydney, NSW">
  <input type="button" value="Geocode" onclick="codeAddress()">
 </div>

 <div id="map"></div>

 <script type="text/javascript">

 var map = L.map('map').setView([33.7489954, -84.3879824], 13);

  var geocoder;

  function initialize() {
    geocoder = new google.maps.Geocoder();     
  }

  function codeAddress() {
    var address = document.getElementById('address').value;
    geocoder.geocode( { 'address': address}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {

        var geolocation = String(results[0].geometry.location);

        var geolocation = geolocation.replace('(','');

        var geolocation = geolocation.replace(')','');      

        map.panTo([geolocation]);

      } else {
        $('#result').html('Geocode was not successful for the following reason: ' + status);
      }
    });
  };

L.tileLayer('http://{s}.tile.cloudmade.com/apikeyputhere/997/256/{z}/{x}/{y}.png', {
maxZoom: 18
}).addTo(map);

</script> 

【问题讨论】:

    标签: javascript google-maps google-maps-api-3 leaflet cloudmade


    【解决方案1】:

    替换这个:

        var geolocation = String(results[0].geometry.location);
    
        var geolocation = geolocation.replace('(','');
    
        var geolocation = geolocation.replace(')','');      
    
        map.panTo([geolocation]);
    

    这样:

    map.panTo([results[0].geometry.location.lat(),results[0].geometry.location.lng()]);
    

    说明:
    您将一个字符串分配给第一个数组值,它与以下内容相同:

    geolocation=new Array('-33.8674869, 151.20699020000006')//contains 1 string
    

    字符串不会被计算,它仍然是 1 个字符串,但是你需要一个有 2 个浮点数的数组:

    geolocation=new Array(-33.8674869, 151.20699020000006)//contains 2 floats
    

    undefined 是提供给panTo() 的数组中缺少的第二项

    【讨论】:

    • 太棒了。简单的解释和将四行代码最小化为一行的答案。非常感谢。
    • map.panTo 的文档为其参数指定了 google.maps.LatLng。如果数组有效,那么您很幸运(它不应该有效)。 geocoder 结果 results[0].geometry.location 已经是 google.maps.LatLng,可以直接传给 panTo。
    • @geocodezip:这不是 google.maps.Map-object ,而是 Leaflet.map-object ,其中 panTo() 接受数组作为参数。
    • 感谢您的澄清。
    猜你喜欢
    • 1970-01-01
    • 2011-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多