Hide

Hello, World

Before you start

Follow the getting-started instructions to register a project on the Google APIs Console.

Overview

Requests to the Google Maps Engine API are HTTP requests with a base URI of:

  https://www.googleapis.com/mapsengine/v1

The remainder of the URI path, including any parameters required, is determined by the resource you are accessing and the operation you are performing. Refer to the reference documentation for details.

Authorization

Most requests must be accompanied by an OAuth 2.0 access token, passed as the value of an Authorization header:

  GET https://www.googleapis.com/mapsengine/v1/assets
  Authorization: Bearer token

Refer to the authentication guide for information on retrieving a valid token.

Requests for data whose access level has been set to public do not need an authorization token. If no authorization token is given, the request must include an API key as the value of a key URI parameter. See the guide to accessing public data for more information.

URL encoding

All URIs must be URL encoded. For example, this request will fail:

GET https://www.googleapis.com/mapsengine/v1/tables/tableId/features?where=age > 10

This request will work as intended:

GET https://www.googleapis.com/mapsengine/v1/tables/tableId/features?where=age+%3E+10

URIs are limited to 2048 characters in length after encoding.

Content type

Any request that contains a JSON body must set an additional HTTP content type header:

Content-Type: application/json

Hello world

Data that is made public in Google Maps Engine is accessible via the API without authentication. Only an API key is required. The examples on this page use publicly-accessible data in Google Maps Engine.

The following URI requests a set of features from a particular asset:

  https://www.googleapis.com/mapsengine/v1/tables/12421761926155747447-06672618218968397709/features
  ?maxResults=500
  &version=published
  &key={YOUR_API_KEY}

You can send the above sample request from your browser, with a pre-filled API key that works only from this documentation site. Try it now.

The response is a JSON object containing the set of features from the specified table.

Alternatively, copy the request URL without an API key and replace {YOUR_API_KEY} with your API key. (That is the key for browser apps available for your project in the Google APIs Console. See the section on API keys in the getting-started guide.) Then paste the URL into your browser's address bar.

cURL

cURL is a command-line tool that can be used to make HTTP requests. You can use it to make requests against the Google Maps Engine API as follows:

  $ curl "https://www.googleapis.com/mapsengine/v1/tables/12421761926155747447-06672618218968397709/features?maxResults=500&version=published&key=YOUR_API_KEY"

Java

There are a few choices when developing against the Google Maps Engine API with Java. You can choose to use pure Java and simply make the HTTP calls yourself. However, we recommend using the Google Maps Engine API client library for Java, along with the wrapper library.

API client library

In this example, we use the Google API client library for Java to communicate with the Google Maps Engine server. The code queries a public table for features within a certain radius and iterates over the results, printing the coordinates and the contents of the Fcility_nam column.

import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.mapsengine.MapsEngine;
import com.google.api.services.mapsengine.MapsEngineRequestInitializer;
import com.google.api.services.mapsengine.model.Feature;
import com.google.api.services.mapsengine.model.FeaturesListResponse;
import com.google.api.services.mapsengine.model.GeoJsonPoint;

import java.io.IOException;

/** Java "Hello, world!" example using the client library */
public class HelloWorld {

  static final String SAMPLE_TABLE_ID = "12421761926155747447-06672618218968397709";
  static final String PUBLIC_API_KEY = "YOUR_API_KEY_GOES_HERE";

  public static void main(String[] args) throws Exception {
    HttpTransport transport = new NetHttpTransport();
    JsonFactory jsonFactory = new GsonFactory();

    // This request initializer will ensure the API key is sent with every HTTP request.
    MapsEngineRequestInitializer apiKeyInitializer =
        new MapsEngineRequestInitializer(PUBLIC_API_KEY);

    MapsEngine engine = new MapsEngine.Builder(transport, jsonFactory, null)
        .setMapsEngineRequestInitializer(apiKeyInitializer)
        .setApplicationName("Google-MapsEngineSample/1.0")
        .build();

    readFeaturesFromTable(engine);
  }

