user3008712
user3008712

Reputation: 611

How To Get Latitude & Longitude with python

I am trying to retrieve the longitude & latitude of a physical address ,through the below script .But I am getting the error. I have already installed googlemaps.

#!/usr/bin/env python
import urllib,urllib2


"""This Programs Fetch The Address"""

from googlemaps import GoogleMaps


address='Mahatma Gandhi Rd, Shivaji Nagar, Bangalore, KA 560001'

add=GoogleMaps().address_to_latlng(address)
print add

Output:

Traceback (most recent call last):
  File "Fetching.py", line 12, in <module>
    add=GoogleMaps().address_to_latlng(address)
  File "/usr/local/lib/python2.7/dist-packages/googlemaps.py", line 310, in address_to_latlng
    return tuple(self.geocode(address)['Placemark'][0]['Point']['coordinates'][1::-1])
  File "/usr/local/lib/python2.7/dist-packages/googlemaps.py", line 259, in geocode
    url, response = fetch_json(self._GEOCODE_QUERY_URL, params=params)
  File "/usr/local/lib/python2.7/dist-packages/googlemaps.py", line 50, in fetch_json
    response = urllib2.urlopen(request)
  File "/usr/lib/python2.7/urllib2.py", line 127, in urlopen
    return _opener.open(url, data, timeout)
  File "/usr/lib/python2.7/urllib2.py", line 407, in open
    response = meth(req, response)
  File "/usr/lib/python2.7/urllib2.py", line 520, in http_response
    'http', request, response, code, msg, hdrs)
  File "/usr/lib/python2.7/urllib2.py", line 445, in error
    return self._call_chain(*args)
  File "/usr/lib/python2.7/urllib2.py", line 379, in _call_chain
    result = func(*args)
  File "/usr/lib/python2.7/urllib2.py", line 528, in http_error_default
    raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
urllib2.HTTPError: HTTP Error 403: Forbidden

Upvotes: 50

Views: 196457

Answers (11)

Hamish Anderson
Hamish Anderson

Reputation: 617

For a Python script that does not require an API key nor external libraries you can query the Nominatim service which in turn queries the Open Street Map database.

For more information on how to use it see https://nominatim.org/release-docs/develop/api/Search/

A simple example is below:

import requests
import urllib.parse

address = 'Shivaji Nagar, Bangalore, KA 560001'
url = 'https://nominatim.openstreetmap.org/search?q=' + urllib.parse.quote(address) +'&format=json'

response = requests.get(url).json()
print(response[0]["lat"])
print(response[0]["lon"])

Upvotes: 43

Nirmal Sankalana
Nirmal Sankalana

Reputation: 453

You can simply use geopy API to get longitude and latitude from address. geopy includes geocoder classes for the OpenStreetMap Nominatim, Google Geocoding API (V3), and many other geocoding services. The full list is available on the Geocoders doc section. Geocoder classes are located in geopy.geocoders. Here is the example code which I use OpenStreetMap Nominatim(Its totally free!):

from geopy.geocoders import Nominatim
Address = "757 N Chase St Athens, GA 30606"
geolocator = Nominatim(user_agent="name_of_the_agent")
location = geolocator.geocode(Address, namedetails=True)
print((location.latitude, location.longitude))

Upvotes: 0

Sayyor Y
Sayyor Y

Reputation: 1314

You can also use geocoder with Bing Maps API. The API gets latitude and longitude data for all addresses for me (unlike Nominatim which works for only 60% of addresses) and it has a pretty good free version for non-commercial uses (max 125000 requests per year for free). To get free API, go here and click "Get a free Basic key". After getting your API, you can use it in the code below:

import geocoder # pip install geocoder
g = geocoder.bing('Mountain View, CA', key='<API KEY>')
results = g.json
print(results['lat'], results['lng'])

The results contains much more information than longitude and latitude. Check it out.

Upvotes: 8

ahmedshahriar
ahmedshahriar

Reputation: 1076

Here is my solution with nominatim using geopy and positionstack API backup

Positionstack API supports upto 25,000 Requests / month for free

import requests

from geopy.geocoders import Nominatim

geolocator = Nominatim(user_agent='myapplication')

def get_nominatim_geocode(address):
    try:
      location = geolocator.geocode(address)
      return location.raw['lon'], location.raw['lat']
    except Exception as e:
        # print(e)
        return None, None

def get_positionstack_geocode(address):
  BASE_URL = "http://api.positionstack.com/v1/forward?access_key="
  API_KEY = "YOUR_API_KEY"
  
  url = BASE_URL +API_KEY+'&query='+urllib.parse.quote(address)
  try:
      response = requests.get(url).json()
      # print( response["data"][0])
      return response["data"][0]["longitude"], response["data"][0]["latitude"]
  except Exception as e:
      # print(e)
      return None,None

