Google Geolocation JS API提供无意义的Lat / Long

时间:2016-12-15 18:27:55

标签: javascript google-maps google-geocoding-api

我使用以下代码(使用有效的API密钥)从Google Geocoder JS API获取纬度和经度:

<script async defer type="text/javascript"
    src="http://maps.google.com/maps/api/js?key=[key]">
</script>
<script>
    var geocoder = new google.maps.Geocoder();
    var address = "1600 Amphitheatre Parkway, Mountain View, CA";
    geocoder.geocode( { 'address': address}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK)
        {
            console.log (results[0]);
            // results[0].geometry.location.lat
            // results[0].geometry.location.lng
        }
        else console.log(status, results);
    });
</script>

对Google服务器的查询工作正常,并带回结果。问题在于,无论我输入什么地址,location.lat都会以_.E/this.lat()的形式返回,而location.lng会以_.E/this.lng()的形式返回。视口坐标很好,但实际的纬度和经度结果对我来说是无稽之谈。如果我将代码放入函数并将其作为回调传递,则会发生同样的事情。

以前有没有人见过这个?有什么我想念的吗?我搜索时无法找到有关此问题的任何内容,这是我第一次使用该API。

1 个答案:

答案 0 :(得分:5)

results[0].geometry.locationgoogle.maps.LatLng。它没有.lat / .lng属性,它们是函数,您需要调用它们:

  var geocoder = new google.maps.Geocoder();
  var address = "1600 Amphitheatre Parkway, Mountain View, CA";
  geocoder.geocode({
    'address': address
  }, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
      console.log(results[0]);
      var lat = results[0].geometry.location.lat();
      var lng = results[0].geometry.location.lng();
      map.setCenter(results[0].geometry.location);
    } else console.log(status, results);
  });

proof of concept fiddle

代码段

var geocoder;
var map;

function initialize() {
  var map = new google.maps.Map(
    document.getElementById("map_canvas"), {
      center: new google.maps.LatLng(37.4419, -122.1419),
      zoom: 13,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });
  var geocoder = new google.maps.Geocoder();
  var address = "1600 Amphitheatre Parkway, Mountain View, CA";
  geocoder.geocode({
    'address': address
  }, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
      console.log(results[0]);
      var lat = results[0].geometry.location.lat();
      var lng = results[0].geometry.location.lng();
      var iw = new google.maps.InfoWindow();
      iw.setContent("lat:" + lat + "<br>lng:" + lng);
      iw.setPosition(results[0].geometry.location);
      iw.open(map);
      map.setCenter(results[0].geometry.location);
    } else console.log(status, results);
  });
}
google.maps.event.addDomListener(window, "load", initialize);
html,
body,
#map_canvas {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map_canvas"></div>