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

DiM*_*ono -1 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>
Run Code Online (Sandbox Code Playgroud)

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

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

geo*_*zip 5

results[0].geometry.location是一个google.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);
  });
Run Code Online (Sandbox Code Playgroud)

概念证明小提琴

代码段:

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);
Run Code Online (Sandbox Code Playgroud)
html,
body,
#map_canvas {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}
Run Code Online (Sandbox Code Playgroud)
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map_canvas"></div>
Run Code Online (Sandbox Code Playgroud)