Using Google maps API v3 how do I get LatLng with a given address?

匿名 (未验证) 提交于 2019-12-03 01:25:01

问题:

If a user inputs an address, I want to convert to the equivalent LatLng.

I've read the documentation, and I think I can use the Geocoder class to do this, but can't figure out how to implement it.

Thanks for any help!

回答1:

There is a pretty good example on https://developers.google.com/maps/documentation/javascript/examples/geocoding-simple

To shorten it up a little:

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 );         }     } ); }


回答2:

I don't think location.LatLng is working, however this works:

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

Found it while exploring Get Lat Lon source code.



回答3:

If you need to do this on the backend you can use the following URL structure:

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

Sample PHP code using 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);

See additional documentation for more details.

The docs provide sample output and will assist you in getting your own API key in order to be able to make requests to the Google Maps Geocoding API.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!