对地址进行地理编码以在 KML 中使用
使用集合让一切井井有条
根据您的偏好保存内容并对其进行分类。
Mano Marks,Google 地理位置团队
撰写时间: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 地理编码器,该地理编码器会以 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”市,而在 maps.google.it(意大利网域)中输入相同的查询内容会找到西西里岛的“Siracusa”市。如果您通过 HTTP 地理编码将该查询发送到 maps.google.it 而不是 maps.google.com,也会获得相同的结果。您可以通过修改上述示例代码中的 mapsUrl
变量来实现这一点。如需详细了解区域偏向,请参阅 Geocoding API 文档。
注意:您无法向不存在的 maps.google.* 服务器发送请求,因此请确保国家/地区网域存在,然后再将地理编码查询重定向到该网域。如需了解各个国家/地区对地理编码的支持情况,请参阅这篇帖子。
总结
使用上述代码,您现在可以使用 Python 对地址进行地理编码,从中创建 KML <Placemark>
,并将其保存到磁盘。如果您发现自己每天需要地理编码的地址数量超过了限制,或者 Google 地理编码器无法覆盖您感兴趣的区域,请考虑使用其他地理编码网络服务。
现在您已了解如何对地址进行地理编码,接下来可以查看以下文章:在 Google Mashup 编辑器中使用 KML和使用 PHP 和 MySQL 创建 KML。如果您对此教程有任何问题或疑问,请在 Stack Overflow 论坛中发帖咨询。
如未另行说明,那么本页面中的内容已根据知识共享署名 4.0 许可获得了许可,并且代码示例已根据 Apache 2.0 许可获得了许可。有关详情,请参阅 Google 开发者网站政策。Java 是 Oracle 和/或其关联公司的注册商标。
最后更新时间 (UTC):2025-07-27。
[null,null,["最后更新时间 (UTC):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."]]