web-dev-qa-db-fra.com

Comment obtenir la latitude et la longitude avec python

J'essaie de récupérer la longitude et la latitude d'une adresse physique, via le script ci-dessous, mais j'obtiens l'erreur. J'ai déjà installé des googlemaps. merci de bien vouloir répondre à l'avance

#!/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

Sortie:

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
23
user3008712

le package googlemaps que vous utilisez n'est pas officiel et n'utilise pas google maps API v3 qui est le dernier de google.

Vous pouvez utiliser geocode REST api de google pour récupérer les coordonnées de l'adresse. Voici un exemple.

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'])
43
Saleem Latif

Essayez ce code: -

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

Moyen le plus simple d'obtenir la latitude et la longitude à l'aide de Google API, Python et 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)
3
sunil singh