• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# -*- coding: utf-8 -*-
2#
3#  Copyright 2014 Google Inc. All Rights Reserved.
4#
5# Licensed under the Apache License, Version 2.0 (the "License");
6# you may not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9#      http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS,
13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
16
17"""Simple command-line sample for Google Maps Engine.
18
19This sample code demonstrates use of the Google Maps Engine API.  For more
20information on the API, see developers.google.com/maps-engine/documentation/
21
22These samples allow you to
231) List projects you have access to
242) List tables in a given project.
253) Upload a shapefile to create a Table asset.
26
27Usage:
28  $ python maps_engine.py [-p project_id] [-s shapefile]
29
30If you do not enter a shapefile, it will upload the included "polygons".
31
32You can also get help on all the command-line flags the program understands
33by running:
34
35  $ python maps_engine.py --help
36
37To get detailed log output run:
38
39  $ python maps_engine.py -p 123456 --logging_level=DEBUG
40"""
41
42__author__ = "jlivni@google.com (Josh Livni)"
43
44import argparse
45import json
46import logging
47import sys
48import time
49
50from googleapiclient import sample_tools
51from googleapiclient.http import MediaFileUpload
52
53logging.basicConfig(level=logging.INFO)
54
55# Declare command-line flags.
56argparser = argparse.ArgumentParser(add_help=False)
57argparser.add_argument("-p", "--project_id", help="optional GME Project ID")
58argparser.add_argument("-s", "--shapefile", help="Shapefile (without the .shp)")
59
60SUCCESSFUL_STATUS = ["processed", "complete", "ready"]
61
62
63class MapsEngineSampleException(Exception):
64  """Catch this for failures specific to this sample code."""
65
66
67def ListProjects(service):
68  """List the projects available to the authorized account.
69
70  Args:
71    service: The service object built by the Google API Python client library.
72  """
73  projects = service.projects().list().execute()
74  logging.info(json.dumps(projects, indent=2))
75
76
77def ListTables(service, project_id):
78  """List the tables in a given project.
79
80  Args:
81    service: The service object built by the Google API Python client library.
82    project_id: string, id of the GME project.
83  """
84
85  tables = service.tables().list(projectId=project_id).execute()
86  logging.info(json.dumps(tables, indent=2))
87
88
89def UploadShapefile(service, project_id, shapefile_prefix):
90  """Upload a shapefile to a given project, and display status when complete.
91
92  Args:
93    service: The service object built by the Google API Python client library.
94    project_id: string, id of the GME project.
95    shapefile_prefix: string, the shapefile without the .shp suffix.
96
97  Returns:
98    String id of the table asset.
99  """
100  # A shapefile is actually a bunch of files; GME requires these four suffixes.
101  suffixes = ["shp", "dbf", "prj", "shx"]
102  files = []
103  for suffix in suffixes:
104    files.append({
105        "filename": "%s.%s" % (shapefile_prefix, suffix)
106    })
107  metadata = {
108      "projectId": project_id,
109      "name": shapefile_prefix,
110      "description": "polygons that were uploaded by a script",
111      "files": files,
112      # You need the string value of a valid shared and published ACL
113      # Check the "Access Lists" section of the Maps Engine UI for a list.
114      "draftAccessList": "Map Editors",
115      "tags": [shapefile_prefix, "auto_upload", "kittens"]
116  }
117
118  logging.info("Uploading metadata for %s", shapefile_prefix)
119  response = service.tables().upload(body=metadata).execute()
120  # We have now created an empty asset.
121  table_id = response["id"]
122
123  # And now upload each of the files individually, passing in the table id.
124  for suffix in suffixes:
125    shapefile = "%s.%s" % (shapefile_prefix, suffix)
126    media_body = MediaFileUpload(shapefile, mimetype="application/octet-stream")
127    logging.info("uploading %s", shapefile)
128
129    response = service.tables().files().insert(
130        id=table_id,
131        filename=shapefile,
132        media_body=media_body).execute()
133
134  # With all files uploaded, check status of the asset to ensure it's processed.
135  CheckAssetStatus(service, "tables", table_id)
136  return table_id
137
138
139def CheckAssetStatus(service, asset_type, asset_id):
140  endpoint = getattr(service, asset_type)
141  response = endpoint().get(id=asset_id).execute()
142  status = response["processingStatus"]
143  logging.info("Asset Status: %s", status)
144  if status in SUCCESSFUL_STATUS:
145    logging.info("asset successfully processed; the id is %s", asset_id)
146  else:
147    logging.info("Asset %s; will check again in 5 seconds", status)
148    time.sleep(5)
149    CheckAssetStatus(service, asset_type, asset_id)
150
151
152def main(argv):
153  # Authenticate and construct service.
154  service, flags = sample_tools.init(
155      argv, "mapsengine", "v1", __doc__, __file__, parents=[argparser],
156      scope="https://www.googleapis.com/auth/mapsengine")
157
158  if flags.project_id:
159    # ListTables(service, flags.project_id)
160    # The example polygons shapefile should be in this directory.
161    filename = flags.shapefile or "polygons"
162    table_id = UploadShapefile(service, flags.project_id, filename)
163    logging.info("Sucessfully created table: %s", table_id)
164  else:
165    ListProjects(service)
166  return
167
168
169if __name__ == "__main__":
170  main(sys.argv)
171