Skip to content

Instantly share code, notes, and snippets.

@AmirHossein
Last active December 25, 2023 11:15
Show Gist options
  • Save AmirHossein/92a0597b5f723b19c648 to your computer and use it in GitHub Desktop.
Save AmirHossein/92a0597b5f723b19c648 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);
}
}
});
@marciano1
Copy link

Strange you only have 1 request/day. Google gives me usd 200 every month and after that 1000 requests cost $5 or something like that.
I only am having few requests/month with Maps api in a private photo family website. Photos uploaded with geodata are able to display the place in a map where they were taken. Now I'd like to add more data below thumbnails like Place, Street, Region, City, State and Country at most. As I explain in that support.google.com question JS loads a lot of geo info but I cannot use it because an error I don't know how to fix Unexpected token ':'. Parse error. I google that error msg but didn't find anything useful. Anyway thanks for your help.

@AmirHossein
Copy link
Author

@marciano1 i can't tell anything without codes. You have to find Unexpected token character...

@marciano1
Copy link

@marciano1
Copy link

@AmirHossein I also have posted https://stackoverflow.com/questions/57128263/reverse-geolocation-loading-api-geocode-i-get-syntaxerror-unexpected-token but I didn't get even a comment.
Your code works okay for me. I'd ask you please to reformulate JS to only get the output of "formatted_address".
From Safari/debugger/sources/Geocode.service.search I see lot of data loaded but formatted_address is a good summary for me: Thank you!

@AmirHossein
Copy link
Author

@marciano1 As i told you i have a valid api key to check and develop code. Send me an email if you could share more details.

@marciano1
Copy link

marciano1 commented Jul 23, 2019 via email

@mubin986
Copy link

mubin986 commented Mar 9, 2020

Thank you brother!

@AppWajih
Copy link

Thanks

@kdhivakaran
Copy link

HI guys is there any possible for getting specific city based area search using google maps auto complete fields. Kindly Help me this

@archie-bryann
Copy link

archie-bryann commented Jul 31, 2020

Thanks. Really helpful.

@natashajaved
Copy link

in some cases locality doesn't have the city as per the google documentation, how to tackle that

@hoodasaad
Copy link

Thanks, Really helpful. ^_^

@rami1973
Copy link

Great Code ,can we find neighborhood and street

@i-yusuf
Copy link

i-yusuf commented Jan 4, 2022

Map & Filter Types

const GEOCODE_API = 'https://maps.googleapis.com/maps/api/geocode/json';
const GEOCODE_KEY = 'YOUR_API_KEY';

export default async function (position) {
  try {
    const coords = `${position.latitude}, ${position.longitude}`;
    const url = `${GEOCODE_API}?latlng=${coords}&key=${GEOCODE_KEY}`;

    const types = {
      // https://developers.google.com/maps/documentation/places/web-service/supported_types#table2
      administrative_area_level_1: 'custom_1',
      administrative_area_level_2: 'custom_2',
      country: 'custom_3',
      postal_code: 'custom_4',
    };

    const response = await axios.get(url);

    if (response.data.status === 'OK') {
      const result = {};

      if (response.data.results[0]) {
        if (response.data.results[0].address_components) {
          response.data.results[0].address_components.map(address => {
            if (address.types[0]) {
              if (types[address.types[0]]) {
                result[types[address.types[0]]] = address.long_name;
              }
            }
          });
        }
      }

      return result;
    }
  } catch (e) {
    console.log(e);
  }
}

Output:

{
    "custom_1": "California",
    "custom_2": "Santa Clara County",
    "custom_3": "Amerika Birleşik Devletleri",
    "custom_4": "94043"
}

Default

export default async function (position) {
  try {
    const coords = `${position.latitude}, ${position.longitude}`;
    const url = `${GEOCODE_API}?latlng=${coords}&key=${GEOCODE_KEY}`;

    const response = await axios.get(url);

    if (response.data.status === 'OK') {
      const result = {};

      if (response.data.results[0]) {
        if (response.data.results[0].address_components) {
          response.data.results[0].address_components.map(address => {
            if (address.types[0]) {
              result[address.types[0]] = address.long_name;
            }
          });
        }
      }

      return result;
    }
  } catch (e) {
    console.log(e);
  }
}

Output:

{
    "street_number": "1600",
    "route": "Amphitheatre Parkway",
    "locality": "Mountain View",
    "administrative_area_level_2": "Santa Clara County",
    "administrative_area_level_1": "California",
    "country": "Amerika Birleşik Devletleri",
    "postal_code": "94043"
}

Fetch All & Map & Filter Types

export default async function (position) {
  try {
    const coords = `${position.latitude}, ${position.longitude}`;
    const url = `${GEOCODE_API}?latlng=${coords}&key=${GEOCODE_KEY}`;

    const response = await axios.get(url);

    const types = {
      administrative_area_level_1: '_administrative_area_level_1',
      administrative_area_level_2: '_administrative_area_level_2',
      country: '_country',
      locality: '_locality',
      plus_code: '_plus_code',
      postal_code: '_postal_code',
      premise: '_premise',
      route: '_route',
      street_number: '_street_number',
    };

    if (response.data.status) {
      const output = {};
      if (response.data.results.length > 0) {
        response.data.results.map(result => {
          if (result.address_components.length > 0) {
            result.address_components.map(address => {
              if (address.types[0]) {
                if (types[address.types[0]]) {
                  if (!output[types[address.types[0]]]) {
                    output[types[address.types[0]]] = address.long_name;
                  }
                }
              }
            });
          }
        });
      }

      return output;
    }
  } catch (e) {
    console.log(e);
  }
}

Output:

{
    "_street_number": "1600",
    "_route": "Amphitheatre Parkway",
    "_locality": "Mountain View",
    "_administrative_area_level_2": "Santa Clara County",
    "_administrative_area_level_1": "California",
    "_country": "Amerika Birleşik Devletleri",
    "_postal_code": "94043",
    "_premise": "Google Building 40",
    "_plus_code": "CWC8+Q9"
}

@Feeeliperesende
Copy link

Thank you brother!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment