Is there an easy way to get the name of the country on whose territory a given point is located?
I don\'t care too much about accuracy nor about ambiguities given by
Here's some JavaScript code to get the name of the country from latitude and longitude coordinates:
Using Google's geocoding services [jsfiddle]:
var lookupCountryWithGoogle = function(lat, lng) { var latlng = new google.maps.LatLng(lat, lng);
var geoCoder = new google.maps.Geocoder();
geoCoder.geocode({
location: latlng
}, function(results, statusCode) {
var lastResult = results.slice(-1)[0];
if (statusCode == 'OK' && lastResult && 'address_components' in lastResult) {
alert('coordinates: ' + lat + ', ' + lng + '\n' + 'country: ' + lastResult.address_components.slice(-1)[0].long_name);
} else {
alert('coordinates: ' + lat + ', ' + lng + '\n' + 'failed: ' + statusCode);
}
});
};
lookupCountryWithGoogle(43.7534932, 28.5743187); // will succeed lookupCountryWithGoogle(142, 124); // will fail
(You'll need to load Google's JavaScript support for this from a URL such as maps.google.com/maps/api/js?sensor=false&fake=.js)
Using ws.geonames.org [jsfiddle]:
var lookupCountryWithGeonames = function(lat, lng) {
$.getJSON('http://ws.geonames.org/countryCode', {
lat: lat,
lng: lng,
type: 'JSON'
}, function(results) {
if (results.countryCode) {
alert('coordinates: ' + lat + ', ' + lng + '\n' + 'country: ' + results.countryName);
} else {
alert('coordinates: ' + lat + ', ' + lng + '\n' + 'failed: ' + results.status.value + ' ' + results.status.message);
}
});
};
lookupCountryWithGeonames(43.7534932, 28.5743187); // will succeed
lookupCountryWithGeonames(142, 124); // will fail