I\'m using Google\'s Geocoder to find lat lng coordinates for a given address.
var geocoder = new google.maps.Geocoder();
geocoder.geocode(
{
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;
}
}
}
}
});
For the united kingdom, you have to use GB for region. UK is not the ISO country code!
According to the docs, the region parameter seems to set a bias only (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.
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 bounds
parameter. See here
You would have to calculate a UK-sized rectangle for that, of course.
I tried with the following:
geocoder.geocode( {'address':request.term + ', USA'}
And its working for me for particular region (US country).
I had to filter results to a country myself today. I found out that the two character country code in componentRestrictions:country: does not work. But the full country name does.
This is the full_name in the address_components from a result.
The correct way of doing this is by providing componentRestrictions
For example:
var request = {
address: address,
componentRestrictions: {
country: 'UK'
}
}
geocoder.geocode(request, function(results, status){
//...
});