【问题标题】:Using Google maps API v3 how do I get LatLng with a given address?使用 Google maps API v3 如何获取具有给定地址的 LatLng?
【发布时间】:2011-04-25 00:27:51
【问题描述】:

如果用户输入地址,我想转换为等价的 LatLng。

我已经阅读了文档,我认为我可以使用 Geocoder 类来执行此操作,但无法弄清楚如何实现它。

感谢您的帮助!

【问题讨论】:

    标签: google-maps-api-3


    【解决方案1】:

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

    【讨论】:

    • 难道我们不希望所有文档都和 jQuery 一样好。我对 Google 的一些文档感到厌烦。
    【解决方案2】:

    我不认为location.LatLng 有效,但这是有效的:

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

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

    【讨论】:

    • 谢谢!
    【解决方案3】:

    如果您需要在后端执行此操作,您可以使用以下 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 发出请求。

    【讨论】:

    • 你知道这个限制是多少吗?我的意思是我一小时或一天可以打多少个电话?
    • 免费 API 限制为每 24 小时 2500 个请求,每秒 5 个请求...请参阅 developers.google.com/maps/documentation/geocoding/intro#Limits
    • 来这里找这个。 PHP 用户可能希望使用$arr = json_decode($json, true); 来访问数据。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-17
    • 1970-01-01
    • 1970-01-01
    • 2011-09-02
    • 2013-10-05
    相关资源
    最近更新 更多