Find Latitude & Longitude from Address

Karpagam Balasubramaniam
2 min readMay 17, 2020

--

Using python to hit OSM to find coordinates given address

We can easily find Latitude and Longitude from Address using the Request Module from Python.

There is a site http://photon.komoot.de/ which is made of OpenStreetMap which lets us make query using the api call from python.

Perquisites of this will require that you have got requests package installed with python.

If you haven’t installed please install using the following.

#From terminal
pip3 install requests
#From Jupyter
import sys
!{sys.executable} -m pip install requests

In here, I have a file (Example.csv) with column Adresse and i have read the file into python Dataframe.

import pandas as pd
df = pd.read_csv('Example.csv')

The data in Example.csv looks like below.

The piece of code below takes the values in the column ‘Adresse’ and finds the latitude and longitude by firing the api query to photon using requests.

It returns the Json dumps containing the features. One of the feature in the features is the geometry which is the list of latitude and longitude.

import requestsdef find_geocode(address):
url = 'http://photon.komoot.de/api/?q='
print(address)
resp = requests.get(url=url+address)
data = json.loads(resp.text)
if('features' in data.keys()):
if(not data['features']):
print(address," not found")
coord = '0,0'
else:
long,lat = data['features'][0]['geometry']['coordinates']
coord = str(lat) + ',' + str(long)
print(coord)
else:
print("Features Not found")
coord = '0,0'
return(coord)

df['coord']=df.apply(lambda row:find_geocode(row['Adresse']),axis=1)

The resultant DataFrame will have a column ‘coord’ which is latitude, longitude corresponding to the addresses.

I have assigned 0,0 for the Addresses which the query could not find the geometry for.

Please note that the address in my example also contains special character and that does not affect the query.

--

--