Если пользователь вводит адрес, я хочу преобразовать его в эквивалентный 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
Пример кода PHP с использованием curl:
$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);
Подробнее см. documentation