How To Get Latitude & Longitude with python

121,079

Solution 1

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'])

Solution 2

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/' + urllib.parse.quote(address) +'?format=json'

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

Solution 3

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)

Solution 4

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)

Solution 5

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.

Share:
121,079

Related videos on Youtube

user3008712
Author by

user3008712

Updated on July 09, 2022

Comments

  • user3008712
    user3008712 almost 2 years

    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 . kindly reply Thanks In Advance

    #!/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
    
  • Doing Things Occasionally
    Doing Things Occasionally almost 6 years
    Would this be in your views or in models? Also, if I wanted to store the lat and long in a field how would I do that?
  • edesz
    edesz almost 5 years
    This answer does require an API key.
  • Christoph Lösch
    Christoph Lösch over 4 years
    this also needs an api-key which must be set in params like 'key': 'AIza...'
  • 89f3a1c
    89f3a1c over 4 years
    Why would you need Django?
  • Mostafa Ghadimi
    Mostafa Ghadimi over 4 years
    It doesn't support utf-8 characters. It's just suitable for latin. Is there any way to make that work for utf-8?
  • Wsaitama
    Wsaitama about 4 years
    Moreover, it's very easy to use it
  • Tommy Lees
    Tommy Lees about 4 years
    is the API key free or does it cost ?
  • saran3h
    saran3h about 4 years
    As far as i know, this needs a key to work and is chargeable. I wish there was a free solution.
  • Santiago
    Santiago almost 4 years
    Would you give a little explanation of how it works?
  • Hamish Anderson
    Hamish Anderson about 3 years
    See answers below for a free solution without an api key.
  • Prateek
    Prateek over 2 years
    If you have an API key, add it in the end of the URL like this response = requests.get('https://maps.googleapis.com/maps/api/geocode/j‌​son?address=1600+Amp‌​hitheatre+Parkway,+M‌​ountain+View,+CA&key‌​=<YOUR_KEY>')
  • naaman
    naaman over 2 years
    Read up on the Usage Policy for this API before selecting the Nominatim/OSM API: operations.osmfoundation.org/policies/nominatim
  • x0xRumbleLorex0x
    x0xRumbleLorex0x over 2 years
    Just a warning for those who use this snippet, it's doesn't always produce a response. Just so I can save you guys some time.
  • Mudit Bhatia
    Mudit Bhatia over 2 years
    You have no idea how helpful is this... Thanks...
  • Frank Jimenez
    Frank Jimenez almost 2 years
    This doesn't work great with normal locations, I've tried with a list of addresses and get a fair amount of NoneType.