def get_geocode(address):
  long,lat = get_nominatim_geocode(address)
  if long == None:
    return get_positionstack_geocode(address)
  else:
    return long,lat

address = "50TH ST S"

get_geocode(address)

Output :

('-80.2581662', '26.6077474'

you can use nominatim without geopy client as well

import requests
import urllib

def get_nominatim_geocode(address):
    url = 'https://nominatim.openstreetmap.org/search/' + urllib.parse.quote(address) + '?format=json'
    try:
        response = requests.get(url).json()
        return response[0]["lon"], response[0]["lat"]
    except Exception as e:
        # print(e)
        return None, None

Upvotes: 1

Wuzardor
Wuzardor

Reputation: 149

I took a solution in this topic but it wasn't working for me so it adapt it and it worked. No token needed .

Refer you to the Doc to go further : https://nominatim.org/release-docs/latest/api/Search/

Here is the code.

import requests
import urllib.parse

city = "Paris"
country = "France"
url = "https://nominatim.openstreetmap.org/?addressdetails=1&q=" + city + "+" + country +"&format=json&limit=1"

response = requests.get(url).json()
print(response[0]["lat"])
print(response[0]["lon"])

Output :

48.8566969 2.3514616

Upvotes: 6

S.S oganja
S.S oganja

Reputation: 429

Try this code:

from geopy.geocoders import Nominatim
geolocator = Nominatim(user_agent="my_user_agent")
city ="London"
country ="Uk"
loc = geolocator.geocode(city+','+ country)
print("latitude is :-" ,loc.latitude,"\nlongtitude is:-" ,loc.longitude)

Upvotes: 28

Carles
Carles

Reputation: 2829

As @WSaitama said, geopy works well and it does not require authentification. To download it: https://pypi.org/project/geopy/. An example on how to use it would be:

from geopy.geocoders import Nominatim

address='Barcelona'
geolocator = Nominatim(user_agent="Your_Name")
location = geolocator.geocode(address)
print(location.address)
print((location.latitude, location.longitude))
#Barcelona, Barcelonès, Barcelona, Catalunya, 08001, España
#(41.3828939, 2.1774322)

Upvotes: 5

Wsaitama
Wsaitama

Reputation: 95

did you try to use the the library geopy ? https://pypi.org/project/geopy/

It works for python 2.7 till 3.8. It also work for OpenStreetMap Nominatim, Google Geocoding API (V3) and others.

Hope it can help you.

Upvotes: 2

abdoulsn
abdoulsn

Reputation: 1159

Hello here is the one I use most time to get latitude and longitude using physical adress. NB: Pleas fill NaN with empty. df.adress.fillna('')

from geopy.exc import GeocoderTimedOut
# You define col corresponding to adress, it can be one
col_addr = ['street','postcode','town']
geocode = geopy.geocoders.BANFrance().geocode  

def geopoints(row):
    search=""
    for x in col_addr:
        search = search + str(row[x]) +' '

    if search is not None:
        print(row.name+1,end="\r")
        try:
            search_location = geocode(search, timeout=5)
            return search_location.latitude,search_location.longitude
        except (AttributeError, GeocoderTimedOut):
            print("Got an error on index : ",row.name)
            return 0,0


print("Number adress to located /",len(df),":")
df['latitude'],df['longitude'] = zip(*df.apply(geopoints, axis=1))

NB: I use BANFrance() as API, you can find other API here Geocoders.

Upvotes: 5

Sunil Singh
Sunil Singh

Reputation: 303

Simplest way to get Latitude and Longitude using google api, Python and Django.

# Simplest way to get the lat, long of any address.

# Using Python requests and the Google Maps Geocoding API.

        import requests

        GOOGLE_MAPS_API_URL = 'http://maps.googleapis.com/maps/api/geocode/json'

        params = {
            'address': 'oshiwara industerial center goregaon west mumbai',
            'sensor': 'false',
            'region': 'india'
        }

        # Do the request and get the response data
        req = requests.get(GOOGLE_MAPS_API_URL, params=params)
        res = req.json()

        # Use the first result
        result = res['results'][0]

        geodata = dict()
        geodata['lat'] = result['geometry']['location']['lat']
        geodata['lng'] = result['geometry']['location']['lng']
        geodata['address'] = result['formatted_address']

    print('{address}. (lat, lng) = ({lat}, {lng})'.format(**geodata))

# Result => Link Rd, Best Nagar, Goregaon West, Mumbai, Maharashtra 400104, India. (lat, lng) = (19.1528967, 72.8371262)

Upvotes: 6

Saleem Latif
Saleem Latif

Reputation: 1520

googlemaps package you are using is not an official one and does not use google maps API v3 which is the latest one from google.

You can use google's geocode REST api to fetch coordinates from address. Here's an example.

import requests

response = requests.get('https://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA')

resp_json_payload = response.json()

print(resp_json_payload['results'][0]['geometry']['location'])

Upvotes: 59

Related Questions