Includes enterprise licensing and support
The Maps Data API allows client applications to view and update maps and map features through the use of Google Data API feeds. These feeds are provided as URLs using the popular Atom standard. You programmatically create, alter and delete data using HTTP requests. The JavaScript client library sits on top of this HTTP protocol and enables API interactions using JavaScript methods.
Maps and map features are stored on Google's servers. A web interface to a user's maps is available through Google My Maps at http://maps.google.com/maps/mm.
Client libraries for other programming languages are also available, and are listed in the Developer's Guide introduction. If you're interested in understanding more about the underlying protocol that these libraries use, see the HTTP Protocol Guide.
This document is intended for JavaScript programmers who wish to interact with the Google Maps Data API to create, update, or delete maps and map features.
For reference information about the classes and methods provided by the client library, see the JSDoc. For general Maps Data API reference information, see the HTTP Protocol Reference.
Using the Maps Data API JavaScript client library requires the following:
We also recommend a JavaScript debugger.
Maps are stored and associated with user IDs attached to a Google Account. If you do not currently have a Google Account, sign up for one here.
The Maps Data API manipulates maps which appear within the My Maps feature on Google Maps. My Maps includes two types of maps: Public, and Unlisted. A sample My Map is shown below:
Figure 1: Google My Maps interface
You can use My Maps within your browser to inspect the state of your map after data updates.
Maps created with the Maps Data API are created as Public maps, meaning they will be indexed and may show up in search results. To change your maps to Unlisted mode, you must edit them through the My Maps web UI.
Before your client can use the client library, the client has to request the client library code from the server. There are two ways of requesting the client library:
google.load())Google's JavaScript client libraries for AJAX APIs can be loaded using a
common loader function, named google.load(). This function is
contained within the jsapi JavaScript file, which you must
reference from your document's <head>:
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
// Load the latest version of the Google Data JavaScript Client
google.load('gdata', '2.x', {packages: ['maps']});
function onGoogleDataLoad() {
// Put your code here
}
// Call function once the client has loaded
google.setOnLoadCallback(onGoogleDataLoad);
</script>
google.load is passed three parameters:
'gdata'."2" is the second-to-last revision of major
version 2."2.x" is the latest revision of major version
2."2.s" is the latest stable revision of
major version 2. We will occasionally declare a certain version of the
client library to be "stable," based on feedback we receive
from developers. However, that version may not have the latest features.
"2.0", "1.1", etc are
specific versions of the library, with a specified major and minor
revision number.gdata package(s). For the
Maps Data API, the value is 'maps'. This parameter is optional,
but is recommended, as it reduces the size of the JavaScript client by
loading only the required packages.google.setOnLoadCallback() is called once the Google Data
JavaScript client library has been fully loaded. This ensures that the browser
doesn't attempt to execute your code before the library is available. Your
client code must be placed inside the onGoogleDataLoad()
function.
For more information on the common loading mechanism, refer to the Loading the library section of Using the JavaScript Client Library.
The gdata client library can
also be loaded directly from the Google AJAX API loader without using
google.load. To do so, add the following tag (removing the
linebreaks) to your document's <head>:
<script type="text/javascript" src="http://www.google.com/jsapi?autoload= %7B%22modules%22%3A%5B%7B%22name%22%3A%22gdata%22%2C%22version%22%3A%222.x %22%2C%5B%22callback%22%3A%22onLoad%22%2C%22packages%22%3A%5B%22maps%22%5D %5D%7D%5D%7D"></script>
The onLoad value in the string above
defines the callback function to invoke once the API is loaded. Place your
client code within the onLoad() function to ensure that the
client library is fully loaded before you attempt to create a new
MapsService object. More information about autoloading is
available from the Autoloading section of the
AJAX APIs documentation.
The google.gdata.maps.MapsService class
(reference)
contains the methods necessary for accessing features and maps in the Google
Data API. This class also inherits authentication methods necessary for
OAuth Proxy
authentication for Google Data API gadgets.
To create a MapsService object:
var service = new google.gdata.maps.MapsService('docs-example');
where docs-example is the application's name. The application
name is used only as an identifier.
To simplify the code samples included in this document,
the MapsService object is assumed to have been declared as a
global variable, service.
Conceptual information about authentication is covered within the HTTP Protocol Guide.
Authentication for a web-based JavaScript client is accomplished through AuthSub for JavaScript. This authentication scheme generates a token that your client application uses to authenticate for each API call.
A simple login function could look like this:
function doLogin() {
var token = google.accounts.user.login('http://maps.google.com/maps/feeds');
}
Calling this function directs the user to a Google-hosted login page, where they are given the choice to allow or disallow access to their account from your application. If access is granted, they are directed back to the URL from which the login function was called.
Some additional authentication-related functions:
// Check whether the user is authenticated.
function checkLogin() {
return google.accounts.user.checkLogin('http://maps.google.com/maps/feeds');
}
// Log the user out.
function doLogout() {
google.accounts.user.logout();
}
// Optionally, include a callback parameter that
// gets called once the user is logged out.
function doLogoutAndRefresh() {
google.accounts.user.logout(function() {
window.location.reload();
});
}
The Google Maps Data API JavaScript client also supports authentication using the OAuth Proxy scheme, for use in Google Data API gadgets.
First, add an <OAuth> element to your gadget's
<ModulePrefs> section:
<ModulePrefs>
...
<OAuth>
<Service name="google">
<Access url="https://www.google.com/accounts/OAuthGetAccessToken" method="GET" />
<Request url="https://www.google.com/accounts/OAuthGetRequestToken?
scope=http://maps.google.com/maps/feeds/" method="GET" />
<Authorization url="https://www.google.com/accounts/OAuthAuthorizeToken?
oauth_callback=http://oauth.gmodules.com/gadgets/oauthcallback" />
</Service>
</OAuth>
...
</ModulePrefs>
Then, call the useOAuth() method on the MapsService
object:
var service = new google.gdata.maps.MapsService('docs-example');
service.useOAuth('google');
More information about using the OAuth Proxy in gadgets is available from Writing OAuth Gadgets.
The Google Maps Data API works with the concepts of maps and features.
Maps are containers for any number of features. A map has attributes that include a title, author, and the time this map was last updated, but does not include any geographic information or placemarks.
Features are objects on a map. A feature is associated with only one map, and is defined using KML. A feature is a KML placemark element and can contain geographic information, descriptive information (such as a title, icon, and description balloon contents), and associated geometry, such as lines or polygons.
Figure 2: Four features on a map
When using the Google Maps Data API:
You cannot request a feed of all features across all maps.
The Google Maps Data API can return a list of a user's maps as a feed object, or individual maps can be retrieved if their URL is known.
When retrieving a list of maps, a feed URL must be specified. The feed URL specified which set of the user's maps to return:
http://maps.google.com/maps/feeds/maps/default/owned
returns all maps created by the userhttp://maps.google.com/maps/feeds/maps/default/public
returns all public maps created by the userhttp://maps.google.com/maps/feeds/maps/default/unlisted
returns all unlisted maps created by the userMap feeds are requested by calling getMapFeed() on the
MapsService object. getMapFeed() takes as
parameters:
Upon success, getMapFeed() passes a feed object to the
continuation function. The list of maps can be accessed from the feed object's
feed parameter:
function listMaps() {
var list = document.createElement('ul');
var mapFeedUrl = 'http://maps.google.com/maps/feeds/maps/default/owned';
service.getMapFeed(mapFeedUrl, function(feedRoot) {
var feed = feedRoot.feed;
var entries = feed.getEntries();
for (var i = 0; i < entries.length; i++) {
var entry = entries[i];
var mapTitle = entry.getTitle().getText();
var listItem = document.createElement('li');
var listText = document.createTextNode(mapTitle);
listItem.appendChild(listText);
list.appendChild(listItem);
}
document.body.appendChild(list);
}, errorHandler);
}
If a map's URL is known, it can be requested directly by calling
getMapEntry() on the MapsService object. A single
map's URL has the following structure:
http://maps.google.com/maps/feeds/maps/userID/full/mapID
The URL of a specific map can be obtained from a feed of all maps by calling
getSelfLink().getHref() on an entry:
var mapFeedUrl = 'http://maps.google.com/maps/feeds/maps/default/owned';
var mapUrl;
service.getMapFeed(mapFeedUrl, function(feedRoot) {
var feed = feedRoot.feed;
var entries = feed.getEntries();
for (var i = 0; i < entries.length; i++) {
var entry = entries[i];
if (entry.getTitle().getText() == "Roadtrip 2009") {
mapUrl = entry.getSelfLink().getHref();
}
}
}, errorHandler);
To store all individual map URLs for later access:
// Create an array to hold individual map URLs.
var mapUrls = [];
var mapFeedUrl = 'http://maps.google.com/maps/feeds/maps/default/owned';
service.getMapFeed(mapFeedUrl, function(feedRoot) {
var feed = feedRoot.feed;
var entries = feed.getEntries();
for (var i = 0; i < entries.length; i++) {
var entry = entries[i];
mapUrls[i] = entry.getSelfLink().getHref();
}
}, errorHandler);
Note that the MapEntry object returned by the
getMapEntry() method is identical to that returned within a
getMapFeed() feed.
The following example retrieves a map entry and prints its title as an
h1 element on the page.
service.getMapEntry(mapUrl, function(entryRoot) {
var entry = entryRoot.entry;
var mapTitle = entry.getTitle().getText();
var titleElement = document.createElement('h1');
var titleText = document.createTextNode(mapTitle);
titleElement.appendChild(titleText);
document.body.appendChild(titleElement);
}, errorHandler);
To create a new map, call insertEntry() on the map feed. A title
must be specified; all other properties are optional. The example below
creates a new map with the title 'Roadtrip 2009' and inserts it into the
user's feed.
Note: All new maps are created with a public access level. The Maps Data API does not provide a method to create unlisted maps, or to modify an existing map's access level. Access levels can be modified using the My Maps web UI.
insertEntry() takes three parameters:
google.gdata.maps.MapEntry object
function addMap() {
var mapFeedUrl = 'http://maps.google.com/maps/feeds/maps/default/owned';
service.getMapFeed(mapFeedUrl, function(feedRoot){
var newMap = new google.gdata.maps.MapEntry();
var newMapTitle = new google.gdata.atom.Text();
newMapTitle.setText('Roadtrip 2009');
newMap.setTitle(newMapTitle);
feedRoot.feed.insertEntry(newMap, function() {window.location.reload();}, errorHandler);
}, errorHandler);
}
A map's fields can be updated by calling updateEntry() on the map
object. updateEntry()
must be passed a function to be called upon successful update, and a function
to be called if the update is unsuccessful.
function updateMap() {
service.getMapEntry(mapUrl, function(entryRoot) {
var entry = entryRoot.entry;
var newTitle = new google.gdata.atom.Text();
newTitle.setText('An updated title');
entry.setTitle(newTitle);
entry.updateEntry(loadMaps, errorHandler);
}, errorHandler);
}
To delete a map, call deleteEntry() on the
MapsService. Provide the URL of the map to be deleted, a function
to be called when the deletion has succeeded, and a function to call if the
deletion is not successful.
function deleteMap(i) {
var mapUrl = mapLinks[i];
service.deleteEntry(mapUrl, function() {
document.getElementById('app_status').innerHTML = 'Map deleted';
}, errorHandler);
}
Caution: Deleting a map also deletes all features associated with that map. There is no way to retrieve a map or its features once the map has been deleted.
Features are the objects that appear on a map. Each feature within the Maps
Data API is defined by a single KML <Placemark> element;
the Placemark must contain a name element and one of the
following elements:
The following KML elements are supported and are optional:
<coordinates>
<description>
<fill>
<IconStyle>
<LinearRing>
<LineStyle>
<outerBoundaryIs>
<outline>
<width>
<href> (within <IconStyle>)
<color> (as #AABBGGRR)
<Icon> (within <IconStyle>)
<Style>All other KML elements are silently removed when the KML is uploaded.
Each map contains a list of zero or more features: the placemarks, lines, and
shapes placed on the map. To retrieve the feed of a map's features, you must
pass the feed URL to the getFeatureFeed() method on the
MapsService object.
To obtain the URL of a map's feature feed, call
getContent().getUri() on a map entry:
var featureFeedUrl;
service.getMapEntry(mapUrl, function(entryRoot) {
var entry = entryRoot.entry;
featureFeedUrl = entry.getContent().getUri();
}, errorHandler);
With this information, you can retrieve a full list of features:
service.getFeatureFeed(featureFeedUrl, function(feedRoot) {
var feed = feedRoot.feed;
var features = feed.getEntries();
// Create an unordered list to hold
// the features' titles and contents.
var ul = document.createElement('ul');
for (var i = 0; i < features.length; i++) {
var feature = features[i];
var title = feature.getTitle().getText();
var content = feature.getContent().getText();
// Create a list item; add the title.
var li = document.createElement('li');
var titleNode = document.createTextNode(title);
li.appendChild(titleNode);
// Create a pre element; populate with content.
// Append the pre to the list item.
var pre = document.createElement('pre');
var contentNode = document.createTextNode(content);
pre.appendChild(contentNode);
li.appendChild(pre);
// Add the list item to the unordered list.
ul.appendChild(li);
}
// Add the unordered list to the document body.
document.body.appendChild(ul);
}, errorHandler);
Individual features can be retrieved with their identifying URLs. The URL can
be obtained from a map's feature feed by calling
getSelfLink().getHref() on the feature entry:
var featureUrl;
service.getFeatureFeed(featureFeedUrl, function(feedRoot) {
var feed = feedRoot.feed;
var entries = feed.getEntries();
for (var i = 0; i < entries.length; i++) {
var entry = entries[i];
if (entry.getTitle().getText() == "A fine feature") {
featureUrl = entry.getSelfLink().getHref();
}
}
}, errorHandler);
Once a feature's URL is known, call getFeatureEntry() on the
MapsService object. getFeatureEntry() takes three
parameters:
service.getFeatureEntry(featureUrl, function(featureRoot) {
var entry = featureRoot.entry;
var title = entry.getTitle().getText();
var content = entry.getContent().getText();
}, errorHandler);
Features are created by passing a FeatureEntry object to
insertEntry() on the feature feed. To create the entry:
google.gdata.maps.FeatureEntry object.setTitle() on the
FeatureEntry object.google.gdata.maps.KmlContent object.setText() on the
KmlContent object.setType() on the KmlContent object,
specifying TYPE_APPLICATION_VND_GOOGLE_EARTH_KML_XML.KmlContent object as the feature entry's content
using setContent().An example is shown below:
service.getFeatureFeed(featureFeedUrl, function(feedRoot) {
var newFeature = new google.gdata.maps.FeatureEntry();
// Set the name for this feature.
var title = new google.gdata.atom.Text();
title.setText('A new feature');
newFeature.setTitle(title);
// Define the content.
var kmlContent = new google.gdata.maps.KmlContent();
var kmlString = '<Placemark>'
+ '<Point>'
+ '<coordinates>-122.448425,37.802907,0</coordinates>'
+ '</Point>'
+ '</Placemark>';
kmlContent.setText(kmlString);
kmlContent.setType(google.gdata.maps.KmlContent.TYPE_APPLICATION_VND_GOOGLE_EARTH_KML_XML);
// Set the KML as the new feature's content.
newFeature.setContent(kmlContent);
// Insert the new feature into the feature feed.
feedRoot.feed.insertEntry(newFeature, function () {window.location.reload();}, errorHandler);
}, errorHandler);
A feature can be updated by calling updateEntry() on the feature
entry after the object has been updated. updateEntry()
takes a function to call upon successful update, and a function to be called
if the update fails.
<name> ElementA feature's name, or title, is defined by its <name>
element in KML. However, in the Maps Data API JavaScript client, the
FeatureEntry uses the entry's title field instead.
Updates to the <name> element in the KML will be silently
ignored.
service.getFeatureEntry(featureLink, function(featureRoot) {
var entry = featureRoot.entry;
var name = new google.gdata.atom.Text();
name = 'Roadtrip 2009, updated';
entry.setTitle(name);
entry.updateEntry(function() {window.location.reload()}, errorHandler);
}, errorHandler);
All elements other than <name> must be updated by editing
the feature's KML.
To pass KML to the entry:
google.gdata.maps.KmlContent object.setText().setType() on the object, specifying
TYPE_APPLICATION_VND_GOOGLE_EARTH_KML_XML.KmlContent object as the feature entry's
content.The following example uses the content of a form (whose textarea
element has the name formInput) to update a feature entry.
function updateKml(form, featureLink) {
service.getFeatureEntry(featureLink, function(featureRoot) {
var entry = featureRoot.entry;
var kmlContent = new google.gdata.maps.KmlContent();
var updatedKml = form.formInput.value;
kmlContent.setText(updatedKml);
kmlContent.setType(google.gdata.maps.KmlContent.TYPE_APPLICATION_VND_GOOGLE_EARTH_KML_XML);
entry.setContent(kmlContent);
entry.updateEntry(function() {window.location.reload()}, errorHandler);
}, errorHandler);
}
To delete a feature, call deleteEntry() on the feature entry,
passing a function to be called upon successful deletion of the feature, and a
function to be called if the deletion is unsuccessful.
service.getFeatureEntry(featureLink, function(featureRoot) {
var entry = featureRoot.entry;
entry.deleteEntry(function() {
document.getElementById('app_status').innerHTML = 'Feature deleted';
}, errorHandler);
}, errorHandler);
Caution: There is no way to retrieve a feature once it has been deleted.
A JavaScript debugger is highly recommended while developing. Some free debuggers include Firebug for Firefox, Microsoft Script Debugger for IE, and the built-in tools in Safari and Google Chrome.
Many methods call for an error handler function as a parameter. If an error
occurs when calling one of these methods, the browser's Error
object will be passed to your specified error handler. If the error is from an
HTTP response, it will include a cause parameter. You can use the
information from the Error object to help troubleshoot your
application.
function errorHandler(e) {
document.getElementById('errors').innerHTML =
'Error: ' + (e.cause ? e.cause.statusText : e.message);
}
More information about the Google Maps Data API and/or the Google Data JavaScript client is available from the following sources: