Finding Longitude & Latitude based on IP
Fri 12 December 2014
Filed under Python
Once I had the IP, I needed to find the longitude & latitude coordinates
On that recent project I was working on, I was looking for the local weather based on where the user is located. So first, I got the IP. With that IP, I used pygeoip.GeoIP to find the longitude and latitude coordinates. Later, I will use those coordinates to find the local weather.
First, I downloaded the GeoIP data from https://pypi.python.org/pypi/pygeoip/ and unzipped it. And saved the GeoLiteCity.dat on my local server.
I also had to
pip install pygeoip.
Here's the code:
import pygeoip geoip_data = pygeoip.GeoIP('/path/GeoLiteCity.dat') def find_lat_lng(ip): data = geoip_data.record_by_addr(ip) lat = data['latitude'] lng = data['longitude'] return lat, lng
data: In this case, I used the record_by_addr(addr) attribute since I had the addr, the IP. And I want the full record.
There are many other attributes you can use with this geoip data. Checkout more at: http://pygeoip.readthedocs.org/en/v0.3.2/api-reference.html
data is a dictionary. And I called the
longitude keys of
data to find the values of
lng, I will be able to get the weather for those coordinates. Using forecast_io. More on that next time.