结合Google Maps Geocoder和Leaflet Map Receiving Error:无效的LatLng对象

时间:2012-10-07 22:51:41

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

我正在使用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> 

1 个答案:

答案 0 :(得分:5)

替换它:

    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()

的数组中缺少的第二项