使用谷歌地图API v3,如何通过给定的地址获取经纬度(LatLng)?

46

如果用户输入一个地址,我想把它转换成对应的LatLng坐标。

我已经阅读了文档,认为可以使用Geocoder类来实现这一点,但无法弄清如何实现。

感谢任何帮助!

3个回答

102

有一个非常好的例子在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 );
        }
    } );
}

13
我们希望所有的文档都像jQuery一样好。我很难理解谷歌的一些文档。 - Joshua G

33

我认为 location.LatLng 没有起作用,但是这个可以起作用:

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

在探索Get Lat Lon源代码时发现了它。


谢谢你! - cpcdev

23

如果你需要在后端完成这个操作,你可以使用以下的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);

查看更多的文档,了解更多细节和预期json响应

这些文档提供了示例输出,并帮助您获取自己的API密钥,以便能够向Google Maps Geocoding API发出请求。


你知道这个有限制吗?我的意思是,我在一个小时或一天内可以进行多少次调用? - Far Sighter
2
免费API限制为每24小时2500个请求,每秒5个请求...请参见https://developers.google.com/maps/documentation/geocoding/intro#Limits - farinspace
2
来到这里是为了找这个。PHP用户可能想使用$arr = json_decode($json, true);来访问数据。 - a coder

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接