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

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?

The answer is


Here's a modern solution using a promise:

function getAddress (latitude, longitude) {
    return new Promise(function (resolve, reject) {
        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) {
                if (request.status == 200) {
                    var data = JSON.parse(request.responseText);
                    var address = data.results[0];
                    resolve(address);
                }
                else {
                    reject(request.status);
                }
            }
        };
        request.send();
    });
};

And call it like this:

getAddress(lat, lon).then(console.log).catch(console.error);

The promise returns the address object in 'then' or the error status code in 'catch'


There are many tools available

  1. google maps API as like all had written
  2. use this data "https://simplemaps.com/data/world-cities" download free version and convert excel to JSON with some online converter like "http://beautifytools.com/excel-to-json-converter.php"
  3. use IP address which is not good because using IP address of someone may not good users think that you can hack them.

other free and paid tools are available also


you can do it with pure php and google geocode api

/*
 *
 * @param latlong (String) is Latitude and Longitude with , as separator for example "21.3724002,39.8016229"
 **/
function getCityNameByLatitudeLongitude($latlong)
{
    $APIKEY = "AIzaXXXXXXXXXXXXXXXXXXXXXXXXXXX"; // Replace this with your google maps api key 
    $googleMapsUrl = "https://maps.googleapis.com/maps/api/geocode/json?latlng=" . $latlong . "&language=ar&key=" . $APIKEY;
    $response = file_get_contents($googleMapsUrl);
    $response = json_decode($response, true);
    $results = $response["results"];
    $addressComponents = $results[0]["address_components"];
    $cityName = "";
    foreach ($addressComponents as $component) {
        // echo $component;
        $types = $component["types"];
        if (in_array("locality", $types) && in_array("political", $types)) {
            $cityName = $component["long_name"];
        }
    }
    if ($cityName == "") {
        echo "Failed to get CityName";
    } else {
        echo $cityName;
    }
}

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>

Following Code Works Fine to Get City Name (Using Google Map Geo API) :

HTML

<p><button onclick="getLocation()">Get My Location</button></p>
<p id="demo"></p>
<script src="http://maps.google.com/maps/api/js?key=YOUR_API_KEY"></script>

SCRIPT

var x=document.getElementById("demo");
function getLocation(){
    if (navigator.geolocation){
        navigator.geolocation.getCurrentPosition(showPosition,showError);
    }
    else{
        x.innerHTML="Geolocation is not supported by this browser.";
    }
}

function showPosition(position){
    lat=position.coords.latitude;
    lon=position.coords.longitude;
    displayLocation(lat,lon);
}

function showError(error){
    switch(error.code){
        case error.PERMISSION_DENIED:
            x.innerHTML="User denied the request for Geolocation."
        break;
        case error.POSITION_UNAVAILABLE:
            x.innerHTML="Location information is unavailable."
        break;
        case error.TIMEOUT:
            x.innerHTML="The request to get user location timed out."
        break;
        case error.UNKNOWN_ERROR:
            x.innerHTML="An unknown error occurred."
        break;
    }
}

function displayLocation(latitude,longitude){
    var geocoder;
    geocoder = new google.maps.Geocoder();
    var latlng = new google.maps.LatLng(latitude, longitude);

    geocoder.geocode(
        {'latLng': latlng}, 
        function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                if (results[0]) {
                    var add= results[0].formatted_address ;
                    var  value=add.split(",");

                    count=value.length;
                    country=value[count-1];
                    state=value[count-2];
                    city=value[count-3];
                    x.innerHTML = "city name is: " + city;
                }
                else  {
                    x.innerHTML = "address not found";
                }
            }
            else {
                x.innerHTML = "Geocoder failed due to: " + status;
            }
        }
    );
}

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 ;)


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' } ]

Same as @Sanchit Gupta.

in this part

if (results[0]) {
 var add= results[0].formatted_address ;
 var  value=add.split(",");
 count=value.length;
 country=value[count-1];
 state=value[count-2];
 city=value[count-3];
 x.innerHTML = "city name is: " + city;
}

just console the results array

if (results[0]) {
 console.log(results[0]);
 // choose from console whatever you need.
 var city = results[0].address_components[3].short_name;
 x.innerHTML = "city name is: " + city;
}

In case if you don't want to use google geocoding API than you can refer to few other Free APIs for the development purpose. for example i used [mapquest] API in order to get the location name.

you can fetch location name easily by implementing this following function

_x000D_
_x000D_
 const fetchLocationName = async (lat,lng) => {
    await fetch(
      'https://www.mapquestapi.com/geocoding/v1/reverse?key=API-Key&location='+lat+'%2C'+lng+'&outFormat=json&thumbMaps=false',
    )
      .then((response) => response.json())
      .then((responseJson) => {
        console.log(
          'ADDRESS GEOCODE is BACK!! => ' + JSON.stringify(responseJson),
        );
      });
  };
_x000D_
_x000D_
_x000D_


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'
    });
}

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to node.js

Hide Signs that Meteor.js was Used Querying date field in MongoDB with Mongoose SyntaxError: Cannot use import statement outside a module Server Discovery And Monitoring engine is deprecated How to fix ReferenceError: primordials is not defined in node UnhandledPromiseRejectionWarning: This error originated either by throwing inside of an async function without a catch block dyld: Library not loaded: /usr/local/opt/icu4c/lib/libicui18n.62.dylib error running php after installing node with brew on Mac internal/modules/cjs/loader.js:582 throw err DeprecationWarning: Buffer() is deprecated due to security and usability issues when I move my script to another server Please run `npm cache clean`

Examples related to google-maps

GoogleMaps API KEY for testing Google Maps shows "For development purposes only" java.lang.NoClassDefFoundError:failed resolution of :Lorg/apache/http/ProtocolVersion How to import JSON File into a TypeScript file? Googlemaps API Key for Localhost Getting "Cannot call a class as a function" in my React Project ERROR: Google Maps API error: MissingKeyMapError This page didn't load Google Maps correctly. See the JavaScript console for technical details Google Maps API warning: NoApiKeys ApiNotActivatedMapError for simple html page using google-places-api

Examples related to geocoding

This API project is not authorized to use this API. Please ensure that this API is activated in the APIs Console Create or update mapping in elasticsearch Getting distance between two points based on latitude/longitude Measuring the distance between two coordinates in PHP Why doesn't file_get_contents work? How can I get city name from a latitude and longitude point? Calculating Distance between two Latitude and Longitude GeoCoordinates Given the lat/long coordinates, how can we find out the city/country? Google Maps: how to get country, state/province/region, city given a lat/long value? Get latitude and longitude based on location name with Google Autocomplete API

Examples related to latitude-longitude

How to get a time zone from a location using latitude and longitude coordinates? What are the lengths of Location Coordinates, latitude and longitude? Using Address Instead Of Longitude And Latitude With Google Maps API Google Maps API - how to get latitude and longitude from Autocomplete without showing the map? Which data type for latitude and longitude? Calculating distance between two geographic locations How can I enter latitude and longitude in Google Maps? Calculate the center point of multiple latitude/longitude coordinate pairs How can I get city name from a latitude and longitude point? Calculating Distance between two Latitude and Longitude GeoCoordinates