如何获得Latitude&经度与python

时间:2014-09-17 10:39:15

标签: python google-maps python-2.7

我正在尝试检索经度&物理地址的纬度,通过下面的脚本。但我收到错误。我已经安装了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

输出:

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

7 个答案:

答案 0 :(得分:39)

您正在使用的googlemaps套餐不是官方套餐,也不使用谷歌地图API v3,这是google的最新版本。

您可以使用Google的geocode REST api从地址获取坐标。这是一个例子。

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

答案 1 :(得分:4)

尝试此代码:-

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)

答案 2 :(得分:3)

您好,这是我最常使用物理地址获得经纬度的位置。 注意:请用NaN填充空白。 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:我使用BANFrance()作为API,您可以在Geocoders处找到其他API。

答案 3 :(得分:3)

对于不需要API密钥或外部库的Python脚本,您可以查询Nominatim服务,该服务依次查询Open Street Map数据库。

有关如何使用它的更多信息,请参见https://nominatim.org/release-docs/develop/api/Search/

下面是一个简单的示例:

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

答案 4 :(得分:2)

使用google api,Python和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)

答案 5 :(得分:1)

正如@WSaitama所说,geopy运作良好,不需要身份验证。要下载它:https://pypi.org/project/geopy/。有关如何使用它的一个示例是:

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)

答案 6 :(得分:0)

您尝试使用库geopy吗? https://pypi.org/project/geopy/

它适用于python 2.7至3.8。 它也适用于OpenStreetMap Nominatim,Google Geocoding API(V3)等。

希望它可以为您提供帮助。