KML에서 사용할 주소 지오코딩
컬렉션을 사용해 정리하기
내 환경설정을 기준으로 콘텐츠를 저장하고 분류하세요.
Mano Marks, Google Geo Team
작성: 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
을 사용하여 문서 요소를 만듭니다.
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' 도시가 검색됩니다. 위 샘플 코드에서 mapsUrl
변수를 수정하여 maps.google.com이 아닌 maps.google.it에 HTTP 지오코딩을 통해 쿼리를 전송해도 동일한 결과를 얻을 수 있습니다.
지역 편향에 관한 자세한 내용은 Geocoding API 문서를 참고하세요.
참고: 존재하지 않는 maps.google.* 서버에 요청을 보낼 수 없으므로 지오코딩 쿼리를 리디렉션하기 전에 국가 도메인이 있는지 확인하세요. 국가별 지오코드 지원은 이 게시물을 참고하세요.
결론
위의 코드를 사용하여 이제 Python으로 주소를 지오코딩하고, 이를 기반으로 KML <Placemark>
를 만들어 디스크에 저장할 수 있습니다. 일일 지오코딩 주소 수가 한도를 초과하거나 Google 지오코더가 관심 있는 지역을 지원하지 않는 경우 추가 지오코딩 웹 서비스를 사용하는 것이 좋습니다.
주소를 지오코딩하는 방법을 알았으니 Google 매시업 편집기에서 KML 사용 및 PHP 및 MySQL을 사용하여 KML 만들기에 관한 도움말을 확인하세요.
이 튜토리얼에 문제가 있거나 궁금한 점이 있으면 Stack Overflow 포럼에 게시해 주세요.
달리 명시되지 않는 한 이 페이지의 콘텐츠에는 Creative Commons Attribution 4.0 라이선스에 따라 라이선스가 부여되며, 코드 샘플에는 Apache 2.0 라이선스에 따라 라이선스가 부여됩니다. 자세한 내용은 Google Developers 사이트 정책을 참조하세요. 자바는 Oracle 및/또는 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."]]