This tutorial is intended for developers who are familiar with scripting languages and want to learn how to use the Google Maps API Geocoder to geocode addresses and incorporate them into a KML file. While the code samples are presented in Python, they can be adapted fairly easily to most other programming languages.
Geocoding is the process of converting an address into a set of latitude/longitude coordinates, making it possible to indicate addresses on a map. Ideally, you would create a database of addresses, and pre-geocode them, as outlined in Geocoding Addresses with PHP/MySQL, by Pamela Fox and Tom Manshreck. However, sometimes you want to geocode addresses and put them directly into a KML file. This is common, for example, when data is being entered into a form and you are generating KML files in response to requests. These KML files could be stored in a database, in a file system or returned to a NetworkLink that connects to your file. Note that this technique should not be used for geocoding thousands of addresses a day, as this goes against the intended use of this service.
This tutorial shows you how to use Python
to take the
1600 Amphitheatre Pkwy, Mountain View, CA 94043"
and turn it into this:
<?xml version='1.0' encoding='UTF-8'?>
<description>1600 Amphitheatre Pkwy, Mountain View, CA 94043, USA</description>
Create a KML Document
KML is an XML markup language, so we can use Python's built in xml.dom.minidom functions to create a KML document. Python's minidom is a DOM implementation, and DOM is supported in most programming languages, so this process should be easy to port into another programming language. Here are the steps:
- Create the document using Python's
- Create the root
- Append it to the document using
- Create a Document element using
- Append it to the
- For each address, create a
createElement, and append it to the
Documentelement. Then, create a
<description>element, assign it the value of the address, and append it to the
- Create a
<Point>element, add a child
<coordinates>element, and append it to the
- Send the address to the Maps API Geocoder, which returns a
special form of a CSV file. Use
urllib.urlopen()to retrieve the file and read it into a string. Split the string into a list, extract the longitude and latitude elements off the list, then combine them into a string.
- Create a text node in the
<coordinates>element and assign the longitude/latitude string as its value.
- Write the KML document to a text file.
Sample Python Code
Sample code for geocoding with Python 2.2 and CSV output is shown below (geocoding_for_kml.py):
# 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 = 'http://maps.google.com/maps/geo?q='
# This joins the parts of the URL together into one string.
url = ''.join([mapsUrl,urllib.quote(address),'&output=csv&key=',mapsKey])
# This retrieves the URL from Google, parses out the longitude and latitude,
# and then returns them as a string.
coordinates = urllib.urlopen(url).read().split(',')
coorText = '%s,%s' % (coordinates,coordinates)
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')pointElement = kmlDoc.createElement('Point')
documentElement = kmlElement.appendChild(documentElement)
placemarkElement = kmlDoc.createElement('Placemark')
descriptionElement = kmlDoc.createElement('description')
descriptionText = kmlDoc.createTextNode(address)
coorElement = kmlDoc.createElement('coordinates')
# This geocodes the address and adds it to a <Point> element
coordinates = geocode(address)
# This writes the KML Document to a file.
kmlFile = open(fileName, 'w')
if __name__ == '__main__':
createKML('1600 Amphitheatre Pkwy, Mountain View, CA 94043, USA', 'google.kml')
Other Things to Consider
Timing the Geocode Requests
Regardless of what geocoder output you specify, your requests will be
subject to the geocoder's maximum
query rate and 15,000 queries per day based on your IP. Additionally, a
status code of
will be returned by the geocoder if you query it faster than it can
handle. (A full list of status codes is
To ensure you don't send queries too rapidly to the geocoder, you can
specify a delay between each geocode request. You can increase this
delay each time you receive a
status, and use a
while loop to ensure you've
successfully geocoded an address before iterating to the next one.
Changing the Base Country
The Maps geocoder is programmed to bias its results depending on the
For example, entering "syracuse" in the search box on maps.google.com
will geocode the city of "Syracuse, NY",
while entering the same query on maps.google.it
(Italy's domain) will
find the city of "Siracusa" in Sicily.
You would get the same results by sending that query through HTTP
geocoding to maps.google.it
instead of maps.google.com,
which you can do by modifying the
mapsUrl variable in the sample code above.
Note: You cannot send a request to a nonexistent maps.google.* server, so ensure that a country domain exists before redirecting your geocoding queries to it. For geocode support by country, check out this post.
Using the code above, you can
now geocode an address using Python, create a KML
<Placemark> out of it, and save
it to disk.
If you find that you need to geocode more than 15K addresses per day,
or that the Google geocoder doesn't cover the
regions you're interested in, then consider using additional geocoding
web services. A list of geocoding resources
Now that you know how to geocode your addresses, check out the articles on Using KML in Google Mashup Editor and Using PHP and MySQL to create KML. If you have any problems with or questions about this tutorial, please post in the KML Developer Support forum.