How can I get city name from a latitude and longitude point?

236,408

Solution 1

This is called Reverse Geocoding

Solution 2

Here is a complete sample:

<!DOCTYPE html>
<html>
  <head>
    <title>Geolocation API with Google Maps API</title>
    <meta charset="UTF-8" />
  </head>
  <body>
    <script>
      function displayLocation(latitude,longitude){
        var request = new XMLHttpRequest();

        var method = 'GET';
        var url = 'http://maps.googleapis.com/maps/api/geocode/json?latlng='+latitude+','+longitude+'&sensor=true';
        var async = true;

        request.open(method, url, async);
        request.onreadystatechange = function(){
          if(request.readyState == 4 && request.status == 200){
            var data = JSON.parse(request.responseText);
            var address = data.results[0];
            document.write(address.formatted_address);
          }
        };
        request.send();
      };

      var successCallback = function(position){
        var x = position.coords.latitude;
        var y = position.coords.longitude;
        displayLocation(x,y);
      };

      var errorCallback = function(error){
        var errorMessage = 'Unknown error';
        switch(error.code) {
          case 1:
            errorMessage = 'Permission denied';
            break;
          case 2:
            errorMessage = 'Position unavailable';
            break;
          case 3:
            errorMessage = 'Timeout';
            break;
        }
        document.write(errorMessage);
      };

      var options = {
        enableHighAccuracy: true,
        timeout: 1000,
        maximumAge: 0
      };

      navigator.geolocation.getCurrentPosition(successCallback,errorCallback,options);
    </script>
  </body>
</html>

Solution 3

In node.js we can use node-geocoder npm module to get address from lat, lng.,

geo.js

var NodeGeocoder = require('node-geocoder');

var options = {
  provider: 'google',
  httpAdapter: 'https', // Default
  apiKey: ' ', // for Mapquest, OpenCage, Google Premier
  formatter: 'json' // 'gpx', 'string', ...
};

var geocoder = NodeGeocoder(options);

geocoder.reverse({lat:28.5967439, lon:77.3285038}, function(err, res) {
  console.log(res);
});

output:

node geo.js

[ { formattedAddress: 'C-85B, C Block, Sector 8, Noida, Uttar Pradesh 201301, India',
    latitude: 28.5967439,
    longitude: 77.3285038,
    extra: 
     { googlePlaceId: 'ChIJkTdx9vzkDDkRx6LVvtz1Rhk',
       confidence: 1,
       premise: 'C-85B',
       subpremise: null,
       neighborhood: 'C Block',
       establishment: null },
    administrativeLevels: 
     { level2long: 'Gautam Buddh Nagar',
       level2short: 'Gautam Buddh Nagar',
       level1long: 'Uttar Pradesh',
       level1short: 'UP' },
    city: 'Noida',
    country: 'India',
    countryCode: 'IN',
    zipcode: '201301',
    provider: 'google' } ]

Solution 4

Here is the latest sample of Google's geocode Web Service

https://maps.googleapis.com/maps/api/geocode/json?latlng=40.714224,-73.961452&key=YOUR_API_KEY

Simply change the YOUR_API_KEY to the API key you get from Google Geocoding API

P/S: Geocoding API is under Places NOT Maps ;)

Solution 5

BigDataCloud also has a nice API for this, also for nodejs users.

they have API for client - free. But also for backend, using API_KEY (free according to quota).

Their GitHub page.

the code looks like:

const client = require('@bigdatacloudapi/client')(API_KEY);

async foo() {
    ...
    const location: string = await client.getReverseGeocode({
          latitude:'32.101786566878445', 
          longitude: '34.858965073072056'
    });
}
Share:
236,408

Related videos on Youtube

Dennis Martinez
Author by

Dennis Martinez

I enjoy JS and cars.

Updated on March 09, 2022

Comments

  • Dennis Martinez
    Dennis Martinez about 2 years

    Is there a way to get a city name from a latitude and longitude point using the google maps api for javascript?

    If so could I please see an example?

    • Deviland
      Deviland almost 13 years
      you will need to find a web service that offers this.
  • Dennis Martinez
    Dennis Martinez almost 13 years
    Awesome! I read up on this, and now the over coming of too many queries ;) thanks.
  • Vikas Verma
    Vikas Verma almost 10 years
    There is any way to find out user location from latitude and longitude without user approval ?
  • omerio
    omerio over 9 years
    @VikasVerma that would be a serious privacy breach if you are allowed to find the user location without their consent
  • Vikas Verma
    Vikas Verma over 9 years
    @omerio thanks but I made code there I forced user to click allow if he/she want to proceed.
  • Andy  Gee
    Andy Gee over 9 years
    Per IP address and per single user is the same if you're using the javascript API but if you're using PHP for example and you think you'll reach these limits you'll need to limit the requests to 1 per second or use proxy servers but be careful with proxies, google isn't stupid and you can't hammer them. More info here: developers.google.com/maps/documentation/business/articles/…
  • ydobonebi
    ydobonebi over 8 years
    This actually gave me my exact home address. Exactly what I want. How do I extract just like the city and state or zip code?
  • Ade
    Ade over 6 years
    Thanks for the very clear and working feedback, would there be any difference between choice of 'node-geocoder' and '@google/maps' ?, they appear to do the same thing though
  • KARTHIKEYAN.A
    KARTHIKEYAN.A over 6 years
    both output are same but node-geocoder is simplified module to get the address and @google/maps is api to get address in that we need to configure.
  • Georgi Tenev
    Georgi Tenev about 6 years
    This wouldn't work without an access key. The sensor parameter is obsolete too
  • Chintan Pathak
    Chintan Pathak about 4 years
    Not a javascript solution
  • Michał Tkaczyk
    Michał Tkaczyk over 3 years
    OP was asking for solution with Google Maps API, I think you're not answering the question.
  • Pankaj Chaturvedi
    Pankaj Chaturvedi over 3 years
    Sorry but i just suggested an alternative way to do so. and it does work fine if he have google geo coding api key.
  • Jorge Miguel Sanchez
    Jorge Miguel Sanchez about 2 years
    Now, you must tu use https instead of http