27

I need to convert longitude and latitude coordinates to either country or city, is there an example of this in python?

thanks in advance!

5 Answers 5

35

I use Google's API.

from urllib2 import urlopen
import json
def getplace(lat, lon):
    url = "http://maps.googleapis.com/maps/api/geocode/json?"
    url += "latlng=%s,%s&sensor=false" % (lat, lon)
    v = urlopen(url).read()
    j = json.loads(v)
    components = j['results'][0]['address_components']
    country = town = None
    for c in components:
        if "country" in c['types']:
            country = c['long_name']
        if "postal_town" in c['types']:
            town = c['long_name']
    return town, country


print(getplace(51.1, 0.1))
print(getplace(51.2, 0.1))
print(getplace(51.3, 0.1))

Output:

(u'Hartfield', u'United Kingdom')
(u'Edenbridge', u'United Kingdom')
(u'Sevenoaks', u'United Kingdom')
6
  • this is great, is there a clean way to pick up city and country without using split?
    – godzilla
    Commented Nov 24, 2013 at 0:10
  • Yes, I have revised my answer to return city and country Commented Nov 24, 2013 at 0:21
  • this works fine, however is there a way of doing this locally? an api of some sort, the latency is a huge bottleneck for what i am trying to do
    – godzilla
    Commented Nov 26, 2013 at 16:23
  • 8
    For Python > 3.5 use from urllib.request import urlopen Commented Mar 27, 2018 at 6:58
  • 5
    Now google map api needs key to be able to use. I need to register for a billing account. after getting the key, I need to change the first url to url = "https://maps.googleapis.com/maps/api/geocode/json?key=YourKey&" (note: it needs to be https, not http)
    – Pengyao
    Commented Jun 3, 2019 at 23:03
13

Google has since removed keyless access to their API. Head over to google and register for a key, you get ~ 1,000 free queries a day. Code in accepted answer should be modified like this (can't add a comment, not enough rep).

from urllib.request import urlopen
import json

def getplace(lat, lon):
    key = "yourkeyhere"
    url = "https://maps.googleapis.com/maps/api/geocode/json?"
    url += "latlng=%s,%s&sensor=false&key=%s" % (lat, lon, key)
    v = urlopen(url).read()
    j = json.loads(v)
    components = j['results'][0]['address_components']
    country = town = None
    for c in components:
        if "country" in c['types']:
            country = c['long_name']
        if "postal_town" in c['types']:
            town = c['long_name']

    return town, country

print(getplace(51.1, 0.1))
print(getplace(51.2, 0.1))
print(getplace(51.3, 0.1))
12

This is called reverse geocoding. There is one library I could find in Python which is focused on this: https://github.com/thampiman/reverse-geocoder

Some related questions with other ideas:

0
8

In general the Google API is the best approach. It was not suitable for my case as I had to process a lot of entries and the api is slow.

I coded a small version that does the same but downloads a huge geometry first and computes the countries on the machine.

import requests

from shapely.geometry import mapping, shape
from shapely.prepared import prep
from shapely.geometry import Point


data = requests.get("https://raw.githubusercontent.com/datasets/geo-countries/master/data/countries.geojson").json()

countries = {}
for feature in data["features"]:
    geom = feature["geometry"]
    country = feature["properties"]["ADMIN"]
    countries[country] = prep(shape(geom))

print(len(countries))

def get_country(lon, lat):
    point = Point(lon, lat)
    for country, geom in countries.iteritems():
        if geom.contains(point):
            return country

    return "unknown"

print(get_country(10.0, 47.0))
# Austria
3
  • this pip extension is also interesting, maybe not so accurate as it is based on some reference point and does some interpolation: pypi.python.org/pypi/reverse_geocode/1.0
    – linqu
    Commented Oct 16, 2017 at 12:58
  • 4
    For Python 3 use: for country, geom in countries.items():
    – DougR
    Commented Jul 19, 2019 at 12:01
  • If you are looking for a static solution, you can actually go a step ahead and download the file mentioned in url and read it this way: with open('countries.geojson', 'w') as fp: data = json.loads(fp.read()) Commented Oct 16, 2020 at 14:52
2
# Python3 program for reverse geocoding. 

# importing necessary libraries 
import reverse_geocoder as rg 
from pandas import DataFrame
import pandas as pd

def reverseGeocode(coordinates): 
    result = rg.search(coordinates) 
    
    return result

    
# Coorinates tuple.Can contain more than one pair. 

if __name__ == "__main__":
    result = []
    path = "CSV_NAME.CSV"
    df = pd.read_csv(path, error_bad_lines=False)
    for i in range(0, len(df)):
        coordinates =(df["latitude"], df["longitude"]) 
        result.append(reverseGeocode(coordinates))
    print(result)
        
1
  • There is module in python called "reverse_geocoder" using this we can get the physical address. Try it.
    – Lokesh K V
    Commented Dec 29, 2020 at 6:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.