Geocoding is the process of taking input text, such as an address or the name of a place, and returning a latitude/longitude location. To put it simply, Geocoding is converting physical address to latitude and longitude.
地理編碼是獲取輸入文本(例如地址或地點名稱)并返回緯度/經度位置的過程。 簡而言之,地理編碼會將物理地址轉換為緯度和經度。
There are many geocoding API options available in python. Some of the popular ones are GeoPy, OpenCage geocoder, google geocoding. Geopy is one of the few API services which provides unlimited access for non-commercial use. For Google API and OpenCage geocoders, there is a limit of 2500 requests per/day. Using geopy, the latitudes and longitudes for some addresses in my dataset, showed different countries instead of the US. With OpenCage geocoder, surprisingly all the addresses were accurate so I used OpenCage encoder.
python中提供了許多地理編碼API選項。 一些受歡迎的是GeoPy,OpenCage地理編碼器,google地理編碼。 Geopy是為非商業用途提供無限訪問的少數API服務之一。 對于Google API和OpenCage地理編碼器,每天限制為2500個請求。 使用geopy,我的數據集中某些地址的經度和緯度顯示了不同的國家,而不是美國。 使用OpenCage 地理編碼器時 ,令人驚訝的是所有地址都是準確的,因此我使用了OpenCage編碼器。
使用OpenCage地理編碼器和熊貓 (Working with OpenCage geocoder and pandas)
To use OpenCage Geocoder in python, the python library should be installed first using pip install opencage
.More info about this library can be found here: OpenCageGeocode on Github
要在python中使用OpenCage Geocoder,應首先使用pip install opencage
安裝python庫。有關此庫的更多信息,請參見: Github上的OpenCageGeocode
Once the library is installed, you will need an OpenCage geocoder account to generate an API key. A free account can be created using opencagedata.com. Once you signup for an account you can find API keys in Dashboard as shown in the below image.
安裝庫后,您將需要一個OpenCage地理編碼器帳戶來生成API密鑰。 可以使用opencagedata.com創建免費帳戶。 注冊帳戶后,即可在儀表板中找到API密鑰,如下圖所示。

例 (Example)
from opencage.geocoder import OpenCageGeocode
key = "Enter_your_Api_Key"
geocoder = OpenCageGeocode(key)
address='1108 ROSS CLARK CIRCLE,DOTHAN,HOUSTON,AL'
result = geocoder.geocode(address, no_annotations="1")
result[0]['geometry']
Output: {‘lat’: 31.2158271, ‘lng’: -85.3634326}
輸出:{'lat':31.2158271,'lng':-85.3634326}
We got the latitude and longitude for one hospital named Southeast Alabama Medical Center. In most cases, we will have multiple addresses that need to be plotted in maps as we do now. In this case, using pandas to create a data frame will be a lot easier. The dataset I used contains the list of all Hospitals in the US along with the COVID-19 total cases for the counties where hospitals are located. The dataset can be downloaded from here.
我們獲得了一家名為阿拉巴馬州東南醫療中心的醫院的經度和緯度。 在大多數情況下,像現在一樣,我們將需要在地圖中繪制多個地址。 在這種情況下,使用熊貓創建數據框會容易得多。 我使用的數據集包含美國所有醫院的列表以及醫院所在縣的COVID-19總病例數。 數據集可從此處下載。
import pandas as pd
data=pd.read_csv(‘Final.csv’)
data.head(10)

We have a data frame that contains the list of Facility Name of all Hospitals in the US and their addresses, so we just need to find location coordinates.
我們有一個數據框,其中包含美國所有醫院的設施名稱及其地址的列表,因此我們只需要查找位置坐標即可。
First, we should convert the Address column to the list. So, it will be easier to loop all the addresses.
首先,我們應該將“地址”列轉換為列表。 因此,將更容易循環所有地址。
Next, enter your API key from OpenCage geocoder website and create empty lists to store latitudes and longitudes. After creating empty list, create a loop which gives latitude’s and longitude’s for all addresses
接下來,從OpenCage地理編碼器網站輸入您的API密鑰,并創建一個空列表來存儲緯度和經度。 創建空列表后,創建一個循環,該循環為所有地址提供緯度和經度
addresses = data["Full_Address"].values.tolist()
key = "Enter-your-key-here"
geocoder = OpenCageGeocode(key)
latitudes = []
longitudes = []
for address in addresses:
result = geocoder.geocode(address, no_annotations="1")
if result and len(result):
longitude = result[0]["geometry"]["lng"]
latitude = result[0]["geometry"]["lat"]
else:
longitude = "N/A"
latitude = "N/A"
latitudes.append(latitude)
longitudes.append(longitude)
We have latitudes and longitudes for the list of all the addresses in the data frame. we can add this latitudes and longitudes to our existing data frame using this simple pandas command.
我們在數據框中列出了所有地址的經度和緯度。 我們可以使用此簡單的pandas命令將此緯度和經度添加到我們現有的數據框中。
data["latitudes"] = latitudes
data["longitudes"] = longitudes
data.head(10)
Finally, we got the latitude and longitudes for all the hospital addresses. To better understand this location coordinates let’s plot all this location coordinates as points in map using folium maps.
最后,我們獲得了所有醫院地址的經度和緯度。 為了更好地理解此位置坐標,讓我們使用葉片地圖在地圖上將所有這些位置坐標繪制為點。
folium_map= folium.Map(location=[33.798259,-84.327062],zoom_start=4.4,tiles=’CartoDB dark_matter’)FastMarkerCluster(data[[‘latitudes’, ‘longitudes’]].values.tolist()).add_to(folium_map)folium.LayerControl().add_to(folium_map) for row in final.iterrows():
row=row[1]
folium.CircleMarker(location=(row["latitudes"],
row["longitudes"]),
radius= 10,
color="#007849",
popup=row[‘Facility_Name’],
fill=False).add_to(folium_map)
folium_map
Now, we can see the location points of all the hospitals in the USA. I used CircleMarker cluster to better help understand the regions with most number of hospitals.
現在,我們可以看到美國所有醫院的位置。 我使用CircleMarker集群來更好地幫助了解醫院數量最多的地區。

