30

我正在使用 Google 的地理编码器来查找给定地址的 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变量取自输入字段。

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

如何限制地理编码器仅从一个国家或可能从某个纬度 lng 范围返回位置?

谢谢

4

13 回答 13

27

使用componentRestrictions属性:

geocoder.geocode({'address': request.term, componentRestrictions: {country: 'GB'}}
于 2013-11-08T10:25:44.993 回答
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;
                    }
                }
            }
        }
    });
于 2012-02-01T14:16:31.757 回答
22

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


除了Pekka 已经建议的内容之外,您可能还想连接', 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>

截屏:

仅在英国进行地理编码

我发现这是非常可靠的。另一方面,以下示例表明,在这种情况下,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>
于 2010-04-15T16:31:59.813 回答
16

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

例如:

var request = {
    address: address,
    componentRestrictions: {
        country: 'UK'
    }
}
geocoder.geocode(request, function(results, status){
    //...
});
于 2014-02-27T22:26:14.470 回答
8

根据文档,区域参数似乎只设置了一个偏差(而不是对该区域的实际限制)。我猜当 API 在英国找不到确切的地址时,无论您输入哪个地区,它都会扩大搜索范围。

过去,我在地址中指定国家代码(除了地区)方面做得很好。不过,我还没有太多在不同国家使用相同地名的经验。尽管如此,还是值得一试。尝试

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

它应该不返回地址(而不是美国波士顿),并且

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

应该返回英国的波士顿,因为那实际上有一条主街。

更新:

如何限制地理编码器仅从一个国家或可能从某个纬度 lng 范围返回位置?

您可以设置一个bounds参数。看这里

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

于 2010-04-15T16:26:54.630 回答
5

我发现放置“,UK”,将地区设置为UK并设置界限的问题。但是,做所有三件事似乎可以为我解决问题。这是一个片段: -

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.....
于 2012-01-05T15:02:31.910 回答
2

我尝试了以下方法:

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

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

于 2012-02-27T04:39:29.693 回答
1

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

response( $.map( results, function( item ) {
 if (item.formatted_address.indexOf("GB") != -1) {
    return {
      latitude: item.geometry.location.lat(),
      longitude: item.geometry.location.lng()
    }
  }
}
于 2013-04-23T07:18:54.373 回答
0

对于英国,您必须使用 GB 表示地区。英国不是ISO国家代码!

于 2011-03-24T19:44:03.797 回答
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 }

于 2014-04-24T17:04:05.963 回答
0

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

    private static string ReturnLatandLng(string GeocodeApiKey, string address)
    {
        string latlng = "";

        Geocoder geocoder = new Geocoder(GeocodeApiKey);

        var locations = geocoder.Geocode(address);

        foreach (var item in locations)
        {

            double longitude = item.LatLng.Longitude;
            double latitude = item.LatLng.Latitude;
            double borderSouthLatitude = 49.895878;
            double borderNorthLatitude = 62.000000;
            double borderWestLongitude = -8.207676;
            double borderEastLongitude = 2.000000;

            //Check If Geocoded Address is inside of the UK
            if (( (borderWestLongitude < longitude) && (longitude < borderEastLongitude) ) && ( (borderSouthLatitude < latitude) && (latitude < borderNorthLatitude) ) )
            {
                latlng = item.LatLng.ToString();
            }
            else
            {
                latlng = "";
                Console.WriteLine("GEOCODED ADDRESS IS NOT LOCATED IN UK ADDRESSES LIST. DELETING MARKER FROM MAP.....");
            }
        }
        return latlng;
    }
于 2019-03-15T11:06:19.327 回答
0

我发现对于很多模棱两可的查询,美国总是在谷歌中优先,即使你试图告诉它在哪里看。您可以查看响应,如果输出 country=US?

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

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

于 2018-04-28T12:10:17.533 回答
-1

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

这是结果中 address_components 中的 full_name。

于 2015-04-20T10:44:10.770 回答