谷歌的地理编码器返回错误的国家,忽略了该地区的暗示

时间:2010-04-15 16:20:21

标签: javascript google-maps geolocation gps geocode

我正在使用Google的Geocoder查找给定地址的lat lng坐标。

    var geocoder = new google.maps.Geocoder();
    geocoder.geocode(
    {
        'address':  address,
        'region':   'uk'
    }, function(results, status) {
        if(status == google.maps.GeocoderStatus.OK) {
            lat: results[0].geometry.location.lat(),
            lng: results[0].geometry.location.lng()
    });

address变量取自输入字段。

我想搜索仅在英国的位置。我认为指定'region': 'uk'应该足够了,但事实并非如此。当我输入“波士顿”时,它在美国找到波士顿,我想在英国找到它。

如何限制地理编码器只返回一个国家或某个纬度范围内的位置?

由于

13 个答案:

答案 0 :(得分:27)

以下代码将获得英国第一个匹配的地址,而无需修改地址。

  var geocoder = new google.maps.Geocoder();
  geocoder.geocode(
  {
    'address':  address,
    'region':   'uk'
  }, function(results, status) {
    if(status == google.maps.GeocoderStatus.OK) {
        for (var i=0; i<results.length; i++) {
            for (var j=0; j<results[i].address_components.length; j++) {
               if ($.inArray("country", results[i].address_components[j].types) >= 0) {
                    if (results[i].address_components[j].short_name == "GB") {
                        return_address = results[i].formatted_address;
                        return_lat = results[i].geometry.location.lat();
                        return_lng = results[i].geometry.location.lng();
                        ...
                        return;
                    }
                }
            }
        }
    });

答案 1 :(得分:26)

使用componentRestrictions属性:

geocoder.geocode({'address': request.term, componentRestrictions: {country: 'GB'}}

答案 2 :(得分:22)

更新:此答案可能不再是最佳方法。有关详细信息,请参阅答案下方的评论。


除了Pekka already suggested之外,您可能希望将', UK'连接到address,如下例所示:

<!DOCTYPE html>
<html> 
<head> 
   <meta http-equiv="content-type" content="text/html; charset=UTF-8"/> 
   <title>Google Maps Geocoding only in UK Demo</title> 
   <script src="http://maps.google.com/maps/api/js?sensor=false" 
           type="text/javascript"></script> 
</head> 
<body> 
   <div id="map" style="width: 400px; height: 300px"></div> 

   <script type="text/javascript"> 

   var mapOptions = { 
      mapTypeId: google.maps.MapTypeId.TERRAIN,
      center: new google.maps.LatLng(54.00, -3.00),
      zoom: 5
   };

   var map = new google.maps.Map(document.getElementById("map"), mapOptions);
   var geocoder = new google.maps.Geocoder();

   var address = 'Boston';

   geocoder.geocode({
      'address': address + ', UK'
   }, 
   function(results, status) {
      if(status == google.maps.GeocoderStatus.OK) {
         new google.maps.Marker({
            position:results[0].geometry.location,
            map: map
         });
      }
   });

   </script> 
</body> 
</html>

截图:

Geocoding only in UK

我发现这非常可靠。另一方面,以下示例显示region参数和bounds参数在这种情况下都没有任何效果:

<!DOCTYPE html>
<html> 
<head> 
   <meta http-equiv="content-type" content="text/html; charset=UTF-8"/> 
   <title>Google Maps Geocoding only in UK Demo with Bounds</title> 
   <script src="http://maps.google.com/maps/api/js?sensor=false" 
           type="text/javascript"></script> 
</head> 
<body> 
   <div id="map" style="width: 500px; height: 300px"></div> 

   <script type="text/javascript"> 

   var mapOptions = { 
      mapTypeId: google.maps.MapTypeId.TERRAIN,
      center: new google.maps.LatLng(50.00, -33.00),
      zoom: 3
   };

   var map = new google.maps.Map(document.getElementById("map"), mapOptions);   
   var geocoder = new google.maps.Geocoder();

   // Define north-east and south-west points of UK
   var ne = new google.maps.LatLng(60.00, 3.00);
   var sw = new google.maps.LatLng(49.00, -13.00);

   // Define bounding box for drawing
   var boundingBoxPoints = [
      ne, new google.maps.LatLng(ne.lat(), sw.lng()),
      sw, new google.maps.LatLng(sw.lat(), ne.lng()), ne
   ];

   // Draw bounding box on map    
   new google.maps.Polyline({
      path: boundingBoxPoints,
      strokeColor: '#FF0000',
      strokeOpacity: 1.0,
      strokeWeight: 2,
      map: map
   });

   // Geocode and place marker on map
   geocoder.geocode({
      'address': 'Boston',
      'region':  'uk',
      'bounds':  new google.maps.LatLngBounds(sw, ne)
   }, 
   function(results, status) {
      if(status == google.maps.GeocoderStatus.OK) {
         new google.maps.Marker({
            position:results[0].geometry.location,
            map: map
         });
      }
   });

   </script> 
</body> 
</html>

答案 3 :(得分:16)

这样做的正确方法是提供componentRestrictions

例如:

var request = {
    address: address,
    componentRestrictions: {
        country: 'UK'
    }
}
geocoder.geocode(request, function(results, status){
    //...
});

答案 4 :(得分:8)

根据docs,区域参数似乎只设置偏差(而不是该区域的实际限制)。我想当API在英国找不到确切的地址时,无论你输入什么地区,它都会扩展搜索范围。

我过去表现得非常好,在地址中指定了国家/地区代码(除了该地区)。 不过,我对不同国家的相同地名没有多少经验。不过,值得一试。尝试

'address': '78 Austin Street, Boston, UK'

它应该返回没有地址(而不是美国波士顿)和

'address': '78 Main Street, Boston, UK'

应该归还英国的波士顿,因为它实际上有一条主街。

<强>更新

  

如何限制地理编码器只返回一个国家或某个纬度范围内的位置?

您可以设置bounds参数。见here

当然,您必须为此计算一个英国大小的矩形。

答案 5 :(得分:5)

我发现将“,英国”,将该地区设置为英国并设置界限存在问题。然而,做所有这三件似乎都适合我。这是一个片段: -

var sw = new google.maps.LatLng(50.064192, -9.711914)
var ne = new google.maps.LatLng(61.015725, 3.691406)
var viewport = new google.maps.LatLngBounds(sw, ne);

geocoder.geocode({ 'address': postcode + ', UK', 'region': 'UK', "bounds": viewport }, function (results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
.....etc.....

答案 6 :(得分:2)

我尝试了以下内容:

geocoder.geocode( {'address':request.term + ', USA'}

它为特定地区(美国)工作。

答案 7 :(得分:1)

我总是发现这很容易过滤,因为结果可能会有所不同,而且该区域似乎不起作用。

response( $.map( results, function( item ) {
 if (item.formatted_address.indexOf("GB") != -1) {
    return {
      latitude: item.geometry.location.lat(),
      longitude: item.geometry.location.lng()
    }
  }
}

答案 8 :(得分:0)

我更喜欢混合方法

  1. 使用componentRestrictions严格限制国家/地区。
  2. 如果这不能产生足够的结果,请更广泛地搜索(并在必要时重新引入偏见)

    function MyGeocoder(address,region)
    {
        geocoder = new google.maps.Geocoder();
        geocoder.geocode({ 'address': address, 'componentRestrictions': { 'country': region } }, function (r, s) {
            if (r.length < 10) geocoder.geocode({ 'address': address /* could also bias here */ }, function (r2, s2) {
                for (var j = 0; j < r2.length; j++) r.push(r2[j]);
                DoSomethingWithResults(r);
            });
            else DoSomethingWithResults(r);
        });
    }
    function DoSomethingWithResults(r) { // Remove Duplicates var d = {}; r = r.filter(function (e) { var h = e.formatted_address.valueOf(); var isDup = d[h]; d[h] = true; return !isDup; });

    // Do something with results }
    // Do something with results }

答案 9 :(得分:0)

我发现,对于很多含糊不清的查询,即使你试图告诉它在哪里看,美国总是优先考虑谷歌。如果输出country = US?

,您可以查看响应并忽略它

这是我不久前停止使用Google Geocoder并在两年前开始建立自己的主要原因。

https://geocode.xyz/Boston,%20UK将始终返回英国位置。您可以通过添加region = UK:https://geocode.xyz/Boston,%20UK?region=UK

来确保更加确定

答案 10 :(得分:0)

我已经在英国周围创建了边框,并检查了我的纬度和经度是否在范围内。对于3 k个地址,我在美国大约有10个至20个地址。我只是忽略它们(我可以这样做),我使用lat和lng在具有自动缩放功能的静态地图上创建多个标记。我将分享我的解决方案,也许这会对某人有所帮助。我也很高兴听到针对我的案件的其他解决方案。

main()

答案 11 :(得分:-1)

对于英国,你必须使用GB作为地区。英国不是ISO国家代码!

答案 12 :(得分:-1)

我今天必须自己过滤结果给一个国家。我发现componentRestrictions:country:中的两个字符国家/地区代码不起作用。但完整的国家名称确实如此。

这是结果中address_components中的full_name。