反向地理編碼 (Reverse Geocoding)
Reverse geocoding, on the other hand, converts geographic coordinates to a description of a location, usually the name of a place or an addressable location. Geocoding relies on a computer representation of address points, the street/road network, together with postal and administrative boundaries.
另一方面, 反向地理編碼會將地理坐標轉換為位置的描述,通常是位置名稱或可尋址位置。 地理編碼依賴于地址點,街道/道路網絡以及郵政和行政邊界的計算機表示。
For reverse geocoding, I found the output format of Geopy API more detailed when compared to OpenCage Geocoder. And also, there is no limit for Geopy API so we will Geopy instead of OpenCage Geocoder.
對于反向地??理編碼,與OpenCage Geocoder相比,我發現Geopy API的輸出格式更加詳細。 而且,對于Geopy API沒有限制,因此我們將使用Geopy代替OpenCage Geocoder。
OpenCage Reverse Geocoder Example
OpenCage反向地理編碼器示例
result = geocoder.reverse_geocode(31.2158271,-85.3634326)
result[0][‘formatted’]
Output : Southeast Health Medical Center, Alma Street, Dothan, AL 36302, United States of America
產出:美利堅合眾國阿拉巴馬州多森市阿爾瑪街東南健康醫學中心,美國36302
Geopy Reverse Geocoder Example
Geopy反向地理編碼器示例
from geopy.geocoders import Nominatim
geolocator = Nominatim(user_agent="test_app")
location = geolocator.reverse("31.2158271,-85.3634326")
location.raw[‘display_name’]
Output: ‘Southeast Health Campus, 1108, Ross Clark Circle, Morris Heights, Dothan, Houston County, Alabama, 36301, United States of America
產出:'東南健康校園,1108,羅斯克拉克圈,莫里斯高地,多森,休斯敦縣,阿拉巴馬州,36301,美國
使用Geopy Geocoder和熊貓 (Working with Geopy Geocoder and pandas)
For reverse geocoding, as above first, we will convert latitude and longitude to list and zip them together.
對于反向地??理編碼,如上所述,首先,我們將緯度和經度轉換為列表并將它們壓縮在一起。
lats=data['latitudes'].to_list()
lons=data['longitudes'].to_list()
# Creating a zip with latitudes and longitudes
coords=list(zip(lats,lons))
Since, we already created list, just like above we will create a loop to find address for each location coordinate and append them together.
因為我們已經創建了列表,所以像上面一樣,我們將創建一個循環以查找每個位置坐標的地址并將它們附加在一起。
from geopy.geocoders import Nominatim
geolocator = Nominatim(user_agent="test_app")
full_address=[]
for i in range(len(coords)):
location = geolocator.reverse(coords[i])
address=location.raw['address']['country']
full_address.append(address)
#Creating dataframe with all the addresses
addres=pd.DataFrame(data=full_address , columns=['Address'])
addres

Finally, we have the address list of all hospitals in the US.
最后,我們擁有美國所有醫院的地址列表。
For interested readers, I put the code in my GitHub Repo here. If you have any doubts, contact me using linkedin.
對于感興趣的讀者,我將代碼放在此處的 GitHub Repo中。 如有任何疑問,請使用linkedin與我聯系。
翻譯自: https://towardsdatascience.com/geocoding-and-reverse-geocoding-using-python-36a6ad275535
本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。 如若轉載,請注明出處:http://www.pswp.cn/news/392288.shtml 繁體地址,請注明出處:http://hk.pswp.cn/news/392288.shtml 英文地址,請注明出處:http://en.pswp.cn/news/392288.shtml
如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!