Home » How to Get the geolocation data in Python

How to Get the geolocation data in Python

by maxguy71

In this article we look at  a python library for

geopy is a Python client for several popular geocoding web services.

geopy makes it easy for Python developers to locate the coordinates of addresses, cities, countries, and landmarks across the globe using third-party geocoders and other data sources.

Examples

This is a basic example

from geopy.geocoders import Nominatim  
geo_locator = Nominatim(user_agent = "geoapitest")

place_1 = "1964 Independence Ave SW"
location = geo_locator.geocode(place_1)  

print(location.address)
print(location.latitude, location.longitude)

data_1 = location.raw  
print (data_1)  
location_data = data_1['display_name'].split()  
print ("\nThe Full Location is: ")  
print (location_data)  
print ("The Zip code of the location is: ", location_data[-3])  

This is what i saw

>>> %Run geopyexample.py
World War II Memorial, 1964, Independence Avenue Southwest, Washington, District of Columbia, 20227, United States
38.88939505 -77.04030796874613
{'place_id': 117595764, 'licence': 'Data © OpenStreetMap contributors, ODbL 1.0. https://osm.org/copyright', 'osm_type': 'way', 'osm_id': 66418767, 'boundingbox': ['38.8888538', '38.889936', '-77.0410642', '-77.0395553'], 'lat': '38.88939505', 'lon': '-77.04030796874613', 'display_name': 'World War II Memorial, 1964, Independence Avenue Southwest, Washington, District of Columbia, 20227, United States', 'class': 'tourism', 'type': 'attraction', 'importance': 0.7129612447715932, 'icon': 'https://nominatim.openstreetmap.org/ui/mapicons//poi_point_of_interest.p.20.png'}

The Full Location is: 
['World', 'War', 'II', 'Memorial,', '1964,', 'Independence', 'Avenue', 'Southwest,', 'Washington,', 'District', 'of', 'Columbia,', '20227,', 'United', 'States']
The Zip code of the location is:  20227,

coordinates example

To find the address corresponding to a set of coordinates:

from geopy.geocoders import Nominatim  
geo_locator = Nominatim(user_agent = "geoapitest")

location = geo_locator.reverse("38.88939505, -77.04030796874613")

print(location.address)

This is what i saw

>>> %Run geopycoords.py
World War II Memorial, 1964, Independence Avenue Southwest, Washington, District of Columbia, 20227, United States

Measure distance example

To find the address corresponding to a set of coordinates:

from geopy.distance import geodesic

newyork_ny = (40.7127281, -74.0060152)
sanfrancisco_ca = (37.15587905455899, -122.20509662089846)

print(geodesic(newyork_ny, sanfrancisco_ca).miles)

This is what i saw

>>> %Run geopydistance.py
2575.809071609786

Links

github code link

documentation link

You may also like

Leave a Comment

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More