[geolocation] Given the lat/long coordinates, how can we find out the city/country?

For example if we have these set of coordinates

"latitude": 48.858844300000001,
"longitude": 2.2943506,

How can we find out the city/country?

This question is related to geolocation geocoding geospatial geo

The answer is


You need geopy

pip install geopy

and then:

from geopy.geocoders import Nominatim
geolocator = Nominatim()
location = geolocator.reverse("48.8588443, 2.2943506")

print(location.address)

to get more information:

print (location.raw)

{'place_id': '24066644', 'osm_id': '2387784956', 'lat': '41.442115', 'lon': '-8.2939909', 'boundingbox': ['41.442015', '41.442215', '-8.2940909', '-8.2938909'], 'address': {'country': 'Portugal', 'suburb': 'Oliveira do Castelo', 'house_number': '99', 'city_district': 'Oliveira do Castelo', 'country_code': 'pt', 'city': 'Oliveira, São Paio e São Sebastião', 'state': 'Norte', 'state_district': 'Ave', 'pedestrian': 'Rua Doutor Avelino Germano', 'postcode': '4800-443', 'county': 'Guimarães'}, 'osm_type': 'node', 'display_name': '99, Rua Doutor Avelino Germano, Oliveira do Castelo, Oliveira, São Paio e São Sebastião, Guimarães, Braga, Ave, Norte, 4800-443, Portugal', 'licence': 'Data © OpenStreetMap contributors, ODbL 1.0. http://www.openstreetmap.org/copyright'}

Minimize the amount of libraries.

Get a key to use the api at their website and just get the result in a http request:

curl -i -H "key: YOUR_KEY" -X GET https://api.latlong.dev/lookup?lat=38.7447913&long=-9.1625173

I've used Geocoder, a good Python library that supports multiple providers, including Google, Geonames, and OpenStreetMaps, to mention just a few. I've tried using the GeoPy library, and it often gets timeouts. Developing your own code for GeoNames is not the best use of your time and you may end up getting unstable code. Geocoder is very simple to use in my experience, and has good enough documentation. Below is some sample code for looking up city by latitude and longitude, or finding latitude/longitude by city name.

import geocoder

g = geocoder.osm([53.5343609, -113.5065084], method='reverse')
print g.json['city'] # Prints Edmonton

g = geocoder.osm('Edmonton, Canada')
print g.json['lat'], g.json['lng'] # Prints 53.5343609, -113.5065084

I spent about an 30min trying to find a code example of how to do this in Javascript. I couldn't find a quick clear answer to the question you posted. So... I made my own. Hopefully people can use this without having to go digging into the API or staring at code they have no idea how to read. Ha if nothing else I can reference this post for my own stuff.. Nice question and thanks for the forum of discussion!

This is utilizing the Google API.

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?key=<YOURGOOGLEKEY>&sensor=false&v=3&libraries=geometry"></script>

.

//CHECK IF BROWSER HAS HTML5 GEO LOCATION
if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function (position) {

        //GET USER CURRENT LOCATION
        var locCurrent = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);

        //CHECK IF THE USERS GEOLOCATION IS IN AUSTRALIA
        var geocoder = new google.maps.Geocoder();
            geocoder.geocode({ 'latLng': locCurrent }, function (results, status) {
                var locItemCount = results.length;
                var locCountryNameCount = locItemCount - 1;
                var locCountryName = results[locCountryNameCount].formatted_address;

                if (locCountryName == "Australia") {
                    //SET COOKIE FOR GIVING
                    jQuery.cookie('locCountry', locCountryName, { expires: 30, path: '/' }); 
                }
        });
    }
}

I was searching for a similar functionality and I saw the data "http://download.geonames.org/export/dump/" shared on earlier reply (thank you for sharing, it is an excellent source), and implemented a service based on the cities1000.txt data.

You can see it running at http://scatter-otl.rhcloud.com/location?lat=36&long=-78.9 (broken link) Just change the latitude and longitude for your locations.

It is deployed on OpenShift (RedHat Platform). First call after a long idle period may take sometime, but usually performance is satisfactory. Feel free to use this service as you like...

Also, you can find the project source at https://github.com/turgos/Location.


Please check the below answer. It works for me

if(navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(position){

        initialize(position.coords.latitude,position.coords.longitude);
    }); 
}

function initialize(lat,lng) {
    //directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);
    //directionsService = new google.maps.DirectionsService();
    var latlng = new google.maps.LatLng(lat, lng);

    //alert(latlng);
    getLocation(latlng);
}

function getLocation(latlng){

    var geocoder = new google.maps.Geocoder();
    geocoder.geocode({'latLng': latlng}, function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                if (results[0]) {
                    var loc = getCountry(results);
                    alert("location is::"+loc);
                }
            }
        });

}

function getCountry(results)
{
    for (var i = 0; i < results[0].address_components.length; i++)
    {
        var shortname = results[0].address_components[i].short_name;
        var longname = results[0].address_components[i].long_name;
        var type = results[0].address_components[i].types;
        if (type.indexOf("country") != -1)
        {
            if (!isNullOrWhitespace(shortname))
            {
                return shortname;
            }
            else
            {
                return longname;
            }
        }
    }

}

function isNullOrWhitespace(text) {
    if (text == null) {
        return true;
    }
    return text.replace(/\s/gi, '').length < 1;
}

Loc2country is a Golang based tool that returns the ISO alpha-3 country code for given location coordinates (lat/lon). It responds in microseconds. It uses a geohash to country map.

The geohash data is generated using georaptor.

We use geohash at level 6 for this tool, i.e., boxes of size 1.2km x 600m.


