如何使用python获取纬度和经度
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25888396/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How To Get Latitude & Longitude with python
提问by user3008712
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
我正在尝试通过以下脚本检索物理地址的经度和纬度。但我收到错误消息。我已经安装了 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
回答by Saleem Latif
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.
您使用的 googlemaps 软件包不是官方软件包,并且不使用 google maps API v3,这是 google 的最新版本。
You can use google's geocode REST apito fetch coordinates from address. Here's an example.
您可以使用谷歌的地理编码 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'])
回答by Sunil Singh
Simplest way to get Latitude and Longitude using google api, Python and Django.
使用 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)
回答by S.S oganja
Try This 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)
回答by abdoulsn
Hello here is the one I use most time to get latitude and longitude using physical adress.
NB: Pleas fill NaNwith empty. df.adress.fillna('')
您好,这是我使用物理地址获取纬度和经度最常使用的方法。注意:请填空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: I use BANFrance() as API, you can find other API here Geocoders.
注意:我使用 BANFrance() 作为 API,您可以在Geocoders 中找到其他 API 。
回答by Wsaitama
did you try to use the the library geopy ? https://pypi.org/project/geopy/
您是否尝试使用库 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.
它适用于 python 2.7 到 3.8。它也适用于 OpenStreetMap Nominatim、Google Geocoding API (V3) 等。
Hope it can help you.
希望它可以帮助你。
回答by Carles Sans Fuentes
As @WSaitama said, geopyworks well and it does not require authentification. To download it: https://pypi.org/project/geopy/. An example on how to use it would be:
正如@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)
回答by Hamish Anderson
Here is a python script that does not require an api key.
这是一个不需要api密钥的python脚本。
It uses the Nominatim service which queries the Open Street Map database. For more information on how to use it see https://nominatim.org/release-docs/develop/api/Search/
它使用 Nominatim 服务查询 Open Street Map 数据库。有关如何使用它的更多信息,请参阅https://nominatim.org/release-docs/develop/api/Search/
A simple example is below, just copy it into file and run it with python 3.
下面是一个简单的示例,只需将其复制到文件中并使用 python 3 运行它。
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"])

