KML で使用する住所のジオコーディング
コレクションでコンテンツを整理
必要に応じて、コンテンツの保存と分類を行います。
Mano Marks、Google Geo チーム
作成: 2007 年 12 月
更新: 2013 年 12 月
目標
このチュートリアルは、スクリプト言語に精通しており、Google Geocoding API を使用して住所をジオコーディングし、KML ファイルに組み込む方法を学びたいデベロッパーを対象としています。コードサンプルは Python で示されていますが、他のほとんどのプログラミング言語に簡単に適用できます。
ジオコーディングとは、住所を緯度と経度の座標のセットに変換するプロセスです。これにより、地図上に住所を表示できるようになります。住所をジオコーディングして KML ファイルに直接配置したい場合があります。たとえば、フォームにデータが入力され、リクエストに応じて KML ファイルを生成する場合などによくあります。これらの KML ファイルは、データベース、ファイル システムに保存するか、ファイルに接続する NetworkLink に返します。この手法を使用する際は、Geocoding API の利用規約を遵守する必要があります。結果を保存できる期間や、1 日にジオコーディングできる要素の数には制限があるためです。
このチュートリアルでは、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 に送信します。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')
その他の考慮事項
ジオコード化リクエストのタイミング
ジオコーディング リクエストには、ジオコーダの 1 日あたりの最大クエリレートの上限が適用されます。これらの上限の詳細については、Google Geocoding API のドキュメントをご覧ください。ジオコーダにクエリを送信する速度が速すぎないようにするには、各ジオコード リクエスト間の遅延を指定します。OVER_QUERY_LIMIT
ステータスを受け取るたびにこの遅延を増やし、while
ループを使用して、次のアドレスに反復処理を行う前にアドレスのジオコーディングが正常に完了したことを確認できます。
ベースの国を変更する
ジオコーダは、元のドメインに応じて結果をバイアスするようにプログラムされています。たとえば、maps.google.com の検索ボックスに「syracuse」と入力すると、ニューヨーク州の「Syracuse」という都市がジオコーディングされますが、maps.google.it(イタリアのドメイン)で同じクエリを入力すると、シチリア島の「Siracusa」という都市が検索されます。上記のサンプルコードの mapsUrl
変数を変更することで、maps.google.com ではなく maps.google.it に HTTP ジオコーディングでクエリを送信しても、同じ結果が得られます。地域バイアスの詳細については、Geocoding API のドキュメントをご覧ください。
注: 存在しない maps.google.* サーバーにリクエストを送信することはできません。そのため、ジオコーディング クエリをリダイレクトする前に、国別ドメインが存在することを確認してください。国別のジオコードのサポートについては、こちらの投稿をご覧ください。
まとめ
上記のコードを使用すると、Python を使用して住所をジオコーディングし、そこから KML <Placemark>
を作成して、ディスクに保存できます。1 日にジオコーディングする必要がある住所の数が上限を超えている場合や、Google ジオコーダが対象とする地域が目的の地域と異なる場合は、追加のジオコーディング ウェブサービスの利用をご検討ください。
住所をジオコーディングする方法を理解したら、Google Mashup Editor で KML を使用すると PHP と MySQL を使用して KML を作成するの記事をご覧ください。このチュートリアルについてご不明な点や問題がございましたら、Stack Overflow フォーラムに投稿してください。
特に記載のない限り、このページのコンテンツはクリエイティブ・コモンズの表示 4.0 ライセンスにより使用許諾されます。コードサンプルは Apache 2.0 ライセンスにより使用許諾されます。詳しくは、Google Developers サイトのポリシーをご覧ください。Java は Oracle および関連会社の登録商標です。
最終更新日 2025-07-27 UTC。
[null,null,["最終更新日 2025-07-27 UTC。"],[[["\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."]]