  public static void readFeaturesFromTable(MapsEngine me) throws IOException {
    // Query the table for offices in WA that are within 100km of Perth.
    FeaturesListResponse featResp =  me.tables().features().list(SAMPLE_TABLE_ID)
        .setVersion("published")
        .setWhere("State='WA' AND ST_DISTANCE(geometry,ST_POINT(115.8589,-31.9522)) < 100000")
        .execute();

    for (Feature feat : featResp.getFeatures()) {
      System.out.println(
          "Properties: " + feat.getProperties().toString() + "\n\t" +
          "Name: " + feat.getProperties().get("Fcilty_nam") + "\n\t" +
          "Geometry Type: " + feat.getGeometry().getType());

      if (feat.getGeometry() instanceof GeoJsonPoint)  {
        GeoJsonPoint point = (GeoJsonPoint) feat.getGeometry();
        System.out.println("\t" +
            "Longitude: " + point.getCoordinates().get(0) + ", " +
            "Latitude: " +  point.getCoordinates().get(1));
      } else {
        System.out.println("Only points are expected in this table!");
        return;
      }
    }
  }
}

You can download the client library directly or add the dependency using Maven or Gradle.

Maven

<dependency>
    <groupId>com.google.apis</groupId>
    <artifactId>google-api-services-mapsengine</artifactId>
    <version>(insert latest version)</version>
</dependency>

Gradle

repositories {
    mavenCentral()
}

dependencies { compile 'com.google.apis:google-api-services-mapsengine:(insert latest version)' ... }

You can find the latest version by searching Maven Central or Gradle, Please.

Wrapper

The API client libraries are generated automatically based on the API specifications. Unfortunately, computers don't always write the best code so we have built a wrapper library that makes it even easier to use the Google Maps Engine API in Java.

The key differences are:

  • Manipulating geometries can be done using POJOs instead of Lists of Lists of doubles.
  • Helper classes exist for common tasks, such as automatic retry of HTTP requests that fail due to rate limiting.
  • A security class exists to handle escaping and quoting of variables intended to be used in database queries.
  • The library is open source, so you can contribute your suggestions for use by other developers.

Get the wrapper library from GitHub or Maven Central.

import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.mapsengine.MapsEngine;
import com.google.api.services.mapsengine.MapsEngineRequestInitializer;
import com.google.api.services.mapsengine.model.Feature;
import com.google.api.services.mapsengine.model.FeaturesListResponse;
import com.google.api.services.mapsengine.model.GeoJsonMultiPolygon;
import com.google.api.services.mapsengine.model.GeoJsonPolygon;
import com.google.maps.clients.BackOffWhenRateLimitedRequestInitializer;
import com.google.maps.clients.mapsengine.Security;
import com.google.maps.clients.mapsengine.geojson.MultiPolygon;
import com.google.maps.clients.mapsengine.geojson.Polygon;

import java.util.Collections;
import java.util.List;

/** Java "Hello, world!" example using the client library and supplementary wrapper. */
class HelloWorldWrapper {

  static final String SAMPLE_TABLE_ID = "12421761926155747447-14043129889721455791";
  static final String PUBLIC_API_KEY = "YOUR_API_KEY_HERE";

  public static void main(String[] args) throws Exception {
    HttpTransport transport = new NetHttpTransport();
    JsonFactory jsonFactory = new GsonFactory();

    // This request initializer will ensure the API key is sent with every HTTP request.
    MapsEngineRequestInitializer apiKeyInitializer =
        new MapsEngineRequestInitializer(PUBLIC_API_KEY);

    // This request initializer will automatically retry any request that is denied by the server
    // due to rate limiting / quota throttling.  It will back off exponentially with each denial.
    HttpRequestInitializer exponentialBackOff = new BackOffWhenRateLimitedRequestInitializer();

    MapsEngine engine = new MapsEngine.Builder(transport, jsonFactory, exponentialBackOff)
        .setApplicationName("Google-MapsEngineSample/1.0")
        .setMapsEngineRequestInitializer(apiKeyInitializer)
        .build();

    List<Polygon> hawaiianIslands = readStateShapes(engine, "Hawaii");
    Polygon maui = hawaiianIslands.get(6);
    System.out.println("Found Maui!");
  }

