使用Python進行地理編碼和反向地理編碼

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密鑰,如下圖所示。

Image for post

(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)
Image for post
Hospital location data frame
醫院位置數據框

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集群來更好地幫助了解醫院數量最多的地區。

Image for post
A snapshot of the map visualization (clustered locations) created using Folium
使用Folium創建的地圖可視化快照(聚集位置)

反向地理編碼 (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
Image for post

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,一經查實,立即刪除!

相關文章

java開發簡歷編寫_如何通過幾個簡單的步驟編寫出色的初級開發人員簡歷

java開發簡歷編寫So you’ve seen your dream junior developer role advertised, and are thinking about applying. It’s time to write that Resume! Nothing better than sitting down to a blank piece of paper and not knowing how to start, right?因此,您…

leetcode 628. 三個數的最大乘積(排序)

給定一個整型數組,在數組中找出由三個數組成的最大乘積,并輸出這個乘積。 示例 1: 輸入: [1,2,3] 輸出: 6 解題思路 最大的乘積可能有兩種情況 1.兩個最小負數和一個最大正數 2.三個最大正數 代碼 class Solution {public int maximumProduct(int[…

[Object-C語言隨筆之三] 類的創建和實例化以及函數的添加和調用!

上一小節的隨筆寫了常用的打印以及很基礎的數據類型的定義方式,今天就來一起學習下如何創建類與函數的一些隨筆; 首先類的創建:在Xcode下,菜單File-New File,然后出現選擇class模板,如下圖&…

2024-AI人工智能學習-安裝了pip install pydot但是還是報錯

2024-AI人工智能學習-安裝了pip install pydot但是還是報錯 出現這樣子的錯誤: /usr/local/bin/python3.11 /Users/wangyang/PycharmProjects/studyPython/tf_model.py 2023-12-24 22:59:02.238366: I tensorflow/core/platform/cpu_feature_guard.cc:182] This …

grafana 創建儀表盤_創建儀表盤前要問的三個問題

grafana 創建儀表盤可視化 (VISUALIZATIONS) It’s easier than ever to dive into dashboarding, but are you doing it right?深入儀表板比以往任何時候都容易,但是您這樣做正確嗎? Tableau, Power BI, and many other business intelligence tools …

qq群 voiceover_如何在iOS上使用VoiceOver為所有人構建應用程序

qq群 voiceoverby Jayven N由Jayven N 如何在iOS上使用VoiceOver為所有人構建應用程序 (How to build apps for everyone using VoiceOver on iOS) 輔助功能入門 (Getting started with accessibility) There’s always those topics that people don’t talk about enough. S…

IntelliJ IDEA代碼常用的快捷鍵(自查)

IntelliJ IDEA代碼常用的快捷鍵有: Alt回車 導入包,自動修正 CtrlN 查找類 CtrlShiftN 查找文件 CtrlAltL 格式化代碼 CtrlAltO 優化導入的類和包 AltInsert 生成代碼(如get,set方法,構造函數等) CtrlE或者AltShiftC 最近更改的代碼 CtrlR…

leetcode 1489. 找到最小生成樹里的關鍵邊和偽關鍵邊(并查集)

給你一個 n 個點的帶權無向連通圖,節點編號為 0 到 n-1 ,同時還有一個數組 edges ,其中 edges[i] [fromi, toi, weighti] 表示在 fromi 和 toi 節點之間有一條帶權無向邊。最小生成樹 (MST) 是給定圖中邊的一個子集,它連接了所有…

帶彩色字體的man pages(debian centos)

1234567891011121314151617181920212223242526272829303132333435363738我的博客已遷移到xdoujiang.com請去那邊和我交流簡介most is a paging program that displays,one windowful at a time,the contents of a file on a terminal. It pauses after each windowful and prin…

提取json對象中的數據,轉化為數組

var xx1 ["樂譜中的調號為( )調", "寫出a自然小調音階。", "以G為冠音,構寫增四、減五音程。", "調式分析。", "將下列樂譜移為C大調。", "正確組合以下樂譜。", "以下…

java 同步塊的鎖是什么,java – 同步塊 – 鎖定多個對象

我添加了另一個答案,因為我還沒有添加評論給其他人的帖子。>事實上,同步是用于代碼,而不是對象或數據。在同步塊中用作參數的對象引用表示鎖定。所以如果你有如下代碼:class Player {// Same instance shared for all players.…

大數據對社交媒體的影響_數據如何影響媒體,廣告和娛樂職業

大數據對社交媒體的影響In advance of our upcoming event — Data Science Salon: Applying AI and ML to Media, Advertising, and Entertainment, we asked our speakers, who are some of nation’s leading data scientists in the media, advertising, and entertainment…

Go-項目結構和代碼組織

簡介 做大量的輸入,通過對比、借鑒,加上自己的經驗,產出一個盡可能優的方案。 開源界優秀項目的結構示例 因為最新的 Go 版本已經使用 module 作為版本依賴,所以,所有項目的 vendor 我都忽略,建議直接使用 …

iref streams_如何利用Neo4j Streams并建立即時數據倉庫

iref streamsby Andrea Santurbano通過安德里亞桑圖爾巴諾(Andrea Santurbano) 如何利用Neo4j Streams并建立即時數據倉庫 (How to leverage Neo4j Streams and build a just-in-time data warehouse) In this article, we’ll show how to create a Just-In-Time Data Wareho…

Nodejs正則表達式函數之match、test、exec、search、split、replace使用詳解

1. Match函數使用指定的正則表達式函數對字符串驚醒查找,并以數組形式返回符合要求的字符串原型:stringObj.match(regExp)參數:stringObj 必選項,需要去進行匹配的字符串RegExp 必選項,指定的正則表達式返回值&#xf…

Zabbix 3.0 從入門到精通(zabbix使用詳解)

第1章 zabbix監控 1.1 為什么要監控 在需要的時刻,提前提醒我們服務器出問題了 當出問題之后,可以找到問題的根源 網站/服務器 的可用性 1.1.1 網站可用性 在軟件系統的高可靠性(也稱為可用性,英文描述為HA,High Avail…

python 裝飾器裝飾類_5分鐘的Python裝飾器指南

python 裝飾器裝飾類重點 (Top highlight)There’s no doubt that Python decorators are one of the more advanced and tougher-to-understand programming concepts. This doesn’t mean you should avoid learning them — as you encounter them in production code soone…

php中顏色的索引值,計算PHP中兩種顏色之間的平均顏色,使用索引號作為參考值...

我們假設為了討論的目的,每個顏色都有一個“值”.那么,你想要的就足夠簡單:$index 0.2;$val1 get_value_of_color($color1);$val2 get_value_of_color($color2);$newval $val1 * $index $val2 * (1 - $index);$newcolor get_color_from_value($newval);所以,很…

leetcode 989. 數組形式的整數加法

對于非負整數 X 而言,X 的數組形式是每位數字按從左到右的順序形成的數組。例如,如果 X 1231,那么其數組形式為 [1,2,3,1]。 給定非負整數 X 的數組形式 A,返回整數 XK 的數組形式。 示例 1: 輸入:A […

您需要了解的WordPress漏洞以及如何修復它們

by Joel S. Syder喬爾賽德(Joel S.Syder) 您需要了解的WordPress漏洞以及如何修復它們 (WordPress vulnerabilities you need to know about — and how to fix them) WordPress is an incredibly useful and versatile platform for all kinds of blogging. It’s become ver…