【问题标题】:Google maps API Searching postcodes in a specific countryGoogle maps API 搜索特定国家/地区的邮政编码
【发布时间】:2017-03-25 20:32:16
【问题描述】:

我正在尝试设置邮政编码以获取经纬度坐标并在其上放置一个标记。到现在为止,一切都很好。

当我输入一个邮政编码并且它最终在世界的另一个地方做一个标记时,问题就出现了。

例如:我输入 2975-435 并得到: https://maps.googleapis.com/maps/api/geocode/json?address=2975-435&key=YOURKEY

"formatted_address" : "Balbey Mahallesi, 435. Sk., 07040 Muratpaşa/Antalya, Turquia",

我想让这个邮政编码只在葡萄牙被搜索。

https://maps.googleapis.com/maps/api/geocode/json?address=2975-435+PT 这样我得到:

"formatted_address" : "2975 Q.ta do Conde, Portugal",

正是我想要的。

问题是,我如何在 JS 代码中做到这一点? 这是我到目前为止的代码

function codeAddress () {
    var lat = '';
    var lng = '';
    var address = document.getElementById("cp").value;
    geocoder.geocode( { 'address': address},

    function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            lat = results[0].geometry.location.lat();
            lng = results[0].geometry.location.lng();
            //Just to keep it stored
            positionArray.push(new google.maps.LatLng(lat,lng));
            //Make the marker
            new google.maps.Marker({
                position:new google.maps.LatLng(lat,lng),
                map:map
            });

        }else {
            alert("Geocode was not successful for the following reason: " + status);
        }
    });
}

谢谢

【问题讨论】:

    标签: javascript google-maps google-maps-api-3 google-maps-markers google-geocoder


    【解决方案1】:

    要将结果限制在某个国家/地区,您可以应用组件过滤:

    https://developers.google.com/maps/documentation/javascript/geocoding#ComponentFiltering

    所以,你的 JavaScript 代码将是

    function codeAddress () {
        var lat = '';
        var lng = '';
        var address = document.getElementById("cp").value;
        geocoder.geocode( { 
            'address': address,
            componentRestrictions: {
                country: 'PT'
            }
        },
    
        function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                lat = results[0].geometry.location.lat();
                lng = results[0].geometry.location.lng();
                //Just to keep it stored
                positionArray.push(new google.maps.LatLng(lat,lng));
                //Make the marker
                new google.maps.Marker({
                    position:new google.maps.LatLng(lat,lng),
                    map:map
                });
    
            }else {
                alert("Geocode was not successful for the following reason: " + status);
            }
        });
    }
    

    您可以使用 Geocoder 工具查看正在执行的组件过滤:

    https://developers-dot-devsite-v2-prod.appspot.com/maps/documentation/utils/geocoder/#q%3D2975-435%26options%3Dtrue%26in_country%3DPT%26nfw%3D1

    希望对你有帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-04-02
      • 1970-01-01
      • 2017-02-15
      • 1970-01-01
      • 2013-02-04
      • 2011-01-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多