  private static List<Polygon> readStateShapes(MapsEngine engine, String state) throws Exception {
    // Query using an "unsafe" external parameter, correctly escaped and quoted.
    FeaturesListResponse response = engine.tables().features().list(SAMPLE_TABLE_ID)
        .setVersion("published")
        .setWhere(String.format("NAME = %s", Security.escapeAndQuoteString(state)))
        .execute();

    // Grab the list of features (rows) returned by the API.
    List<Feature> features = response.getFeatures();

    // For this example, we should only ever get one row returned.
    if (features.size() == 1) {
      Feature feature = features.get(0);
      // Convert from the Maps Engine shape representations to List<Polygon>.
      if (feature.getGeometry() instanceof GeoJsonMultiPolygon) {
        return new MultiPolygon(feature).getPolygons();
      } else if (feature.getGeometry() instanceof GeoJsonPolygon) {
        return Collections.singletonList(new Polygon(feature));
      } else {
        throw new IllegalStateException("States should be composed of one or more polygons.");
      }
    } else {
      throw new IllegalArgumentException("Did not find exactly one state matching the query.");
    }
  }
}

Python

We recommend using our API client library for Python. Refer to the setup guide and the reference documentation.

The following example requests all of the features in the specified table, then loops through and displays the coordinates for each feature.

from apiclient import discovery

service = discovery.build('mapsengine', 'v1',
                          developerKey=YOUR_API_KEY_GOES_HERE)

# Read the location of every Feature in a Table.
features = service.tables().features()
request = features.list(id='12421761926155747447-06672618218968397709',
                        maxResults=500, version='published')
while request is not None:
  response = request.execute()
  for feature in response['features']:
    print feature['geometry']['coordinates']

  # Is there an additional page of features to load?
  request = features.list_next(request, response)

JavaScript

The Google APIs Client Library for JavaScript provides a convenient way of using the Google Maps Engine API. See the related developer's guide.

The following example uses the client library. It requests all features from the specified table, then loops through them and displays their coordinates and name.

<html>
 <head>
   <script>
     function appendResults(features) {
       var results = document.getElementById('results');
       features.forEach(function(feature) {
         results.appendChild(document.createElement('pre'))
                .appendChild(document.createTextNode(JSON.stringify(feature)));
       });
     }

     function makeRequest() {
       var request = gapi.client.mapsengine.tables.features.list({
         'id': '12421761926155747447-06672618218968397709',
         'maxResults': 500,
         'version': 'published'
       });
       request.execute(function(response) {
         appendResults(response.result.features);
       });
     }

     function load() {
       gapi.client.setApiKey('YOUR_API_KEY_GOES_HERE');
       gapi.client.load('mapsengine', 'v1', makeRequest);
     }
   </script>
   <script src="https://apis.google.com/js/client.js?onload=load"></script>
 </head>
 <body>
   <div id="results"></div>
 </body>
</html>


JavaScript cross-domain requests

The Google Maps Engine API supports a callback parameter for all requests, which returns JSONP-compatible data. The value of the callback parameter must be that of a JavaScript function in the global scope. For more information about JSONP, you can start with the Wikipedia article.

The following example includes a callback parameter that will call the my_func function in your app:

  https://www.googleapis.com/mapsengine/v1/tables/12421761926155747447-06672618218968397709/features
       ?maxResults=500
       &version=published
       &key={YOUR_API_KEY}
       &callback=my_func

The Google Maps Engine API also supports cross-origin resource sharing (CORS) by setting a permissive Access-Control-Allow-Origin HTTP header.

PHP

The Google APIs Client Library for PHP provides a convenient way of using the Google Maps Engine API. See the client library on GitHub and the related developer's guide.

The following PHP example uses the client library. It requests all features from the specified table, then loops through them and displays their coordinates and name.

<?php

set_include_path("google-api-php-client/src/" . PATH_SEPARATOR . get_include_path());
require_once 'Google/Client.php';
require_once 'Google/Service/MapsEngine.php';

$apiKey = "YOUR_API_KEY_GOES_HERE";

$client = new Google_Client();
$client->setApplicationName("Google-PhpMapsEngineSample/1.0");
$client->setDeveloperKey($apiKey);

$service = new Google_Service_MapsEngine($client);

$optParams = array('maxResults' => 500, 'version' => 'published');
$results = $service->tables_features->listTablesFeatures("12421761926155747447-06672618218968397709", $optParams);

print_r($results);

?>

Send feedback about...

Google Maps Engine API (Deprecated)