【发布时间】:2011-04-25 00:27:51
【问题描述】:
如果用户输入地址,我想转换为等价的 LatLng。
我已经阅读了文档,我认为我可以使用 Geocoder 类来执行此操作,但无法弄清楚如何实现它。
感谢您的帮助!
【问题讨论】:
如果用户输入地址,我想转换为等价的 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源代码时发现它。
【讨论】:
如果您需要在后端执行此操作,您可以使用以下 URL 结构:
https://maps.googleapis.com/maps/api/geocode/json?address=[STREET_ADDRESS]&key=[YOUR_API_KEY]
使用 curl 的示例 PHP 代码:
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'https://maps.googleapis.com/maps/api/geocode/json?address=' . rawurlencode($address) . '&key=' . $api_key);
curl_setopt ($curl, CURLOPT_RETURNTRANSFER, 1);
$json = curl_exec($curl);
curl_close ($curl);
$obj = json_decode($json);
更多详情请参见其他documentation,预计json response。
文档提供示例输出,并将帮助您获取自己的 API key,以便能够向 Google Maps Geocoding API 发出请求。
【讨论】:
$arr = json_decode($json, true); 来访问数据。