An Open Source alternative is Nominatim from Open Street Map. All you have to do is set the variables in an URL and it returns the city/country of that location. Please check the following link for official documentation: Nominatim


If you are using Google's Places API, this is how you can get country and city from the place object using Javascript:

function getCityAndCountry(location) {
  var components = {};
  for(var i = 0; i < location.address_components.length; i++) {
    components[location.address_components[i].types[0]] = location.address_components[i].long_name;
  }

  if(!components['country']) {
    console.warn('Couldn\'t extract country');
    return false;
  }

  if(components['locality']) {
    return [components['locality'], components['country']];
  } else if(components['administrative_area_level_1']) {
    return [components['administrative_area_level_1'], components['country']];
  } else {
    console.warn('Couldn\'t extract city');
    return false;
  }
}

I know this question is really old, but I have been working on the same issue and I found an extremely efficient and convenient package, reverse_geocoder, built by Ajay Thampi. The code is available here. It based on a parallelised implementation of K-D trees which is extremely efficient for large amounts of points (it took me few seconds to get 100,000 points.

It is based on this database, already highlighted by @turgos.

If your task is to quickly find the country and city of a list of coordinates, this is a great tool.


Another option:

  • Download the cities database from http://download.geonames.org/export/dump/
  • Add each city as a lat/long -> City mapping to a spatial index such as an R-Tree (some DBs also have the functionality)
  • Use nearest-neighbour search to find the closest city for any given point

Advantages:

  • Does not depend on an external server to be available
  • Very fast (easily does thousands of lookups per second)

Disadvantages:

  • Not automatically up to date
  • Requires extra code if you want to distinguish the case where the nearest city is dozens of miles away
  • May give weird results near the poles and the international date line (though there aren't any cities in those places anyway

It really depends on what technology restrictions you have.

One way is to have a spatial database with the outline of the countries and cities you are interested in. By outline I mean that countries and cities are store as the spatial type polygon. Your set of coordinates can be converted to the spatial type point and queried against the polygons to get the country/city name where the point is located.

Here are some of the databases which support spatial type: SQL server 2008, MySQL, postGIS - an extension of postgreSQL and Oracle.

If you would like to use a service in stead of having your own database for this you can use Yahoo's GeoPlanet. For the service approach you might want to check out this answer on gis.stackexchange.com, which covers the availability of services for solving your problem.


You can use Google Geocoding API

Bellow is php function that returns Adress, City, State and Country

public function get_location($latitude='', $longitude='')
{
    $geolocation = $latitude.','.$longitude;
    $request = 'http://maps.googleapis.com/maps/api/geocode/json?latlng='.$geolocation.'&sensor=false'; 
    $file_contents = file_get_contents($request);
    $json_decode = json_decode($file_contents);
    if(isset($json_decode->results[0])) {
        $response = array();
        foreach($json_decode->results[0]->address_components as $addressComponet) {
            if(in_array('political', $addressComponet->types)) {
                    $response[] = $addressComponet->long_name; 
            }
        }

        if(isset($response[0])){ $first  =  $response[0];  } else { $first  = 'null'; }
        if(isset($response[1])){ $second =  $response[1];  } else { $second = 'null'; } 
        if(isset($response[2])){ $third  =  $response[2];  } else { $third  = 'null'; }
        if(isset($response[3])){ $fourth =  $response[3];  } else { $fourth = 'null'; }
        if(isset($response[4])){ $fifth  =  $response[4];  } else { $fifth  = 'null'; }


        $loc['address']=''; $loc['city']=''; $loc['state']=''; $loc['country']='';
        if( $first != 'null' && $second != 'null' && $third != 'null' && $fourth != 'null' && $fifth != 'null' ) {
            $loc['address'] = $first;
            $loc['city'] = $second;
            $loc['state'] = $fourth;
            $loc['country'] = $fifth;
        }
        else if ( $first != 'null' && $second != 'null' && $third != 'null' && $fourth != 'null' && $fifth == 'null'  ) {
            $loc['address'] = $first;
            $loc['city'] = $second;
            $loc['state'] = $third;
            $loc['country'] = $fourth;
        }
        else if ( $first != 'null' && $second != 'null' && $third != 'null' && $fourth == 'null' && $fifth == 'null' ) {
            $loc['city'] = $first;
            $loc['state'] = $second;
            $loc['country'] = $third;
        }
        else if ( $first != 'null' && $second != 'null' && $third == 'null' && $fourth == 'null' && $fifth == 'null'  ) {
            $loc['state'] = $first;
            $loc['country'] = $second;
        }
        else if ( $first != 'null' && $second == 'null' && $third == 'null' && $fourth == 'null' && $fifth == 'null'  ) {
            $loc['country'] = $first;
        }
      }
      return $loc;
}

Examples related to geolocation

getCurrentPosition() and watchPosition() are deprecated on insecure origins Can we locate a user via user's phone number in Android? What is meaning of negative dbm in signal strength? How to get current location in Android Google API for location, based on user IP address How to get a time zone from a location using latitude and longitude coordinates? How to display my location on Google Maps for Android API v2 Getting visitors country from their IP Does GPS require Internet? How to calculate distance from Wifi router using Signal Strength?

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 geospatial

Given the lat/long coordinates, how can we find out the city/country? Find nearest latitude/longitude with an SQL query Converting from longitude\latitude to Cartesian coordinates

Examples related to geo

How to define object in array in Mongoose schema correctly with 2d geo index Getting distance between two points based on latitude/longitude Calculate the center point of multiple latitude/longitude coordinate pairs Given the lat/long coordinates, how can we find out the city/country? How to convert latitude or longitude to meters?