I am calculating latitudes and longitudes from zip code.
I have installed geopy
pip install geopy
In my code:
from geopy.geocoders import GoogleV3
def get_lat_lng(zip_code):
lat, lng = False, False
geocoder = GoogleV3()
location = geocoder.geocode(query=str(zip_code))
if location:
print location
lat, lng = location.latitude, location.longitude
return lat, lng
When I call above method and I am giving zip code of Lahore,Pakistan which is 54000.
get_lat_lng(54000)
Out put of latitude and longitude is:
(46.975033, 31.994583)
Actual latitude and longitude of Lahore are
31.5546° N, 74.3572° E
And on print of location I got:
Mykolaiv, Mykolaivs'ka oblast, Ukraine, 54000
What can be issue ?
The only way I could get it to work was to use the components keyword passing a dict of country code and locality:
from geopy.geocoders import GoogleV3
def get_lat_lng(zip_code):
geocoder = GoogleV3()
location = geocoder.geocode(query=str(zip_code),components={"country": "PK","locality":"lahore"})
if location:
print location._address
lat, lng = location.latitude, location.longitude
return lat, lng
print(get_lat_lng(54000))
Which outputs:
Lahore, Pakistan
(31.55460609999999, 74.3571581)
The other option is to try the region=
keyword and/or pass the domain explicitly something other than the default maps.google.com
.
Even setting exactly_one
to False:
from geopy.geocoders import GoogleV3
def get_lat_lng(zip_code):
lat, lng = False, False
geocoder = GoogleV3()
location = geocoder.geocode(query=str(zip_code), exactly_one=False)
if location:
print [loc.address for loc in location]
print(get_lat_lng(54000))
Does not return any match.
[u"Mykolaiv, Mykolaivs'ka oblast, Ukraine, 54000", u'54000 Nancy, France', u'54000, Thailand', u'Kampung Datuk Keramat, 54000 Kuala Lumpur, Federal Territory of Kuala Lumpur, Malaysia', u'Tlalnepantla Centro, 54000 Tlalnepantla, M\xe9x., Mexico', u'54000, Broken Bow, OK 74728, USA', u'54000, Oklahoma, USA']