使用谷歌地图API v3如何获得给定地址的LatLng?

如果用户input一个地址,我想要转换成相应的LatLng。

我读过文档,我想我可以使用Geocoder类来做到这一点,但不知道如何实现它。

谢谢你的帮助!

https://developers.google.com/maps/documentation/javascript/examples/geocoding-simple上有一个很好的例子;

缩短一点:

geocoder = new google.maps.Geocoder(); function codeAddress() { //In this case it gets the address from an element on the page, but obviously you could just pass it to the method instead var address = document.getElementById( 'address' ).value; geocoder.geocode( { 'address' : address }, function( results, status ) { if( status == google.maps.GeocoderStatus.OK ) { //In this case it creates a marker, but you can get the lat and lng from the location.LatLng map.setCenter( results[0].geometry.location ); var marker = new google.maps.Marker( { map : map, position: results[0].geometry.location } ); } else { alert( 'Geocode was not successful for the following reason: ' + status ); } } ); } 

我不认为location.LatLng正在工作,但是这个工作:

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

在探索Get Lat Lon源代码的时候find了它。

如果您需要在后端执行此操作,则可以使用以下URL结构:

 https://maps.googleapis.com/maps/api/geocode/json?address=STREET_ADDRESS 

使用curl示例PHP代码:

 $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, 'https://maps.googleapis.com/maps/api/geocode/json?address=' . rawurlencode($address)); curl_setopt ($curl, CURLOPT_RETURNTRANSFER, 1); $json = curl_exec($curl); curl_close ($curl); 

请参阅其他文档以获取更多详细信