2016-12-15 44 views
-1

我用下面的代码,以有效的API密钥,从谷歌地理编码器JS API获取经纬度:谷歌地理位置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> 

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

有没有人曾经遇到过这个?有什么我失踪?我在搜索时找不到任何有关此问题的任何地方,这是我第一次使用该API。

回答

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>

+0

我本来可以发誓我试过提醒那些人,并且它h广告抱怨它不是真实的,但我只是试了一遍,它的工作。奇怪的。谢谢。 – DiMono