如果用户输入一个地址,我想把它转换成对应的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);
这些文档提供了示例输出,并帮助您获取自己的API密钥,以便能够向Google Maps Geocoding API发出请求。
$arr = json_decode($json, true);
来访问数据。 - a coder