為 KML 使用的地址進行地理編碼
透過集合功能整理內容
你可以依據偏好儲存及分類內容。
Google 地理位置團隊 Mano Marks
撰寫日期:2007 年 12 月
更新日期:2013 年 12 月
目標
本教學課程適用於熟悉指令碼語言的開發人員,他們想瞭解如何使用 Google Geocoding API 為地址進行地理編碼,並將其併入 KML 檔案。雖然程式碼範例是以 Python 呈現,但可以輕鬆改寫成大多數其他程式設計語言。
地理編碼是指將地址轉換為一組經緯度座標的程序,方便在地圖上標示地址。您可能需要將地址地理編碼,然後直接放入 KML 檔案。舉例來說,當您在表單中輸入資料,並根據要求產生 KML 檔案時,通常會發生這種情況。這些 KML 檔案可以儲存在資料庫或檔案系統中,也可以傳回至連線到檔案的 NetworkLink。請注意,使用這項技術時,您必須遵守 Geocoding API 的服務條款,因為結果的儲存時間和每天可地理編碼的元素數量都有限制。
本教學課程說明如何使用 Python 取得「1600 Amphitheatre Pkwy, Mountain View, CA 94043
」字串,並將其轉換為:
<?xml version='1.0' encoding='UTF-8'?>
<kml xmlns='http://earth.google.com/kml/2.2'>
<Document>
<Placemark>
<description>1600 Amphitheatre Pkwy, Mountain View, CA 94043, USA</description>
<Point>
<coordinates>-122.081783,37.423111,0</coordinates>
</Point>
</Placemark>
</Document>
</kml>
建立 KML 文件
KML 是 XML 標記語言,因此我們可以使用 Python 的內建 xml.dom.minidom 函式建立 KML 文件。Python 的 minidom 是 DOM 實作項目,而大多數程式設計語言都支援 DOM,因此這個程序應該很容易移植到其他程式設計語言。步驟如下:
- 使用 Python 的
xml.dom.minidom.Document()
建立文件。
- 使用
createElementNS.
建立根 <kml>
元素
- 使用
appendChild
將其附加至文件。
- 使用
createElement
建立 Document 元素。
- 使用
appendChild
將其附加至 <kml>
元素。
- 針對每個地址,使用
createElement
建立 <Placemark>
元素,並附加至 Document
元素。接著,建立 <description>
元素,將地址值指派給該元素,然後將其附加至 <Placemark>
元素。
- 建立
<Point>
元素、新增子項 <coordinates>
元素,然後附加至 <Placemark>
元素。
- 將地址傳送至 Maps API Geocoder,後者會以 JSON 或 XML 格式傳送回應。
使用
urllib.urlopen()
擷取檔案,並將檔案讀取至字串。
- 剖析回應並擷取經緯度元素。
- 在
<coordinates>
元素中建立文字節點,並將經度/緯度字串指派為其值。
- 將 KML 文件寫入文字檔。
Python 程式碼範例
請注意,下列範例程式碼使用虛擬的 mapsKey 變數,您需要將這個金鑰換成自己的金鑰。
以下是使用 Python 2.7 進行地理編碼並輸出 JSON 的程式碼範例:
import urllib
import xml.dom.minidom
import json
def geocode(address, sensor=False):
# This function queries the Google Maps API geocoder with an
# address. It gets back a csv file, which it then parses and
# returns a string with the longitude and latitude of the address.
# This isn't an actual maps key, you'll have to get one yourself.
# Sign up for one here: https://code.google.com/apis/console/
mapsKey = 'abcdefgh'
mapsUrl = 'https://maps.googleapis.com/maps/api/geocode/json?address='
# This joins the parts of the URL together into one string.
url = ''.join([mapsUrl,urllib.quote(address),'&sensor=',str(sensor).lower()])
#'&key=',mapsKey])
jsonOutput = str(urllib.urlopen(url).read ()) # get the response
# fix the output so that the json.loads function will handle it correctly
jsonOutput=jsonOutput.replace ("\\n", "")
result = json.loads(jsonOutput) # converts jsonOutput into a dictionary
# check status is ok i.e. we have results (don't want to get exceptions)
if result['status'] != "OK":
return ""
coordinates=result['results'][0]['geometry']['location'] # extract the geometry
return str(coordinates['lat'])+','+str(coordinates['lng'])
def createKML(address, fileName):
# This function creates an XML document and adds the necessary
# KML elements.
kmlDoc = xml.dom.minidom.Document()
kmlElement = kmlDoc.createElementNS('http://earth.google.com/kml/2.2','kml')
kmlElement = kmlDoc.appendChild(kmlElement)
documentElement = kmlDoc.createElement('Document')
documentElement = kmlElement.appendChild(documentElement)
placemarkElement = kmlDoc.createElement('Placemark')
descriptionElement = kmlDoc.createElement('description')
descriptionText = kmlDoc.createTextNode(address)
descriptionElement.appendChild(descriptionText)
placemarkElement.appendChild(descriptionElement)
pointElement = kmlDoc.createElement('Point')
placemarkElement.appendChild(pointElement)
coorElement = kmlDoc.createElement('coordinates')
# This geocodes the address and adds it to a element.
coordinates = geocode(address)
coorElement.appendChild(kmlDoc.createTextNode(coordinates))
pointElement.appendChild(coorElement)
documentElement.appendChild(placemarkElement)
# This writes the KML Document to a file.
kmlFile = open(fileName, 'w')
kmlFile.write(kmlDoc.toprettyxml(' '))
kmlFile.close()
if __name__ == '__main__':
createKML('1600 Amphitheatre Pkwy, Mountain View, CA 94043, USA', 'google.kml')
其他注意事項
計時地理編碼要求
地理編碼要求會受到地理編碼器每日查詢次數上限的限制。如要進一步瞭解這些限制,請參閱 Google Geocoding API 說明文件。為確保您不會太快將查詢傳送至地理編碼器,您可以指定每次地理編碼要求之間的延遲時間。每次收到 OVER_QUERY_LIMIT
狀態時,您都可以增加這項延遲時間,並使用 while
迴圈,確保已成功將地址地理編碼,再疊代至下一個地址。
變更基準國家
地理編碼器會根據原始網域調整結果。舉例來說,在 maps.google.com 的搜尋框中輸入「syracuse」,系統會將「Syracuse, NY」這個城市進行地理編碼;在 maps.google.it (義大利網域) 輸入相同查詢,系統則會找到西西里島的「Siracusa」這個城市。如果透過 HTTP 地理編碼將該查詢傳送至 maps.google.it,而非 maps.google.com,您會得到相同的結果。如要這麼做,請修改上述範例程式碼中的 mapsUrl
變數。如要進一步瞭解區域偏向,請參閱 Geocoding API 說明文件。
注意:您無法將要求傳送至不存在的 maps.google.* 伺服器,因此請務必先確認國家/地區網域存在,再將地理編碼查詢重新導向至該網域。如要瞭解各國家/地區的地理編碼支援情形,請參閱這篇文章。
結論
使用上述程式碼,您現在可以透過 Python 對地址進行地理編碼、從中建立 KML <Placemark>
,並儲存至磁碟。如果發現每天需要地理編碼的地址數量超過限制,或是 Google 地理編碼器未涵蓋您感興趣的區域,請考慮使用其他地理編碼網路服務。
現在您已瞭解如何將地址轉換為地理編碼,請參閱「在 Google Mashup Editor 中使用 KML」和「使用 PHP 和 MySQL 建立 KML」一文。如果您對本教學課程有任何問題,請前往 Stack Overflow 論壇提問。
除非另有註明,否則本頁面中的內容是採用創用 CC 姓名標示 4.0 授權,程式碼範例則為阿帕契 2.0 授權。詳情請參閱《Google Developers 網站政策》。Java 是 Oracle 和/或其關聯企業的註冊商標。
上次更新時間:2025-07-27 (世界標準時間)。
[null,null,["上次更新時間:2025-07-27 (世界標準時間)。"],[[["\u003cp\u003eThis tutorial demonstrates how to geocode addresses using the Google Geocoding API and Python, converting them into latitude/longitude coordinates for KML file integration.\u003c/p\u003e\n"],["\u003cp\u003eThe process involves creating a KML document, sending addresses to the Geocoding API, parsing the response for coordinates, and embedding them within KML Placemark elements.\u003c/p\u003e\n"],["\u003cp\u003ePython's xml.dom.minidom library is used for KML document creation, and urllib.urlopen is used for retrieving the geocoding results in JSON format.\u003c/p\u003e\n"],["\u003cp\u003eConsiderations include respecting the Geocoding API's usage limits by implementing delays between requests and adjusting the base country for region-specific results.\u003c/p\u003e\n"],["\u003cp\u003eThe resulting KML file can be used to display geocoded addresses as points on a map, enabling visualization and integration with other geographic data.\u003c/p\u003e\n"]]],[],null,["# Geocoding Addresses for Use in KML\n\n*Mano Marks, Google Geo Team\nAuthored: December 2007\nUpdated: December 2013*\n\nObjective\n---------\n\nThis tutorial is intended for developers who are familiar with\nscripting languages and want to learn how to use the [Google\nGeocoding API](/maps/documentation/geocoding) to geocode addresses and incorporate them into a KML file. While the code samples\nare presented in Python, they can be adapted fairly easily to most other programming languages.\n\n\n*Geocoding* is the process of converting an address into a set of latitude/longitude\ncoordinates, making it possible to indicate addresses on a map. You may want to geocode addresses\nand put them directly into a KML file. This is common, for example, when data is being entered into\na form and you are generating KML files in response to requests. These KML files could be\nstored in a database, in a file system or returned to a NetworkLink that connects to your file.\nNote that when using this technique, you must observe the [Terms of Service](/maps/terms)\nfor the Geocoding API as there are some limitations on the time the results can be stored for, as\nwell as the number of elements that you can geocode each day.\n\nThis tutorial shows you how to use Python to take the string\n\"`1600 Amphitheatre Pkwy, Mountain View, CA 94043`\" and turn it into this: \n\n```text\n\u003c?xml version='1.0' encoding='UTF-8'?\u003e \n\u003ckml xmlns='http://earth.google.com/kml/2.2'\u003e\n \u003cDocument\u003e\n \u003cPlacemark\u003e\n \u003cdescription\u003e1600 Amphitheatre Pkwy, Mountain View, CA 94043, USA\u003c/description\u003e\n \u003cPoint\u003e\n \u003ccoordinates\u003e-122.081783,37.423111,0\u003c/coordinates\u003e\n \u003c/Point\u003e\n \u003c/Placemark\u003e\n \u003c/Document\u003e\n\u003c/kml\u003e\n```\n\nCreate a KML Document\n---------------------\n\nKML is an XML markup language, so we can use Python's built in\n[xml.dom.minidom](http://docs.python.org/lib/module-xml.dom.minidom.html)\nfunctions to create a KML document. Python's minidom is a [DOM](http://www.w3.org/DOM/)\nimplementation, and DOM is supported in most programming languages, so this process should be easy\nto port into another programming language. Here are the steps:\n\n1. Create the document using Python's `xml.dom.minidom.Document()`.\n2. Create the root `\u003ckml\u003e` element using `createElementNS.`\n3. Append it to the document using `appendChild`.\n4. Create a Document element using `createElement`.\n5. Append it to the `\u003ckml\u003e` element using `appendChild`.\n6. For each address, create a `\u003cPlacemark\u003e` element using `createElement`, and append it to the `Document` element. Then, create a `\u003cdescription\u003e` element, assign it the value of the address, and append it to the `\u003cPlacemark\u003e` element.\n7. Create a `\u003cPoint\u003e` element, add a child `\u003ccoordinates\u003e` element, and append it to the `\u003cPlacemark\u003e` element.\n8. Send the address to the Maps API Geocoder, which sends a response in either JSON or XML. Use `urllib.urlopen()` to retrieve the file and read it into a string.\n9. Parse the response and extract the longitude and latitude elements.\n10. Create a text node in the `\u003ccoordinates\u003e` element and assign the longitude/latitude string as its value.\n11. Write the KML document to a text file.\n\nSample Python Code\n------------------\n\n\nNote that the sample code below uses a dummy mapsKey variable---you'll need to replace this key with your\n[own key](https://code.google.com/apis/console/?noredirect).\n\nSample code for geocoding with Python 2.7 and JSON output is shown below: \n\n```python\nimport urllib\nimport xml.dom.minidom\nimport json \n\ndef geocode(address, sensor=False):\n # This function queries the Google Maps API geocoder with an\n # address. It gets back a csv file, which it then parses and\n # returns a string with the longitude and latitude of the address.\n\n # This isn't an actual maps key, you'll have to get one yourself.\n # Sign up for one here: https://code.google.com/apis/console/\n mapsKey = 'abcdefgh'\n mapsUrl = 'https://maps.googleapis.com/maps/api/geocode/json?address='\n \n # This joins the parts of the URL together into one string.\n url = ''.join([mapsUrl,urllib.quote(address),'&sensor=',str(sensor).lower()])\n#'&key=',mapsKey])\n jsonOutput = str(urllib.urlopen(url).read ()) # get the response \n # fix the output so that the json.loads function will handle it correctly\n jsonOutput=jsonOutput.replace (\"\\\\n\", \"\")\n result = json.loads(jsonOutput) # converts jsonOutput into a dictionary \n # check status is ok i.e. we have results (don't want to get exceptions)\n if result['status'] != \"OK\": \n return \"\"\n coordinates=result['results'][0]['geometry']['location'] # extract the geometry \n return str(coordinates['lat'])+','+str(coordinates['lng'])\n\ndef createKML(address, fileName):\n # This function creates an XML document and adds the necessary\n # KML elements.\n\n kmlDoc = xml.dom.minidom.Document()\n \n kmlElement = kmlDoc.createElementNS('http://earth.google.com/kml/2.2','kml')\n\n kmlElement = kmlDoc.appendChild(kmlElement)\n\n documentElement = kmlDoc.createElement('Document')\n documentElement = kmlElement.appendChild(documentElement)\n\n placemarkElement = kmlDoc.createElement('Placemark')\n \n descriptionElement = kmlDoc.createElement('description')\n descriptionText = kmlDoc.createTextNode(address)\n descriptionElement.appendChild(descriptionText)\n placemarkElement.appendChild(descriptionElement)\n pointElement = kmlDoc.createElement('Point')\n placemarkElement.appendChild(pointElement)\n coorElement = kmlDoc.createElement('coordinates')\n\n # This geocodes the address and adds it to a element.\n coordinates = geocode(address)\n coorElement.appendChild(kmlDoc.createTextNode(coordinates))\n pointElement.appendChild(coorElement)\n\n documentElement.appendChild(placemarkElement)\n\n # This writes the KML Document to a file.\n kmlFile = open(fileName, 'w')\n kmlFile.write(kmlDoc.toprettyxml(' ')) \n kmlFile.close()\n\nif __name__ == '__main__':\n createKML('1600 Amphitheatre Pkwy, Mountain View, CA 94043, USA', 'google.kml')\n```\n\nOther Things to Consider\n------------------------\n\n### Timing the Geocode Requests\n\n\nGeocoding requests will be subject to the geocoder's maximum query rate daily limits. Please refer\nto the [Google Geocoding API](/maps/documentation/geocoding) documentation for more\ninformation about these limits. To ensure you don't send queries too rapidly to the geocoder, you\ncan specify a delay between each geocode request. You can increase this delay each time you receive\nan `OVER_QUERY_LIMIT` status, and use a `while` loop to ensure you've\nsuccessfully geocoded an address before iterating to the next one.\n\n### Changing the Base Country\n\n\nThe geocoder is programmed to bias its results depending on the originating domain.\nFor example, entering \"syracuse\" in the search box on maps.google.com will geocode the city of\n\"Syracuse, NY\", while entering the same query on *maps.google.it* (Italy's domain) will\nfind the city of \"Siracusa\" in Sicily. You would get the same results by sending that query\nthrough HTTP geocoding to *maps.google.it* instead of *maps.google.com* ,\nwhich you can do by modifying the `mapsUrl` variable in the sample code above.\nRefer to the Geocoding API documentation for more information on\n[Region Biasing](/maps/documentation/geocoding#RegionCodes).\n\n**Note:** You cannot send a request to a nonexistent\nmaps.google.\\* server, so ensure that a country domain exists before redirecting your geocoding\nqueries to it. For geocode support by country, check out\n[this\npost](http://googlemapsapi.blogspot.com/2007/11/is-google-maps-in-your-neck-of-woods.html).\n\nConclusion\n----------\n\nUsing the code above, you can now geocode an address using Python, create a KML\n`\u003cPlacemark\u003e` out of it, and save it to disk. If you find that you need to\ngeocode more addresses per day than the limits allow, or that the Google geocoder doesn't cover the\nregions you're interested in, then consider using additional geocoding web services.\n\nNow that you know how to geocode your addresses, check out the articles on\n[Using KML in Google Mashup Editor](/kml/articles/kmlgme) and\n[Using PHP and MySQL to create KML](/kml/articles/phpmysqlkml).\nIf you have any problems with or questions about this tutorial, please post in the [Stack Overflow](/maps/support)\nforum."]]