Skip to content

Instantly share code, notes, and snippets.

@aslamdoctor
Forked from AmirHossein/coordinatestoname.js
Created December 27, 2022 03:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aslamdoctor/c04bf1739d87dbe6a1c77e9c9ad5ff16 to your computer and use it in GitHub Desktop.
Save aslamdoctor/c04bf1739d87dbe6a1c77e9c9ad5ff16 to your computer and use it in GitHub Desktop.
Get City and Country name by coordinates via Google Maps api
// Demo: http://jsfiddle.net/xuyp8qb5/
// Note: You need Google Map API Key to run demo; bit.ly/2pBgToW
var latlng;
latlng = new google.maps.LatLng(40.730885, -73.997383); // New York, US
//latlng = new google.maps.LatLng(37.990849233935194, 23.738339349999933); // Athens, GR
//latlng = new google.maps.LatLng(48.8567, 2.3508); // Paris, FR
//latlng = new google.maps.LatLng(47.98247572667902, -102.49018710000001); // New Town, US
//latlng = new google.maps.LatLng(35.44448406385493, 50.99001635390618); // Parand, Tehran, IR
//latlng = new google.maps.LatLng(34.66431108560504, 50.89113940078118); // Saveh, Markazi, IR
new google.maps.Geocoder().geocode({'latLng' : latlng}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
var country = null, countryCode = null, city = null, cityAlt = null;
var c, lc, component;
for (var r = 0, rl = results.length; r < rl; r += 1) {
var result = results[r];
if (!city && result.types[0] === 'locality') {
for (c = 0, lc = result.address_components.length; c < lc; c += 1) {
component = result.address_components[c];
if (component.types[0] === 'locality') {
city = component.long_name;
break;
}
}
}
else if (!city && !cityAlt && result.types[0] === 'administrative_area_level_1') {
for (c = 0, lc = result.address_components.length; c < lc; c += 1) {
component = result.address_components[c];
if (component.types[0] === 'administrative_area_level_1') {
cityAlt = component.long_name;
break;
}
}
} else if (!country && result.types[0] === 'country') {
country = result.address_components[0].long_name;
countryCode = result.address_components[0].short_name;
}
if (city && country) {
break;
}
}
console.log("City: " + city + ", City2: " + cityAlt + ", Country: " + country + ", Country Code: " + countryCode);
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment