Javascript 谷歌的地理编码器返回错误的国家,忽略区域提示
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2647086/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Google's Geocoder returns wrong country, ignoring the region hint
提问by 6bytes
I'm using Google's Geocoder to find lat lng coordinates for a given address.
我正在使用 Google 的地理编码器来查找给定地址的经纬度坐标。
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()
});
addressvariable is taken from an input field.
address变量取自输入字段。
I want to search locations only in UK. I thought that specifying 'region': 'uk'should be enough but it's not. When I type in "Boston" it's finding Boston in US and I wanted the one in UK.
我只想在英国搜索位置。我认为指定'region': 'uk'应该足够了,但事实并非如此。当我输入“波士顿”时,它会在美国找到波士顿,而我想要在英国找到一个。
How to restrict Geocoder to return locations only from one country or maybe from a certain lat lng range?
如何限制地理编码器仅返回一个国家或某个纬度范围内的位置?
Thanks
谢谢
采纳答案by Daniel Vassallo
UPDATE:This answer may not be the best approach anymore. See the comments below the answer for more details.
更新:这个答案可能不再是最好的方法了。有关更多详细信息,请参阅答案下方的评论。
In addition to what Pekka already suggested, you may want to concatenate ', UK'to your address, as in the following example:
除了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>
Screenshot:
截屏:


I find that this is very reliable. On the other hand, the following example shows that neither the regionparameter, nor the boundsparameter, are having any effect in this case:
我发现这是非常可靠的。另一方面,以下示例表明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>
回答by Yenya
Use componentRestrictionsattribute:
geocoder.geocode({'address': request.term, componentRestrictions: {country: 'GB'}}
回答by Ivo Bosticky
The following code will get the first matching address in the UK without the need to modify the address.
以下代码将获取英国第一个匹配地址,无需修改地址。
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;
}
}
}
}
});
回答by Deminetix
The correct way of doing this is by providing componentRestrictions
这样做的正确方法是提供componentRestrictions
For example:
例如:
var request = {
address: address,
componentRestrictions: {
country: 'UK'
}
}
geocoder.geocode(request, function(results, status){
//...
});
回答by Pekka
According to the docs, the region parameter seems to set a biasonly (instead of a real limit to that region). I guess when the API doesn't find the exact address in the UK place, it will expand it search no matter what region you enter.
根据docs, region 参数似乎只设置了一个偏差(而不是对该区域的真正限制)。我猜当 API 在英国地方找不到确切地址时,无论您输入哪个地区,它都会扩展搜索。
I've fared pretty well in the past with specifying the country code in the address(in addition to the region). I haven't had much experience with identical place names in different countries yet, though. Still, it's worth a shot. Try
过去,我在地址中指定国家/地区代码(除了地区之外)做得很好。不过,我还没有在不同国家/地区使用相同地名的经验。尽管如此,还是值得一试。尝试
'address': '78 Austin Street, Boston, UK'
it should return no address(Instead of the US Boston), and
它不应该返回地址(而不是美国波士顿),并且
'address': '78 Main Street, Boston, UK'
Should return the Boston in the UK because that actually has a Main Street.
应该返回英国的波士顿,因为那里实际上有一条主街。
Update:
更新:
How to restrict Geocoder to return locations only from one country or maybe from a certain lat lng range?
如何限制地理编码器仅返回一个国家或某个纬度范围内的位置?
You can set a boundsparameter. See here
您可以设置一个bounds参数。看这里
You would have to calculate a UK-sized rectangle for that, of course.
当然,您必须为此计算一个英国大小的矩形。
回答by nickthompson
I found problems with putting ",UK", setting the region to UK and setting bounds. However, doing ALL THREE seems to fix it for me. Here's a snippet:-
我发现放置“,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.....
回答by Ankit Adlakha
I tried with the following:
我尝试了以下内容:
geocoder.geocode( {'address':request.term + ', USA'}
And its working for me for particular region (US country).
它在特定地区(美国国家)为我工作。
回答by bokor
I always found this to be pretty easy to filter through since the results can vary and the region doesn't seem to work.
我总是发现这很容易过滤,因为结果可能会有所不同,而且该区域似乎不起作用。
response( $.map( results, function( item ) {
if (item.formatted_address.indexOf("GB") != -1) {
return {
latitude: item.geometry.location.lat(),
longitude: item.geometry.location.lng()
}
}
}
回答by Ervin Ruci
I find that for a lot of ambiguous queries, the US always takes precedence in Google, even if you try to tell it where to look. You can look at the response and perhaps ignore it if output country=US?
我发现对于很多模棱两可的查询,美国总是优先考虑谷歌,即使你试图告诉它去哪里找。如果输出国家/地区=美国,您可以查看响应并可能忽略它?
That is the main reason I stopped using Google Geocoder a while ago and started building my own two years ago.
这就是我不久前停止使用 Google Geocoder 并在两年前开始构建自己的地理编码器的主要原因。
https://geocode.xyz/Boston,%20UKwill always return the UK location. You can make extra sure by adding region=UK: https://geocode.xyz/Boston,%20UK?region=UK
https://geocode.xyz/Boston,%20UK将始终返回英国位置。您可以通过添加 region=UK 来更加确定:https: //geocode.xyz/Boston,%20UK?region=UK
回答by mateusz stacel
I have Created Border All Around Uk and check if my Lat and Lng are in the Range. For 3 k addresses I have around 10 up to 20 addresses in US. I just Ignore them(I can do that in my case) I use lat and lng for creating multi markers on static map with auto zoom. I will share my Solution maybe this will be help for someone. Also I'm Happy to hear different Solutions for my case.
我已经在英国各地创建了边界,并检查我的 Lat 和 Lng 是否在范围内。对于 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;
}

