KEMBAR78
Amazon Location Developer Guide - Pdfhhhfss | PDF | Internet Privacy | Esri
0% found this document useful (0 votes)
414 views136 pages

Amazon Location Developer Guide - Pdfhhhfss

Hhgf
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
414 views136 pages

Amazon Location Developer Guide - Pdfhhhfss

Hhgf
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 136

Amazon Location Service

Developer Guide
Amazon Location Service Developer Guide

Amazon Location Service: Developer Guide


Copyright © Amazon Web Services, Inc. and/or its affiliates. All rights reserved.

Amazon's trademarks and trade dress may not be used in connection with any product or service that is not
Amazon's, in any manner that is likely to cause confusion among customers, or in any manner that disparages or
discredits Amazon. All other trademarks not owned by Amazon are the property of their respective owners, who may
or may not be affiliated with, connected to, or sponsored by Amazon.
Amazon Location Service Developer Guide

Table of Contents
........................................................................................................................................................ v
What is Amazon Location Service? ....................................................................................................... 1
Key features .............................................................................................................................. 1
Related services ......................................................................................................................... 2
How Amazon Location Service Works ................................................................................................... 3
Overview ................................................................................................................................... 3
Maps ................................................................................................................................ 4
Places ............................................................................................................................... 5
Geofences ......................................................................................................................... 6
Trackers ............................................................................................................................ 6
Component definitions ............................................................................................................... 7
Maps ................................................................................................................................ 7
Places ............................................................................................................................... 8
Geofences ......................................................................................................................... 8
Trackers ............................................................................................................................ 9
Regions and endpoints ............................................................................................................... 9
Regions ............................................................................................................................. 9
Endpoints ........................................................................................................................ 10
Data providers ................................................................................................................................. 11
Data privacy ............................................................................................................................ 11
Esri ......................................................................................................................................... 11
Terms of use .................................................................................................................... 12
Reporting errors and discrepancies to Esri ........................................................................... 12
Esri map styles ................................................................................................................. 12
HERE ...................................................................................................................................... 14
Terms of use .................................................................................................................... 15
Reporting errors and discrepancies to HERE ......................................................................... 15
HERE map styles .............................................................................................................. 15
Data attribution ....................................................................................................................... 15
Common use cases ........................................................................................................................... 16
User engagement and geomarketing applications ......................................................................... 16
Asset tracking applications ........................................................................................................ 17
Delivery applications ................................................................................................................. 18
Getting started ................................................................................................................................ 20
Sign up for AWS ...................................................................................................................... 20
Manage access to your AWS resources ........................................................................................ 20
Grant access to Amazon Location Service .................................................................................... 21
Next steps ............................................................................................................................... 22
Accessing Amazon Location ............................................................................................................... 23
Allowing unauthenticated guest access using Amazon Cognito ....................................................... 23
Create an Amazon Cognito identity pool ............................................................................. 24
Using the Identity Pool from JavaScript .............................................................................. 25
Next steps ....................................................................................................................... 26
Using Amazon Location ..................................................................................................................... 27
Using maps ............................................................................................................................. 27
Step 1: Create a map resource ........................................................................................... 27
Step 2: Creating an unauthenticated identity pool ................................................................ 29
Step 3: Display a map in your application ............................................................................ 30
Geocoding, reverse geocoding, and searching .............................................................................. 63
Step 1: Create a place index resource .................................................................................. 63
Step 2: Creating an unauthenticated identity pool ................................................................ 64
Step 3: Geocoding and reverse geocoding ........................................................................... 65
Geofencing an area of interest ................................................................................................... 68
Step 1: Add geofences ...................................................................................................... 68

iii
Amazon Location Service Developer Guide

Step 2: Start tracking ....................................................................................................... 71


Step 3: Link a tracker to a geofence collection ..................................................................... 75
Step 4: Evaluate device positions against geofences .............................................................. 76
Reacting to geofence events with EventBridge ............................................................................. 77
Create event rules ............................................................................................................ 77
Event examples ................................................................................................................ 78
Monitoring with CloudWatch ..................................................................................................... 79
Metrics ............................................................................................................................ 80
View metrics .................................................................................................................... 80
Create CloudWatch alarms ................................................................................................. 81
Metric output examples .................................................................................................... 82
Using CloudTrail with Amazon Location ...................................................................................... 83
Amazon Location Service Information in CloudTrail .............................................................. 83
Understanding Amazon Location Service Log File Entries ....................................................... 84
Tracking using MQTT ................................................................................................................ 86
Prerequisite ..................................................................................................................... 87
Create a Lambda function ................................................................................................. 87
Create an AWS IoT Core rule ............................................................................................. 89
Optional: Test your AWS IoT Core rule ................................................................................ 90
Managing resources .................................................................................................................. 90
Maps ............................................................................................................................... 90
Place indexes ................................................................................................................... 93
Geofence collections ......................................................................................................... 95
Trackers ......................................................................................................................... 100
Best practices ................................................................................................................................. 104
Security ................................................................................................................................. 104
Resource management ............................................................................................................ 104
Billing and cost management ................................................................................................... 104
Security ......................................................................................................................................... 105
Data protection ...................................................................................................................... 105
Data retention ................................................................................................................ 106
Configuration and vulnerability analysis ............................................................................ 106
Encryption for data at rest .............................................................................................. 106
Encryption for data in transit ........................................................................................... 106
Key management ........................................................................................................... 107
Identity and Access Management .............................................................................................. 107
Audience ....................................................................................................................... 107
Authenticating with identities .......................................................................................... 107
Managing access using policies ......................................................................................... 109
How Amazon Location Service works with IAM ................................................................... 111
Identity-based policy examples ........................................................................................ 114
Troubleshooting ............................................................................................................. 118
Incident response ................................................................................................................... 120
Logging and Monitoring .................................................................................................. 120
Compliance validation ............................................................................................................. 120
Resilience .............................................................................................................................. 121
Infrastructure security ............................................................................................................. 121
Security best practices ............................................................................................................ 122
Detective best practices ................................................................................................... 122
Preventive best practices ................................................................................................. 122
Service quotas ................................................................................................................................ 123
Amazon Location APIs ..................................................................................................................... 129
Document History .......................................................................................................................... 130
AWS glossary ................................................................................................................................. 131

iv
Amazon Location Service Developer Guide

Amazon Location Service is in preview release and is subject to change.

v
Amazon Location Service Developer Guide
Key features

What is Amazon Location Service?


Welcome to the Amazon Location Service Developer Guide.

Amazon Location Service lets you add location data to applications, which includes capabilities such
as maps, points of interest, geocoding, routing, geofences, and tracking. Amazon Location provides
cost-effective location-based services (LBS) using high-quality data from global, trusted providers Esri
and HERE. With affordable data, tracking and geofencing capabilities, and built-in metrics for health
monitoring, you can build sophisticated location-enabled applications.

With Amazon Location, you retain control of your organization’s data. Amazon Location anonymizes all
queries sent to data providers by removing customer metadata and account information. Additionally,
sensitive tracking and geofencing location information, such as facility, asset, and personnel locations,
never leaves your AWS account at all. This helps you shield sensitive information from third parties,
protect user privacy, and reduce your application’s security risks. With Amazon Location, neither Amazon
nor third parties have rights to sell your data or use it for advertising.

Amazon Location is fully integrated with services such as AWS CloudTrail, Amazon CloudWatch,
Amazon EventBridge, and AWS Identity and Access Management (IAM). Amazon Location simplifies
your development workflow with data integration, and fast tracks apps to production with built-in
monitoring, security and compliance features.

For information about Amazon Location Service highlights, product details, and pricing, see the Amazon
Location service page.

Key features in Amazon Location


Amazon Location provides the following features:

Maps

Amazon Location Service Maps lets you visualize location information and is the foundations of
many location-based service capabilities. Amazon Location Service provides map tiles of different
styles sourced from global location data providers Esri and HERE.

Places

Amazon Location Service Places lets you integrate search functionality into your application,
convert addresses into geographic coordinates in latitude and longitude (geocoding), and convert a
coordinate into a street address (reverse geocoding). Amazon Location Service sources high-quality
geospatial data from Esri and HERE to support Places functions.

Geofencing

Amazon Location Service Geofences lets you give your application the ability to detect and act when
a device enters or exits a defined geographical boundary known as a geofence. Automatically send
an entry or exit event to Amazon EventBridge when a geofence breach is detected. This lets you
initiate downstream actions such as sending a notification to a target.

Trackers

Amazon Location Service Trackers lets you retrieve current and historical location of devices
running your tracking-enabled application. You can also link Trackers with Amazon Location Service
Geofences to automatically evaluate location updates from your devices against your geofences.

1
Amazon Location Service Developer Guide
Related services

While using Trackers, sensitive location information of your tracked devices never leaves your AWS
account. This helps protect sensitive information from third parties, protect user privacy, and reduce
security risks.

Routing coming soon

Amazon Location Service Routes lets you find routes and estimate travel time based on up-to-date
roadway and live traffic information. Build features that allow your application to request the travel
time, distance, and directions between any two locations.

Services you can use with Amazon Location


You can use the following services along with Amazon Location Service:

Integrated Monitoring and Management

Amazon Location Service is integrated with Amazon CloudWatch and Amazon EventBridge for easy
monitoring and data management:
• Amazon CloudWatch – View metrics on service usage and health, including requests,
latency, faults, and logs. For more information, see the section called “Monitoring with
CloudWatch” (p. 79).
• AWS CloudTrail – Log and monitor your API calls, which includes actions taken by a user, role
or an AWS service. For more information, see the section called “Using CloudTrail with Amazon
Location” (p. 83)
• Amazon EventBridge – Enable an event-driven application architecture so you can use
AWS Lambda functions to activate other parts of your application and work flows. For more
information, see the section called “Reacting to geofence events with EventBridge” (p. 77).

Developer Tools

Amazon Location Service offers a variety of tools for developers to build location-enabled
applications. These include the standard AWS SDKs, front-end mobile and web SDKs, and sample
code to combine it with open source libraries such as Mapbox GL. Use the Amazon Location Service
console to learn about resources, and to get started with a visual and interactive learning tool.

2
Amazon Location Service Developer Guide
Overview

How Amazon Location Service Works


With Amazon Location Service, you can securely add location data to your application. You can begin
exploring some of the capabilities using the visual and interactive tool available on the Amazon Location
console. Using the explore tool, you can manipulate a default map, search for points of interest, draw
geofences around areas of interest, and simulate sending device location to a tracker.

When you are ready to build, you can create your resources and choose from a variety of map styles
and data providers. After you have your resources, you can then install the SDK that matches your
development environment, and start using the Amazon Location APIs using instructions from this guide.
Additionally, you can integrate monitoring using Amazon CloudWatch and AWS CloudTrail .

The topics in this section provide you an overview of the Amazon Location core components and how to
get started with each component.

Topics
• Overview (p. 3)
• Amazon Location core components defined (p. 7)
• Amazon Location Regions and endpoints (p. 9)

Overview
Amazon Location Service offers four types of AWS resources for your location data needs. You can create
one or more of these resources using the Amazon Location console, the Amazon Location APIs, or the
SDKs

3
Amazon Location Service Developer Guide
Maps

For example:

• Amazon Location Service Maps allows you to select a map from a map provider to use on your mobile
or web application.
• Amazon Location Service Places lets you select a data provider for geocoding, reverse geocoding, and
searching for points of interest.
• Amazon Location Service Geofences allow you to define areas of interest as a virtual boundary on a
map. You can then evaluate locations against them and get notifications of entry and exit events.
• Amazon Location Service Trackers receive location updates from your devices. You can link trackers
to collections of goefences so that all position updates are automatically evaluated against all your
geofences.

Access to your Amazon Location resources is managed and authenticated using permission policies,
which you can set for each IAM user. You can also organize your resources into resource groups to
manage and automate tasks as your resource numbers grow. For more information about managing AWS
resources, see What are AWS Resource Groups? In the AWS Resource Groups User Guide.

Location data flows through Amazon Location resources using a format that's compliant to a standard
geospatial data format called GeoJSON RFC 7946, which encodes geographic data into a standard
definition. GeoJSON is a subset of JSON, and can be used by any programming language or parsed
natively using JavaScript.

Location is defined using coordinates that follow the World Geodetic System (WGS 84), commonly used
as the standard coordinate reference system for Global Positioning System (GPS) services.

The following sections provide overview descriptions about how the components of Amazon Location
work.

Maps
The following shows how map resources are created and used:

4
Amazon Location Service Developer Guide
Places

1. You create a map resource in your AWS account by selecting a map style from a data provider.
2. You can then select and install the SDK that matches your development environment and
applications. For more information about available options, see the topic about Accessing Amazon
Location.
3. To display a map in your application, you must combine a map resource with a rendering library such
as Mapbox GL, or Tangram. For more information. see the topic about Using maps.
4. You can then integrate monitoring using services such as Amazon CloudWatch and using AWS
CloudTrail with Amazon Location. For more information see, the section called “Monitoring with
CloudWatch” (p. 79) and the section called “Using CloudTrail with Amazon Location” (p. 83).

Places
Place index resources enable geographical search functionality. You can use the place index APIs to
search for:

• Points of interest, such as restaurants and landmarks, and receive a list of options ordered by
relevance.
• A street address, and receive a latitude and longitude for that address. This is otherwise known as
geocoding.
• A latitude and longitude, and receive the associated street address. This is otherwise known as reverse
geocoding.

The following shows how place resources are created and used:

1. First, you create a place index resource in your AWS account by selecting a data provider.
2. You can then select and install the SDK that matches your development environment and
applications. For more information about available options, see the topic about Accessing Amazon
Location.
3. Start using the Amazon Location Places APIs . For more information, see the topic on the section
called “Geocoding, reverse geocoding, and searching” (p. 63).
4. You can then integrate monitoring using services such as Amazon CloudWatch and AWS CloudTrail.
For more information see, the section called “Monitoring with CloudWatch” (p. 79) and the section
called “Using CloudTrail with Amazon Location” (p. 83).

5
Amazon Location Service Developer Guide
Geofences

Geofences
Geofence collection resources allow you to store and manage geofences—virtual boundaries on a map.
You can evaluate locations against a geofence collection resource and get notifications when the location
update crosses the boundary of any of the geofences in the geofence collection.

The following shows how geofence collection resources are created and used:

1. You create a geofence collection resource in your AWS account.


2. You add geofences to that collection. You can do so by either using the geofence upload tool on the
Amazon Location console, or by using the Amazon Location Geofences API. For more information
about available options, see the topic about Accessing Amazon Location.
3. You can start evaluating locations against all your geofences. When a location update crosses the
boundaries of one or more goefences, you geofence collection resource will emit one of the following
geofence event types on Amazon EventBridge:
• ENTER – One event is generated for each geofence where the location update crosses its boundary
by entering it.
• EXIT – One event is generated for each geofence where the location update crosses its boundary by
exiting it.

For more information, see the section called “Reacting to geofence events with EventBridge” (p. 77).
You can also integrate monitoring using services such as Amazon CloudWatch and AWS CloudTrail. For
more information see, the section called “Monitoring with CloudWatch” (p. 79) and the section called
“Using CloudTrail with Amazon Location” (p. 83).

Trackers
A tracker resource receives location updates from devices to support queries for current location and
location history. You can link trackers to your geofence collection resources so that all position updates
are automatically evaluated against all your geofences.

The following shows how tracker resources are created and used:

1. First, you create a tracker resource in your AWS account.


2. Next you have to decide how you will send location updates to your tracker resources. The Android
and iOS SDKs offer integrated tracking capabilities for your mobile applications. Alternatively, you can

6
Amazon Location Service Developer Guide
Component definitions

use MQTT by following the step-by-step directions in the tracking using MQTT (p. 86) section of
this guide.
3. You can now use your tracker resource to record location history and visualize it on a map.
4. You can also link your tracker resource to one or more geofence collections so that every position
update sent to your tracker resource is automatically evaluated against all the geofence in all the
linked geofence collections. You can link resource on the tracker resource details page of the Amazon
Location console or by using the Amazon Location Trackers API. For more information about available
options, see the topic about Accessing Amazon Location.
5. You can then integrate monitoring using services such as Amazon CloudWatch and AWS CloudTrail.
For more information see, the section called “Monitoring with CloudWatch” (p. 79) and the section
called “Using CloudTrail with Amazon Location” (p. 83).

Amazon Location core components defined


Amazon Location Service uses GeoJSON geometries to define geographic data, such as location and
boundaries, in its parameters and responses.

This section provides an introduction to the core components, terminology, and basic geometries you'll
need to know when using Amazon Location Service.

Maps
Map resource

Allows you to select a map from a provider. Use the map resource to fetch map tiles that contain
map data and a style descriptor to specify how features render on a map.

Basemap

Provides geographic context to your map, which are stored as vector tile layers. Tile layers include
geographical context such as street names, buildings, and land use for visual reference.

Vector tile

A tile format that stores map data using vector shapes such as points, lines, and polygons. This data
results in a map that can adjust to the display resolution and selectively render features in a number
of ways while maintaining a small file size for optimal performance.

Supported vector file format: Mapbox Vector Tiles (MVT).

Glyph file

A binary file containing encoded Unicode characters. Used by a map renderer display labels.

Sprite file

A Portable Network Graphic (PNG) image file that contains small images, with location descriptions
in a JSON file. Used by a map renderer to render icons or textures on a map.

7
Amazon Location Service Developer Guide
Places

Places
Place resource

Allows you to select a data source to support search queries. Search queries enable you to search for
points of interest, addresses, or coordinates. When a search query is sent to a place index resource,
it's fulfilled using the resource's configured data source.

ISO 3166 country codes

Amazon Location Service Places uses the International Organization for Standardization (ISO) 3166
country codes to refer to countries or regions.

To find the code for a specific country or region, use the ISO Online Browsing Platform.

Geofences
Geofence Collection

Contains zero or more geofences and is capable of geofence monitoring by emitting Entry and Exit
events when requested to evaluate a device position against its geofences.

Geofence

A polygon geometry that defines a virtual boundary on a map.

Polygon geometry

An Amazon Location geofence is a virtual boundary for a geographical area and is represented as a
polygon geometry.

A Polygon is an array composed of 1 or more linear rings. A linear ring is an array of 4 or more
vertices, where the first and last vertex are the same to form a closed boundary. Each vertex is a 2-
dimensional point of the form [longitude, latitude], where the units of longitude and latitude
are degrees.
Note
Limitation — Amazon Location does not currently support polygons with holes,
multipolygons, polygons that are wound clockwise, or that cross the antimeridian.

The first linear ring is an outer ring, describing the polygon's boundary. Subsequent linear rings may
be inner or outer rings to describe holes and islands.
• Outer rings must list their vertices in counter-clockwise order around the ring's center, where the
left side is the polygon's exterior.
• Inner rings must list their vertices in clockwise order, where the left side is the polygon's interior.

The following is an example of a single linear external ring:

[
[
[-5.716667, -15.933333],
[-14.416667, -7.933333],
[-12.316667, -37.066667],
[-5.716667, -15.933333]
]

8
Amazon Location Service Developer Guide
Trackers

Trackers
Tracker resource

An AWS resource that receives location updates from devices. The tracker resource provides support
for location queries, such as current and historic device location. Linking a tracker resource to
a geofence collection evaluates location updates against all geofences in the linked geofence
collection automatically.

When using Mobile Asset Tracking and Mobile Asset Management pricing plans, you use trackers to
calculate the number of assets and monthly API allowance. For more information, see the Amazon
Location Service pricing page.

RFC 3339 timestamp format

Amazon Location Service Trackers uses the RFC 3339 format, which follows the International
Organization for Standardization (ISO) 8601 format for dates and time.

The format is “YYYY-MM-DDThh:mm:ss.sssZ+00:00”:


• YYYY-MM-DD — Represents the date format.
• T — Indicates that the time values will follow.
• hh:mm:ss.sss — Represents the time in 24-hour format.
• Z — Indicates that the time zone used is UTC, which can be followed with deviations from the UTC
time zone.
• +00:00 — Optionally indicate deviations from the UTC time zone. For example, +01:00 indicates
UTC + 1 hour.

Example

For July 2, 2020, at 12:15:20 in the afternoon, with an adjustment of an additional 1 hour to the
UTC timezone.

2020-07-02T12:15:20.000Z+01:00

Amazon Location Regions and endpoints


Amazon Location is available in the following AWS Regions:

Regions
Region name Region code

US East (N. Virginia) us-east-1

US East (Ohio) us-east-2

US West (Oregon) us-west-2

Europe (Ireland) eu-west-1

9
Amazon Location Service Developer Guide
Endpoints

Region name Region code

Asia Pacific (Tokyo) ap-northeast-1

Endpoints
The general syntax for an Amazon Location regional endpoint is as follows:

protocol://service-code.geo.region-code.amazonaws.com

Within this syntax, Amazon Location uses the following service codes:

Service Service code

Amazon Location Maps maps

Amazon Location Places places

Amazon Location Geofences geofencing

Amazon Location Trackers tracking

For example, the regional endpoint for Amazon Location Maps for US East (N. Virginia) would be:
https://maps.geo.us-east-1.amazonaws.com.

10
Amazon Location Service Developer Guide
Data privacy

What is a data provider?


Which Amazon Location services use data providers?

• Maps – Amazon Location Service lets you choose styles from different map providers when creating a
map resource. You can use map resources to build an interactive maps to visualize data.
• Places – Amazon Location Service lets you select a data provider as the source for geocoding, reverse
geocoding and searches. Place index resources enable you to select a data provider to support search
queries for places through your AWS account.

Each provider gathers and curates their data using different means. They may also have varying expertise
in different regions of the world. This section provides details about our data providers. You may select
any data provider based on your preference.

Make sure you read the terms of conditions when using Amazon Location Service data providers. For
more information, see https://aws.amazon.com/service-terms/. Also see the the section called “Data
privacy” (p. 11) section for more information about how Amazon Location protects your privacy.

Data privacy
With Amazon Location Service, you retain control of your organization’s data. Amazon Location Service
anonymizes all queries sent to data providers by removing customer metadata and account information.

Additionally, sensitive tracking and geofencing location information, such as facility, asset, and personnel
locations, never leaves your AWS account at all. This helps you shield sensitive information from third
parties, protect user privacy, and reduce your application’s security risks.

Esri
Maps

Esri uses the most up-to-date reference data from authoritative sources, including community,
commercial, and governmental providers. Esri maps are updated regularly by a dedicated team of expert
in-house cartographers maintaining a global collection of up-to-date authoritative data with strong
lineage, accuracy, and completeness

Places

Esri’s geocoding helps you convert your addresses and place-names into coordinates and display them on
a map. Esri offers a complete geocoding experience:

• Search a single address (geocoding): Search for addresses around the globe and put them on a map
with a high level of accuracy.
• Search for places: Search and display millions of businesses, landmarks, and other points of interest in
any local language.
• Reverse geocoding: Get textual descriptions such as nearest address, intersection, or place name for
coordinates on a map using reverse geocoding.

As with Maps, Esri Places uses the most up-to-date reference data from authoritative sources, including
community, commercial, and governmental providers. This allows Esri to deliver a precise and accurate
service.

11
Amazon Location Service Developer Guide
Terms of use

Global coverage with local language and format support: Esri provides street-level address data for 149
countries that covers more than 90 percent of the world's population.

Terms of use
You must read the service terms and conditions found at https://aws.amazon.com/service-terms/.

Reporting errors and discrepancies to Esri


If you encounter a problem with the data and want to report errors and discrepancies to Esri, follow Esri's
technical support article for How to: Provide feedback on basemaps and geocoding in www.ArcGIS.com
on the Esri webpage.

Esri map styles


Esri maps

Map Description

Esri Light Map

This provides a detailed basemap for the


world symbolized with a classic Esri map style.
This includes highways, major roads, minor
roads, railways, water features, cities, parks,
landmarks, building footprints, and administrative
boundaries.

This basemap is compiled from a variety of


authoritative sources from several data providers,
including the US Geological Survey (USGS),
US Environmental Protection Agency (EPA),
U.S. National Park Service (NPS), Food and
Agriculture Organization of the United Nations
(FAO), Department of Natural Resources Canada
(NRCAN), HERE, and Esri. Data for select areas
is sourced from OpenStreetMap contributors.
Additionally, data is provided by the GIS
community.

Esri Dark Gray Canvas


This map provides a detailed vector basemap for
the world symbolized with a dark gray, neutral
background style with minimal colors, labels, and
features that is designed to draw attention to
your thematic content.

This map includes highways, major roads, minor


roads, railways, water features, cities, parks,
landmarks, building footprints, and administrative
boundaries. The vector tile layers in this map
are built using the same data sources used for
the Dark Gray Canvas raster map and other Esri
basemaps.

For more information, see Esri Dark Gray Canvas


on the Esri website.

12
Amazon Location Service Developer Guide
Esri map styles

Map Description

Esri Light Gray Canvas

This map provides a detailed basemap for the


world symbolized with a light gray, neutral
background style with minimal colors, labels, and
features that is designed to draw attention to
your thematic content.

This vector tile layer is built using the same data


sources used for the Light Gray Canvas and other
Esri basemaps. The map includes highways, major
roads, minor roads, railways, water features,
cities, parks, landmarks, building footprints, and
administrative boundaries.

For more information, see Esri Light Gray Canvas


on the Esri website.

Esri World Navigation

This map provides a detailed basemap for the


world symbolized with a custom navigation map
style that is designed for use during the day in
mobile devices.

This comprehensive street map includes highways,


major roads, minor roads, railways, water features,
cities, parks, landmarks, building footprints, and
administrative boundaries. The vector tile layer
in this map is built using the same data sources
used for the World Street Map and other Esri
basemaps.

For more information, see Esri World Navigation


on the Esri website.

Esri World Streets

This vector tile layer provides a detailed basemap


for the world symbolized with a classic Esri
street map style. The vector tile layer is similar
in content and style to the World Street Map
raster map. This vector tile layer provides unique
capabilities for customization and high-resolution
display.

This comprehensive street map includes highways,


major roads, minor roads, railways, water features,
cities, parks, landmarks, building footprints, and
administrative boundaries. The vector tile layer
is built using the same data sources used for the
raster basemap World Street Map raster map and
other Esri basemaps

For more information, see Esri World Street on the


Esri website.

13
Amazon Location Service Developer Guide
HERE

HERE
Maps

The HERE map receives 5 million updates on average per day across the globe. With one of the highest
accuracy levels in the industry, HERE's validated map data delivers over 900 mapping attributes while
continuously updating its global road network coverage to maintain the most accurate index of reality.

HERE Vector Tiles allows for style customization while providing map functionality for lightweight
applications.

Key features:

• Map Rendering.
• 2D Vector tiles in the size of 512x512 pixel at different zoom levels .
• HERE or 3rd party rendering engine for map creation .
• Client-side rendering for map interactivity and retrieval of Map Objects at an application level.
• HERE map content in industry accepted MVT format.
• Geopolitical views can be built and stored on the client side to retrieve the available political views of
the map.
• Client-side map customization, which includes selection of specific HERE map data sets and visual
appearance of map objects.

Places

HERE provides access to highly accurate geocoding services that deliver on quality, flexibility,
functionality, and experience – whether a location represents a store, a house, a business, or an event.
In addition, HERE offers a true data representation of what is available in the physical world, presenting
Places or point of interests (POIs) that are accurate and deliver meaningful, value-added information.

Geocoding key features:

• Free form, structured and hybrid address input.


• 400 million point addresses in over 102 countries and territories.
• 270 million hyper-precise point addresses in over 70 countries.
• Administrative and postal code boundary shapes.
• High-precision postal codes (US, Great Britain and Republic of Ireland).
• Places geocoding with integrated POI information in queries.

Reverse geocoding key features:

• Address retrieval for the nearest street addresses including long-haul road, such as freeways and
interstates, and entry points.
• Area retrieval for administrative area information for a given position (lat/long).

Search data and point of interest (POIs) key features:

• Rich database of over 400 categories of POIs/ Places.


• Daily data updates with fresh content.
• Display of basic name, address, category and extended attributes information, including operating/
open hours, URLs, contact and more.
• Interact with POI function: navigate, get information, call, visit website, email and more.

14
Amazon Location Service Developer Guide
Terms of use

One box search and discovery key features:

• Support for multiple query types input.


• Querying by: place names, addresses (partial and complete, including postal codes), chains, categories,
postal codes.

Note
Because of licensing limitations, you may not use HERE to store geocoding results for locations
in Japan. For more information, see https://aws.amazon.com/service-terms/ .

Terms of use
You must read the service terms and conditions found at https://aws.amazon.com/service-terms/.

Reporting errors and discrepancies to HERE


If you encounter a problem with the data and want to report errors and discrepancies to HERE:

1. Go to https://mapcreator.here.com/.
2. Choose Join HERE Map Creator and register for a free account.
3. In the HERE Map Creator, Zoom to the area of interest.
4. Open the context (right-click) menu for the area, and choose Customer Ticket to follow the ticket
prompts.

HERE map styles


HERE maps

Map name Description

HERE Berlin maps


HERE Berlin style, inspired by the vibrant city of
Berlin, with colors influenced from the city itself,
blue from the river Spree, green from the many
parks and forests of the city, and yellow for the
color of the taxis and the public transport system.

Data attribution
Ensure that you provide attribution to each data provider you use, either on your application or your
documentation.

• Esri attribution guidelines are found https://www.esri.com/en-us/legal/terms/data-attributions.


• HERE attribution guidelines are found at https://legal.here.com/en-gb/terms/general-content-
supplier-terms-and-notices.

15
Amazon Location Service Developer Guide
User engagement and geomarketing applications

Common use cases for using Amazon


Location Service
Amazon Location Service lets you build a range of applications, from asset tracking to location-based
marketing. The following are common use cases:

User engagement and geomarketing

Use location data to build solutions that improve user engagement with marketing to target
customers. For example, Amazon Location can trigger an event that prompts a notification
when a customer who ordered a coffee on their mobile app is nearby. Additionally, you can build
geomarketing features so that retailers can send discount codes or digital flyers to customers who
are near target stores.

Asset tracking

Build asset tracking features to help businesses understand the current and historical locations of
their products, personnel, and infrastructure. With asset tracking features, you can build a number of
solutions that optimize remote staffing, secure shipment en-route, and maximize dispatch efficacy.

Delivery

Integrate location features into delivery applications to store, track, and coordinate the departure
location, delivery vehicles, and their destination. For example, a food delivery application with
Amazon Location features built-in has location tracking and geofencing capabilities that can
automatically notify a restaurant when a delivery driver is nearby. This reduces the wait times wait
time and helps maintain the quality of the food delivered.

This topic provides you an overview of the architecture and steps for applications you can build with
Amazon Location.

Topics
• User engagement and geomarketing applications (p. 16)
• Asset tracking applications (p. 17)
• Delivery applications (p. 18)

User engagement and geomarketing applications


The following is an illustration of a user engagement and geomarketing application architecture using
Amazon Location:

With this architecture, you can:

• Initiate events based on the proximity of a target so that you can send offers to nearby customers or
engage those who recently left your establishment.
• Visualize customer device locations on a map to monitor trends over time.

16
Amazon Location Service Developer Guide
Asset tracking applications

• Store customer device locations that you can analyze over time.
• Analyze location history to identify trends and opportunities for optimization.

The following is an overview of the steps required to build a user engagement and geomarketing
application:

1. Create your geofences in Geofence Collections and link Trackers to them. For more information, see
the section called “Geofencing an area of interest” (p. 68).
2. Configure Amazon EventBridge to send a notification to customers who enter or exit a geofenced
area of interest. For more information, see the section called “Reacting to geofence events with
EventBridge” (p. 77).
3. Display customer locations and geofences on a map. For more information, see Using maps.
4. Save location data to long-term storage for further analysis.
5. Once you have built your application, you can use Amazon CloudWatch and AWS CloudTrail
to manage your application. For more information, see the section called “Monitoring with
CloudWatch” (p. 79) and the section called “Using CloudTrail with Amazon Location” (p. 83).

Asset tracking applications


The following is an illustration of an asset tracking application architecture using Amazon Location:

With this architecture, you can:

• Display asset locations on a map to illustrate the big picture. For example, showing a heat map using
historical locations or events to help an operations or planning team.
• Initiate events based on asset proximity to provide notice to a receiving department to prepare for a
shipment arrival and reduce processing time.
• Store asset locations to trigger actions in your backend applications or to analyze data over time.
• Analyze location history to identify trends and opportunities for optimization.

17
Amazon Location Service Developer Guide
Delivery applications

The following provides an overview of the steps required to build an asset tracking application:

1. Create your geofences in Geofence Collections and link Trackers to them. For more information, see
the section called “Geofencing an area of interest” (p. 68).
2. Configure Amazon EventBridge to send a notification or initiate a process. For more information, see
the section called “Reacting to geofence events with EventBridge” (p. 77).
3. Display your tracked assets and your active geofences on a map. For more information, see Using
maps.
4. Save location data in long-term storage for further analysis.
5. Once you have built your application, you can use Amazon CloudWatch and AWS CloudTrail
to manage your application. For more information, see the section called “Monitoring with
CloudWatch” (p. 79) and the section called “Using CloudTrail with Amazon Location” (p. 83).

Delivery applications
The following is an illustration of a delivery application architecture using Amazon Location.

With this architecture, you can:

• Initiate events based on proximity of delivery agents so that pickups are ready in time and customers
can be notified when their delivery is arriving.
• Display driver locations, as well as pick-up and drop-off locations in near-real time on a map to show
dispatch teams the big picture.
• Store the locations of delivery agents so that you can act on them in your backend application or
analyze them over time.
• Analyze location history to identify trends and opportunities for optimization.

18
Amazon Location Service Developer Guide
Delivery applications

The following is an overview of the steps required to build a delivery application:

1. Create your geofence collections and link tracked devices to the collection. For more information see,
the section called “Geofencing an area of interest” (p. 68).
2. Create an AWS Lambda function to automatically add and remove geofences as your orders are
booked.
3. Configure Amazon EventBridge to send notifications or initiate a processes. For more information, see
the section called “Reacting to geofence events with EventBridge” (p. 77).
4. Display tracked assets and active geofences on a map. For more information, see Using maps.
5. Save location data to long-term storage for further analysis.
6. Once you have built your application, you can use Amazon CloudWatch and AWS CloudTrail
to manage your application. For more information, see the section called “Monitoring with
CloudWatch” (p. 79) and the section called “Using CloudTrail with Amazon Location” (p. 83).

19
Amazon Location Service Developer Guide
Sign up for AWS

Getting started with Amazon


Location Service
Before you can access Amazon Location, start by making sure that you have the following prerequisite
tasks completed:

Sign up for AWS


If you're new to Amazon Web Services AWS, sign up for an AWS account.

To create an AWS account

1. Open https://portal.aws.amazon.com/billing/signup.
2. Choose Create an AWS Account.
3. Follow the instructions.
Note
You'll need your 12-digit AWS account ID to verify your AWS account through a phone call
and by entering a PIN using your phone keypad. For more information about Finding your
AWS account ID, see The AWS General Reference Guide.

Manage access to your AWS resources using IAM


AWS Identity and Access Management (IAM) is a web service that enables you to manage access to your
AWS resources by controlling who is authenticated and authorized to use resources.

When you sign up for an AWS account, you start with a root account.

There are two different types of users in AWS:

• Root user — The administrative account used by the account owner to allow full access to all resources
in the account.
• IAM user — An account created by the root user, which is granted targeted access to resources using
attached permissions specified by an IAM policy.

Because you cannot use IAM policies to explicitly deny the root user access to resources, it's a best
practice to avoid using your AWS root user account for everyday tasks where it’s not required. Instead,
we recommend that you set up and use an IAM user account with targeted access and permissions to
perform specific tasks and access resources. This enables you to lock away the access keys for the root
user. For more information about tasks that require a root user, see the IAM User Guide.

When you create a new IAM user, you’ll be able to view and download your user credentials, which are
your account ID, account key ID, and secret key. You will need these later to set up authentication to
access AWS resources.
Important
This is the only time that you can view and download your secret access key. You can select the
Download .csv option to keep record of your Access key ID and Secret access key. If you lose
your credentials, you can create new credentials.

20
Amazon Location Service Developer Guide
Grant access to Amazon Location Service

To create an IAM user account

Console

Creating an IAM User and Administrator Group using the IAM Console

You can create an IAM user and group using the AWS Management Console. For information about
Creating an IAM Admin User and Group (Console) , see the IAM User Guide.

If you're new to AWS, see Getting Started with a Service in the AWS Management Console Getting
Started guide.
CLI

Creating an IAM User and Administrator Group using AWS CLI

Alternatively, you can create an IAM user and group using AWS CLI. For information about Creating
an IAM Admin User and Group (AWS CLI), see the IAM User Guide.

If you're new to AWS Command Line Interface (AWS CLI), see Getting Set Up with the AWS
Command Line Interface in the AWS Command Line Interface User Guide.

Grant access to Amazon Location Service


Your new IAM user account has no permissions by default. Before you can access Amazon Location, you
must grant permission by attaching an IAM policy with specific permissions. Make sure to follow the
Principle of least privilege when granting access to resources.

To grant access to Amazon Location, you must create an IAM policy to assign to IAM users.

To create a policy to grant permission to an IAM user

1. Open the IAM console at https://console.aws.amazon.com/iam/.


2. In the navigation pane, choose Policies, then Create policy.
3. Open the JSON tab to enter the following:

In this example policy, the new user is given permission to access Amazon Location operations.

{
"Version": "2012-10-17",
"Statement": [
{
"Action": [
"geo:*"
],
"Resource": "*",
"Effect": "Allow"
}
]
}

For more examples, see the section called “Identity-based policy examples” (p. 114).
4. Choose Review policy.
5. For Name, enter a unique name for this policy. For example, AmazonLocationAccessPolicy .
6. Choose Create policy.

For more information about request property descriptions, see the IAM JSON Policy Elements Reference
in the AWS Identity and Access Management User Guide.

21
Amazon Location Service Developer Guide
Next steps

Next steps
Now that your account is set up:

• Learn more about Accessing Amazon Location Service. (p. 23).

Optionally:

• If you want an alternative to using IAM directly with both frontend SDKs and direct HTTPS requests,
see Enabling unauthenticated access using Amazon Cognito (p. 23).
• To see more examples of IAM policies you can implement for Amazon Location, see the section called
“Identity-based policy examples” (p. 114).

22
Amazon Location Service Developer Guide
Allowing unauthenticated guest
access using Amazon Cognito

Accessing Amazon Location Service


When you're ready to begin building location features into your application, there are many ways to
access Amazon Location Service APIs depending on your goals and inclinations:

• Exploration tools – If you want to experiment with resources, the following tools are the fastest way
to access and try out the APIs:
• The Amazon Location console provides a variety of quick-access tools. You can create and manage
your resources and try the APIs using a visual tool on the Explore page.
• The AWS Command Line Interface (CLI) lets you create resources and access the Amazon Location
APIs using a terminal. Authentication is handled by the AWS CLI when you configure it with your
credentials.
• Platform SDKs – If you don't need to visualize data on a map, you can use any of the AWS standard
tools to build on AWS.
• The following SDKs are available: C++, Go, Java, JavaScript, .NET, Node.js, PHP, Python, and Ruby.
• Frontend SDKs and libraries – If you want to use Amazon Location to build an application on a mobile
platform or visualize data on a map on any platform, you have the following options:
• The AWS Amplify libraries integrates Amazon Location within iOS, Android, and JavaScript web
applications.
• The Mapbox GL libraries lets you render client-side maps into iOS, Android, and JavaScript web
applications using Amazon Location.
• Tangram ES libraries enables you to render 2D and 3D maps from vector data using OpenGL ES
within iOS and Android web applications. There is also Tangram for JavaScript web applications.
• Sending direct HTTPS requests – If you are working with a programming language for which there
is no SDK available, or if you want more control over how a request is sent to AWS, you can access
Amazon Location by sending direct HTTPS requests authenticated by the Signature Version 4 signing
process. For more information on the Signature Version 4 signing process, see the AWS General
Reference.

Allowing unauthenticated guest access to your


application using Amazon Cognito
You can use Amazon Cognito authentication as an alternative to using IAM directly with both frontend
SDKs and direct HTTPS requests.

You may want to authenticate using this method for the following reasons:

• Unauthenticated users – If you have a website with anonymous users, you can use Amazon Cognito
identity pools. For more information, see the section on the section called “Allowing unauthenticated
guest access using Amazon Cognito” (p. 23).
• Your own authentication – If you would like to use your own authentication process, or combine
multiple authentication methods, you can use Amazon Cognito Federated Identities. For more
information, see Getting Started with Federated Identities in the Amazon Cognito Developer guide.

Amazon Cognito provides authentication, authorization, and user management for web and mobile
apps. You can use Amazon Cognito unauthenticated identity pools with Amazon Location as a way for
applications to retrieve temporary, scoped-down AWS credentials.

For more information, see Getting Started with User Pools in the Amazon Cognito Developer Guide.

23
Amazon Location Service Developer Guide
Create an Amazon Cognito identity pool

Create an Amazon Cognito identity pool


You can create Amazon Cognito identity pools to allow unauthenticated guest access to your application
through the Amazon Cognito console, the AWS CLI or the Amazon Cognito APIs.

Note that IAM policies associated with unauthenticated identity roles are limited to the following
actions:

• geo:GetMap*
• geo:SearchPlaceIndex*
• geo:BatchUpdateDevicePosition

Including any other Amazon Location actions will have no effect, and unauthenticated identities will be
unable to call them.

Example

To create an identity pool using the Amazon Cognito console

1. Go to the Amazon Cognito console.


2. Choose Manage Identity Pools.
3. Choose Create new identity pool, then enter a name for your identity pool.
4. To enable unauthenticated identities, select Enable access to unauthenticated identities from the
Unauthenticated identities collapsible section.
5. Choose Create Pool.
6. You will be prompted to specify IAM roles to use with your identity pool.
7. Expand View Details.
8. For this example, we'll focus on an unauthenticated identity role. Under Unauthenticated identities,
enter a role name.
9. Expand the View Policy Document section, then choose Edit to add your policy.
10. Add your policy to grant access to your resources.

The following are policy examples for Maps, Places and Trackers. Note that you will need to replace
region and account ID :

Maps policy example

The following policy grants read only access to a map resource named ExampleMap:

{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "MapsReadOnly",
"Effect": "Allow",
"Action": "geo:GetMap*",
"Resource": "arn:aws:geo:region:account ID:map/ExampleMap"
}
]
}

Places policy example

The following policy allows access to a place index resource named ExamplePlaceIndex to
enable searching for places by text or positions:

24
Amazon Location Service Developer Guide
Using the Identity Pool from JavaScript

{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "PlacesReadOnly",
"Effect": "Allow",
"Action": "geo:SearchPlaceIndex*",
"Resource": "arn:aws:geo:region:accountID:place-index/ExamplePlaceIndex"
}
]
}

Trackers policy example

The following policy allows access to a tracker resouce named ExampleTracker to update
device positions:

{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "UpdateDevicePosition",
"Effect": "Allow",
"Action": [
"geo:BatchUpdateDevicePosition"
],
"Resource": "arn:aws:geo:region:accountID:tracker/ExampleTracker"
}
]
}

Note
While unauthenticated identity pools are intended for exposure on unsecured internet sites,
note that they will be exchanged for standard, time-limited AWS credentials. Therefore, you
must ensure that the associated IAM roles are scoped appropriately.
11. Choose Allow to create your identity pools.

For more policy examples specific to Amazon Location, see the section called “Identity-based policy
examples” (p. 114).

Using the Amazon Cognito identity pools in


JavaScript
The following code snippet will exchange the unauthenticated identity pool that you've recently created
for credentials that are then used to fetch the style descriptor for your map resource "<MapName>".

const AWS = require("aws-sdk");

const credentials = new AWS.CognitoIdentityCredentials({


IdentityPoolId: "<identity pool ID>" // e.g., us-east-1:d40a3a95-a6b5-4816-a15c-
a15ac4f0930d
});

const client = new AWS.Location({


credentials,
region: AWS.config.region || "<region>"

25
Amazon Location Service Developer Guide
Next steps

});

console.log(await client.getMapStyleDescriptor("<MapName>").promise());

Note
Since the identities use credentials outside the normal AWS SDK workflow, retrieved credentials
are valid for one hour.

The following is an example of a function that will automatically renew credentials before they expire:

async function refreshCredentials() {


await credentials.refreshPromise();
// schedule the next credential refresh when they're about to expire
setTimeout(refreshCredentials, credentials.expireTime - new Date());
}

Next steps
• If you need to modify your roles, you'll be able to edit your roles in the IAM console.
• To manage your identity pools, go to the Amazon Cognito console.

26
Amazon Location Service Developer Guide
Using maps

Using Amazon Location Service


You can use Amazon Location Service capabilities to complete a variety of tasks. You can then combine
these tasks to address more complex uses cases such as geomarketing, delivery, and asset tracking.

The section describes many of the tasks that are common to applications using location data. The
common use cases section describes how to combine these with other AWS services to achieve more
complex use cases.

Topics
• Using Amazon Location Maps in your application (p. 27)
• Geocoding, reverse geocoding and searching using Amazon Location (p. 63)
• Geofencing an area of interest using Amazon Location (p. 68)
• Reacting to Amazon Location Service events with Amazon EventBridge (p. 77)
• Monitoring Amazon Location Service with Amazon CloudWatch (p. 79)
• Logging and monitoring with AWS CloudTrail (p. 83)
• Tracking using MQTT with Amazon Location Service (p. 86)
• Managing resources (p. 90)

Using Amazon Location Maps in your application


Amazon Location lets you create map resources, which allow you to select a map style from an available
data provider through your AWS account. You can use map resources to add interactive maps to your
application so you can display data such as points of interest, device location and geofences.

To add a map to your application, you must first create a map resource and select one of available map
providers and styles. You can then use the resource with popular open-source map SDKs, such as Mapbox
GL and Tangram, to display the map in your application.

• AWS SDKs – The AWS mobile SDKs for Android, iOS, and AWS SDK for JavaScript provide an easy-to-
use interface to integrate Amazon Location APIs into your mobile and web applications.
• Mapbox GL JS – An open-source JavaScript library for embedding client-side maps into web
applications. is a library based on Mapbox GL Native, and is compatible with the styles and tiles
provided by the Amazon Location Service Maps API.
• MapLibre Library – A library for Android and iOs based on Mapbox GL Native, and is compatible with
the styles and tiles provided by the Amazon Location Service Maps API.
• Tangram – A flexible mapping engine, designed for real-time rendering of 2D and 3D maps from
vector tiles.
• Tangram ES – Tangram ES is a C++ library for rendering 2D and 3D maps from vector data using
OpenGL ES.

Create a map resource


Before you can display an interactive map, begin by creating a map resource. You can use the Amazon
Location console, the AWS CLI, or the Amazon Location APIs to do this:

27
Amazon Location Service Developer Guide
Step 1: Create a map resource

Important
If you're using Tangram styles in the following tutorial, note that they're only compatible with
Amazon Location map resources configured with the VectorHereBerlin style.

Console

To create a map resource using the Amazon Location console

1. Open the Amazon Location console at https://console.aws.amazon.com/location/.


2. In the left navigation pane, choose Maps.
3. Choose Create map.
4. Fill out the following boxes:
• Name – Enter a unique name. For example, ExampleMap. Maximum 100 characters. Valid
entries include alphanumeric characters, hyphens, periods, and underscores.
• Description – Enter an optional description.
5. In the available list, select a map.
6. Choose Add map.

API

To create a map resource using the Amazon Location APIs

Use the CreateMap action from the Amazon Location Maps APIs.

The following example is an API request to create a map resource called ExampleMap using the
VectorEsriNavigation map style, and a request-based usage pricing plan.
Note
During the preview period, you will not incur Amazon Location Service charges for the
use of the service. You may incur fees for the use of other AWS services. For additional
information on pricing, see the Amazon Location service page.

POST /maps/v0/maps
Content-type: application/json

{
"Configuration": {
"Style": "VectorEsriNavigation"
},
"Description": "Esri Dark Gray Canvas",
"MapName": "ExampleMap",
"PricingPlan": "RequestBasedUsage"
}

AWS CLI

To create a map resource using AWS CLI commands

Use the create-map command.

The following example is an AWS CLI to create a map resource called ExampleMap using the
VectorEsriNavigation map style, and a request-based usage pricing plan.
Note
During the preview period, you will not incur Amazon Location Service charges for the
use of the service. You may incur fees for the use of other AWS services. For additional
information on pricing, see the Amazon Location service page.

28
Amazon Location Service Developer Guide
Step 2: Creating an unauthenticated identity pool

aws location \
create-map \
--map-name "ExampleMap" \
--configuration "Style=VectorEsriNavigation" \
--pricing-plan "RequestBasedUsage"

Create an identity pool to enable unauthenticated


access to your application
Before you can display a map in your application, use Amazon Cognito to create an unauthenticated
identity pool with a scoped-down AWS Identity and Access Management (IAM) role that allows read-only
access to the Amazon Location Maps APIs.
Important
Ensure that the pool you create is in the same AWS Region as the place index resources that
you're using.

The pool's ID will take the form <region>:<GUID>. For example:

us-east-1:54f2ba88-9390-498d-aaa5-0d97fb7ca3bd

The following is an example of a scoped-down IAM policy allowing access to a map resource named
ExampleMap:

{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "MapsReadOnly",
"Effect": "Allow",
"Action": [
"geo:GetMapStyleDescriptor",
"geo:GetMapGlyphs",
"geo:GetMapSprites",
"geo:GetMapTile"
],
"Resource": "arn:aws:geo:<region>:<account ID>:map/ExampleMap"
}
]
}

The following is another example of a scoped-down IAM policy allowing access to a map resource named
TangramExampleMap:
Note
If you're using Tangram, note that Tangram does not use the style descriptors, glyphs, or sprites
returned by the Maps API. Instead, it is configured by pointing to a ZIP file that contains style
rules and necessary assets.

{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "MapsReadOnly",
"Effect": "Allow",
"Action": [

29
Amazon Location Service Developer Guide
Step 3: Display a map in your application

"geo:GetMapTile"
],
"Resource": "arn:aws:geo:region:accountID:map/TangramExampleMap"
}
]
}

Display a map in your application


This section provides tutorials on how to use map rendering tools to display a map in your mobile or web
application when using Amazon Location APIs.

Topics
• Using the MapLibre library with Amazon Location Service (p. 30)
• Using Tangram with Amazon Location Service (p. 44)

Using the MapLibre library with Amazon Location Service


The following tutorials walk you through using the MapLibre Library with Amazon Location.

Topics
• Using Mapbox GL JS with Amazon Location Service (p. 30)
• Using the MapLibre GL Native SDK for Android with Amazon Location Service (p. 34)
• Using the MapLibre GL Native SDK for iOS with Amazon Location Service (p. 40)

Using Mapbox GL JS with Amazon Location Service


Use Mapbox GL JS to embed client-side maps into web applications.

Mapbox GL JS is an open-source JavaScript library that is compatible with the styles and tiles provided
by the Amazon Location Service Maps API. You can integrate Mapbox GL JS within a basic HTML or
JavaScript application to embed customizable and responsive client-side maps.

This tutorial describes how to integrate Mapbox GL JS with Amazon Location within a basic HTML and
JavaScript application. Note that the same libraries and techniques presented in this tutorial also apply
to frameworks, such as React and Angular.

The sample application for this tutorial is available as part of the Amazon Location Service samples
repository on GitHub.

Building the application: Scaffolding

This tutorial creates a web application that uses JavaScript to build a map on an HTML page.

Begin by creating an HTML page (index.html) that includes the map's container:

• Enter a div element with an id of map to apply the map's dimensions to the map view. The
dimensions are inherited from the viewport.

<html>
<head>
<style>

30
Amazon Location Service Developer Guide
Step 3: Display a map in your application

body {
margin: 0;
}

#map {
height: 100vh; /* 100% of viewport height */
}
</style>
</head>
<body>
<!-- map container -->
<div id="map" />
</body>
</html>

Building the application: Adding dependencies

Add the following dependencies to your application:

• Mapbox GL JS (v1.13.0 or earlier), and its associated CSS.


• AWS SDK for JavaScript.
• AWS Amplify core library.

<!-- CSS dependencies -->


<link
href="https://api.mapbox.com/mapbox-gl-js/v1.12.0/mapbox-gl.css"
rel="stylesheet"
/>
<!-- JavaScript dependencies -->
<script src="https://api.mapbox.com/mapbox-gl-js/v1.12.0/mapbox-gl.js"></script>
<script src="https://sdk.amazonaws.com/js/aws-sdk-2.775.0.min.js"></script>
<script src="https://unpkg.com/@aws-amplify/core@3.7.0/dist/aws-amplify-core.min.js"></
script>
<script>
// application-specific code
</script>

This creates an empty page with the map's container.

Building the application: Configuration

To configure your application using JavaScript:

1. Enter the names and identifiers of your resources.

// Cognito Identity Pool ID


const identityPoolId = "us-east-1:54f2ba88-9390-498d-aaa5-0d97fb7ca3bd";
// Amazon Location Service Map name
const mapName = "ExampleMap";

2. Instantiate a credential provider using the unauthenticated identity pool you created (p. 29).

// extract the Region from the Identity Pool ID; this will be used for both Amazon
Cognito and Amazon Location
AWS.config.region = identityPoolId.split(":")[0];

// instantiate an Amazon Cognito-backed credential provider


const credentials = new AWS.CognitoIdentityCredentials({
IdentityPoolId: identityPoolId,

31
Amazon Location Service Developer Guide
Step 3: Display a map in your application

});

3. Because this uses credentials outside the normal AWS SDK workflow sessions expire after one hour.

The following is an example of a function that will automatically renew credentials before they
expire:

async function refreshCredentials() {


await credentials.refreshPromise();
// schedule the next credential refresh when they're about to expire
setTimeout(refreshCredentials, credentials.expireTime - new Date());
}

Building the application: Request transformation

Mapbox GL JS map instances include a transformRequest option, which you use to intercept and
modify requests before they're made.

To sign AWS requests using Signature Version 4 with credentials obtained from Amazon Cognito, enter
the following function.

// use Signer from @aws-amplify/core


const { Signer } = window.aws_amplify_core;

/**
* Sign requests made by Mapbox GL JS using AWS SigV4.
*/
function transformRequest(url, resourceType) {
if (resourceType === "Style" && !url.includes("://")) {
// resolve to an AWS URL
url = `https://maps.geo.${AWS.config.region}.amazonaws.com/maps/v0/maps/${url}/style-
descriptor`;
}

if (url.includes("amazonaws.com")) {
// only sign AWS requests (with the signature as part of the query string)
return {
url: Signer.signUrl(url, {
access_key: credentials.accessKeyId,
secret_key: credentials.secretAccessKey,
session_token: credentials.sessionToken,
}),
};
}

// don't sign
return { url };
}

Building the application: Map initialization

For the map to display after the page is loaded, you must initialize the map. You can adjust the initial
map location, add additional controls, and overlay data.

async function initializeMap() {


// load credentials and set them up to refresh
await credentials.getPromise();

// actually initialize the map


const map = new mapboxgl.Map({

32
Amazon Location Service Developer Guide
Step 3: Display a map in your application

container: "map",
center: [-123.1187, 49.2819], // initial map centerpoint
zoom: 10, // initial map zoom
style: mapName,
transformRequest,
});

map.addControl(new mapboxgl.NavigationControl(), "top-left");


}

initializeMap();

Note
You must provide wordmark or text attribution for each data provider that you use, either on
your application or your documentation. Attribution strings are included in the style descriptor
response under the sources.esri.attribution and sources.here.attribution keys.
Mapbox GL will automatically provide attribution. When using Amazon Location resources with
data providers, make sure to read the service terms and conditions.

Running the application

You can run this sample application by using it in a local web server, or opening it in a browser.

To use a local web server, you can use npx, because it's installed as part of Node.js. You can use
npx serve from within the same directory as index.html. This serves the application on
localhost:5000.

After completing the tutorial, the final application looks like the following example.

<!-- index.html -->


<html>
<head>
<link
href="https://api.mapbox.com/mapbox-gl-js/v1.12.0/mapbox-gl.css"
rel="stylesheet"
/>
<style>
body {
margin: 0;
}

#map {
height: 100vh;
}
</style>
</head>

<body>
<!-- map container -->
<div id="map" />
<!-- JavaScript dependencies -->
<script src="https://api.mapbox.com/mapbox-gl-js/v1.12.0/mapbox-gl.js"></script>
<script src="https://sdk.amazonaws.com/js/aws-sdk-2.775.0.min.js"></script>
<script src="https://unpkg.com/@aws-amplify/core@3.7.0/dist/aws-amplify-core.min.js"></
script>
<script>
// use Signer from @aws-amplify/core
const { Signer } = window.aws_amplify_core;

// configuration
const identityPoolId = "us-east-1:54f2ba88-9390-498d-aaa5-0d97fb7ca3bd"; // Cognito
Identity Pool ID
const mapName = "ExampleMap"; // Amazon Location Service Map Name

33
Amazon Location Service Developer Guide
Step 3: Display a map in your application

// extract the region from the Identity Pool ID


AWS.config.region = identityPoolId.split(":")[0];

// instantiate a Cognito-backed credential provider


const credentials = new AWS.CognitoIdentityCredentials({
IdentityPoolId: identityPoolId,
});

/**
* Sign requests made by Mapbox GL using AWS SigV4.
*/
function transformRequest(url, resourceType) {
if (resourceType === "Style" && !url.includes("://")) {
// resolve to an AWS URL
url = `https://maps.geo.${AWS.config.region}.amazonaws.com/maps/v0/maps/${url}/
style-descriptor`;
}

if (url.includes("amazonaws.com")) {
// only sign AWS requests (with the signature as part of the query string)
return {
url: Signer.signUrl(url, {
access_key: credentials.accessKeyId,
secret_key: credentials.secretAccessKey,
session_token: credentials.sessionToken,
}),
};
}

// don't sign
return { url };
}

/**
* Initialize a map.
*/
async function initializeMap() {
// load credentials and set them up to refresh
await credentials.getPromise();

// actually initialize the map


const map = new mapboxgl.Map({
container: "map",
center: [-123.1187, 49.2819], // initial map centerpoint
zoom: 10, // initial map zoom
style: mapName,
transformRequest,
});

map.addControl(new mapboxgl.NavigationControl(), "top-left");


}

initializeMap();
</script>
</body>
</html>

Running this application displays a full-screen map using your chosen map style. This sample is available
in the Amazon Location Service samples repository on GitHub.

Using the MapLibre GL Native SDK for Android with Amazon Location Service
Use MapLibre GL Native SDK to embed interactive maps into your Android applications.

34
Amazon Location Service Developer Guide
Step 3: Display a map in your application

The MapLibre GL Native SDK for Android is a library based on Mapbox GL Native, and is compatible with
the styles and tiles provided by the Amazon Location Service Maps API. You can integrate MapLibre GL
Native SDK for Android to embed interactive map views with scalable, customizable vector maps into
your Android applications.

This tutorial describes how to integrate the MapLibre GL Native SDK for Android with Amazon Location.
The sample application for this tutorial is available as part of the Amazon Location Service samples
repository on GitHub.

Building the application: Initialization

To initialize your application:

1. Create a new Android Studio project from the Empty Activity template.
2. Ensure that Kotlin is selected for the project language.
3. Select a Minimum SDK of API 14: Android 4.0 (Ice Cream Sandwich) or newer.
4. Open Project Structure, then go to File > Project Structure... to choose the Dependencies section.
5. With <All Modules> selected,then choose the + button to add a new Library Dependency.
6. Add AWS Android SDK version 2.20.0 or later. For example: com.amazonaws:aws-android-sdk-
core:2.20.0
7. Add the MapLibre GL Native SDK for Android version 9.4.0 or later. For example:
org.maplibre.gl:android-sdk:9.4.0
8. At the project level of your build.gradle file, add the following bintray maven repository to enable
access to the MapLibre packages for Android:

allprojects {
repositories {
// Retain your existing repositories
google()
jcenter()

// declare the custom URL repositories for MapLibre


maven {
url = "https://dl.bintray.com/maplibre/maplibre-gl-native"
}
}
}

Building the application: Configuration

To configure your application with your resources and AWS Region:

<?xml version="1.0" encoding="utf-8"?>


<resources>
<string name="identityPoolId">us-east-1:54f2ba88-9390-498d-aaa5-0d97fb7ca3bd</string>
<string name="mapName">ExampleMap</string>
<string name="awsRegion">us-east-1</string>
</resources>

Building the application: Activity layout

Edit app/src/main/res/layout/activity_main.xml:

• Add a MapView, which renders the map. This will also set the map's initial center point.
• Add a TextView, which displays attribution.

35
Amazon Location Service Developer Guide
Step 3: Display a map in your application

<?xml version="1.0" encoding="utf-8"?>


<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<com.mapbox.mapboxsdk.maps.MapView
android:id="@+id/mapView"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:mapbox_cameraTargetLat="49.2819"
app:mapbox_cameraTargetLng="-123.1187"
app:mapbox_cameraZoom="12"
app:mapbox_uiAttribution="false"
app:mapbox_uiLogo="false" />

<TextView
android:id="@+id/attributionView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#80808080"
android:padding="5sp"
android:textColor="@android:color/black"
android:textSize="10sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
tools:ignore="SmallSp" />
</androidx.constraintlayout.widget.ConstraintLayout>

Note
You must provide wordmark or text attribution for each data provider that you use, either on
your application or your documentation. Attribution strings are included in the style descriptor
response under the sources.esri.attribution and sources.here.attribution keys.
When using Amazon Location resources with data providers, make sure to read the service terms
and conditions.

Building the application: Request transformation


Create a class named SigV4Interceptor to intercept AWS requests and sign them using Signature
Version 4. This will be registered with the HTTP client used to fetch map resources when the Main
Activity is created.

package aws.location.demo.okhttp

import com.amazonaws.DefaultRequest
import com.amazonaws.auth.AWS4Signer
import com.amazonaws.auth.AWSCredentialsProvider
import com.amazonaws.http.HttpMethodName
import com.amazonaws.util.IOUtils
import okhttp3.HttpUrl
import okhttp3.Interceptor
import okhttp3.Request
import okhttp3.Response
import okio.Buffer
import java.io.ByteArrayInputStream
import java.net.URI

class SigV4Interceptor(
private val credentialsProvider: AWSCredentialsProvider,
private val serviceName: String

36
Amazon Location Service Developer Guide
Step 3: Display a map in your application

) : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response {
val originalRequest = chain.request()

if (originalRequest.url().host().contains("amazonaws.com")) {
val signer = if (originalRequest.url().encodedPath().contains("@")) {
// the presence of "@" indicates that it doesn't need to be double URL-
encoded
AWS4Signer(false)
} else {
AWS4Signer()
}

val awsRequest = toAWSRequest(originalRequest, serviceName)


signer.setServiceName(serviceName)
signer.sign(awsRequest, credentialsProvider.credentials)

return chain.proceed(toSignedOkHttpRequest(awsRequest, originalRequest))


}

return chain.proceed(originalRequest)
}

companion object {
fun toAWSRequest(request: Request, serviceName: String): DefaultRequest<Any> {
// clone the request (AWS-style) so that it can be populated with credentials
val dr = DefaultRequest<Any>(serviceName)

// copy request info


dr.httpMethod = HttpMethodName.valueOf(request.method())
with(request.url()) {
dr.resourcePath = uri().path
dr.endpoint = URI.create("${scheme()}://${host()}")

// copy parameters
for (p in queryParameterNames()) {
if (p != "") {
dr.addParameter(p, queryParameter(p))
}
}
}

// copy headers
for (h in request.headers().names()) {
dr.addHeader(h, request.header(h))
}

// copy the request body


val bodyBytes = request.body()?.let { body ->
val buffer = Buffer()
body.writeTo(buffer)
IOUtils.toByteArray(buffer.inputStream())
}

dr.content = ByteArrayInputStream(bodyBytes ?: ByteArray(0))

return dr
}

fun toSignedOkHttpRequest(
awsRequest: DefaultRequest<Any>,
originalRequest: Request
): Request {
// copy signed request back into an OkHttp Request
val builder = Request.Builder()

37
Amazon Location Service Developer Guide
Step 3: Display a map in your application

// copy headers from the signed request


for ((k, v) in awsRequest.headers) {
builder.addHeader(k, v)
}

// start building an HttpUrl


val urlBuilder = HttpUrl.Builder()
.host(awsRequest.endpoint.host)
.scheme(awsRequest.endpoint.scheme)
.encodedPath(awsRequest.resourcePath)

// copy parameters from the signed request


for ((k, v) in awsRequest.parameters) {
urlBuilder.addQueryParameter(k, v)
}

return builder.url(urlBuilder.build())
.method(originalRequest.method(), originalRequest.body())
.build()
}
}
}

Building the application: Main activity

The Main Activity is responsible for initializing the views that will be displayed to users. This involves:

• Instantiating an Amazon Cognito CredentialsProvider.


• Registering the Signature Version 4 interceptor.
• Configuring the map by pointing it at a map style descriptor, and displaying appropriate attribution.

MainActivity is also responsible for forwarding life cycle events to the map view, allowing it to
preserve the active viewport between invocations.

package aws.location.demo.mapboxgl

import android.os.Bundle
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import aws.location.demo.okhttp.SigV4Interceptor
import com.amazonaws.auth.CognitoCachingCredentialsProvider
import com.amazonaws.regions.Regions
import com.mapbox.mapboxsdk.Mapbox
import com.mapbox.mapboxsdk.maps.MapView
import com.mapbox.mapboxsdk.maps.Style
import com.mapbox.mapboxsdk.module.http.HttpRequestUtil
import okhttp3.OkHttpClient

private const val SERVICE_NAME = "geo"

class MainActivity : AppCompatActivity() {


private var mapView: MapView? = null

override fun onCreate(savedInstanceState: Bundle?) {


super.onCreate(savedInstanceState)

// configuration
val identityPoolId = getString(R.string.identityPoolId)
val region = getString(R.string.awsRegion)
val mapName = getString(R.string.mapName)

// Credential initialization

38
Amazon Location Service Developer Guide
Step 3: Display a map in your application

val credentialProvider = CognitoCachingCredentialsProvider(


applicationContext,
identityPoolId,
Regions.fromName(identityPoolId.split(":").first())
)

// initialize Mapbox GL
Mapbox.getInstance(this, null)
HttpRequestUtil.setOkHttpClient(
OkHttpClient.Builder()
.addInterceptor(SigV4Interceptor(credentialProvider, SERVICE_NAME))
.build()
)

// initialize the view


setContentView(R.layout.activity_main)

// initialize the map view


mapView = findViewById(R.id.mapView)
mapView?.onCreate(savedInstanceState)
mapView?.getMapAsync { map ->
map.setStyle(
Style.Builder()
.fromUri("https://maps.geo.${region}.amazonaws.com/maps/v0/maps/
${mapName}/style-descriptor")
) { style ->
findViewById<TextView>(R.id.attributionView).text =
style.sources.first()?.attribution
}
}
}

override fun onStart() {


super.onStart()
mapView?.onStart()
}

override fun onResume() {


super.onResume()
mapView?.onResume()
}

override fun onPause() {


super.onPause()
mapView?.onPause()
}

override fun onStop() {


super.onStop()
mapView?.onStop()
}

override fun onSaveInstanceState(outState: Bundle) {


super.onSaveInstanceState(outState)
mapView?.onSaveInstanceState(outState)
}

override fun onLowMemory() {


super.onLowMemory()
mapView?.onLowMemory()
}

override fun onDestroy() {


super.onDestroy()
mapView?.onDestroy()
}

39
Amazon Location Service Developer Guide
Step 3: Display a map in your application

Running this application displays a full-screen map in the style of your choosing. This sample is available
as part of the Amazon Location Service samples repository on GitHub.

Using the MapLibre GL Native SDK for iOS with Amazon Location Service
Use MapLibre GL Native SDK for iOS to embed client-side maps into iOS applications.

The MapLibre GL Native SDK for iOS is a library based on Mapbox GL Native, and is compatible with
the styles and tiles provided by the Amazon Location Service Maps API. You can integrate MapLibre GL
Native SDK for iOS to embed interactive map views with scalable, customizable vector maps into your
iOS applications.

This tutorial describes how to integrate the MapLibre GL Native SDK for iOS with Amazon Location.
The sample application for this tutorial is available as part of the Amazon Location Service samples
repository on GitHub.

Building the application: Initialization

To initialize your application:

1. Create a new Xcode project from the App template.


2. Select SwiftUI for its interface.
3. Select SwiftUI application for its Life Cycle.
4. Select Swift for its language.

Adding MapLibre dependencies using Swift Packages

To add a package dependency to your Xcode project:

1. Navigate to File > Swift Packages > Add Package Dependency.


2. Enter the repository URL: https://github.com/maplibre/maplibre-gl-native-
distribution
Note
For more information about Swift Packages see Adding Package Dependencies to Your App
at Apple.com
3. In your terminal, install CocoaPods:

sudo gem install cocoapods

4. Navigate to your application's project directory and initialize the Podfile with the CocoaPods
package manager:

pod init

5. Open the Podfile to add AWSCore as a dependency:

platform :ios, '12.0'

target 'Amazon Location Service Demo' do


use_frameworks!

pod 'AWSCore'

40
Amazon Location Service Developer Guide
Step 3: Display a map in your application

end

6. Download and install dependencies:

pod install --repo-update

7. Open the Xcode workspace that CocoaPods created:

xed .

Building the application: Configuration

Add the following keys and values to Info.plist to configure the application:

Key Value

AWSRegion us-east-1

IdentityPoolId us-east-1:54f2ba88-9390-498d-
aaa5-0d97fb7ca3bd

MapName ExampleMap

Building the application: ContentView layout

To render the map, edit ContentView.swift:

• Add a MapView which renders the map.


• Add a TextField which displays attribution.

This also sets the map's initial center point.

import SwiftUI

struct ContentView: View {


@State private var attribution = ""

var body: some View {


MapView(attribution: $attribution)
.centerCoordinate(.init(latitude: 49.2819, longitude: -123.1187))
.zoomLevel(12)
.edgesIgnoringSafeArea(.all)
.overlay(
TextField("", text: $attribution)
.disabled(true)
.font(.system(size: 12, weight: .light, design: .default))
.foregroundColor(.black)
.background(Color.init(Color.RGBColorSpace.sRGB, white: 0.5, opacity:
0.5))
.cornerRadius(1),
alignment: .bottomTrailing)
}
}

struct ContentView_Previews: PreviewProvider {


static var previews: some View {
ContentView()

41
Amazon Location Service Developer Guide
Step 3: Display a map in your application

}
}

Note
You must provide wordmark or text attribution for each data provider that you use, either on
your application or your documentation. Attribution strings are included in the style descriptor
response under the sources.esri.attribution and sources.here.attribution keys.
When using Amazon Location resources with data providers, make sure to read the service terms
and conditions.

Building the application: Request transformation

Create a new Swift file named AWSSignatureV4Delegate.swift containing the following class
definition to intercept AWS requests and sign them using Signature Version 4. An instance of this class
will be assigned as the offline storage delegate, which is also responsible for rewriting URLs, in the map
view.

import AWSCore
import Mapbox

class AWSSignatureV4Delegate : NSObject, MGLOfflineStorageDelegate {


private let region: AWSRegionType
private let identityPoolId: String
private let credentialsProvider: AWSCredentialsProvider

init(region: AWSRegionType, identityPoolId: String) {


self.region = region
self.identityPoolId = identityPoolId
self.credentialsProvider = AWSCognitoCredentialsProvider(regionType: region,
identityPoolId: identityPoolId)
super.init()
}

class func doubleEncode(path: String) -> String? {


return path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed)?
.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed)
}

func offlineStorage(_ storage: MGLOfflineStorage, urlForResourceOf kind:


MGLResourceKind, with url: URL) -> URL {
if url.host?.contains("amazonaws.com") != true {
// not an AWS URL
return url
}

// URL-encode spaces, etc.


let keyPath = String(url.path.dropFirst())
guard let percentEncodedKeyPath =
keyPath.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else {
print("Invalid characters in path '\(keyPath)'; unsafe to sign")
return url
}

let endpoint = AWSEndpoint(region: region, serviceName: "geo", url: url)


let requestHeaders: [String: String] = ["host": endpoint!.hostName]

// sign the URL


let task = AWSSignatureV4Signer
.generateQueryStringForSignatureV4(
withCredentialProvider: credentialsProvider,
httpMethod: .GET,
expireDuration: 60,
endpoint: endpoint!,

42
Amazon Location Service Developer Guide
Step 3: Display a map in your application

// workaround for https://github.com/aws-amplify/aws-sdk-ios/issues/3215


keyPath: AWSSignatureV4Delegate.doubleEncode(path: percentEncodedKeyPath),
requestHeaders: requestHeaders,
requestParameters: .none,
signBody: true)
task.waitUntilFinished()

if let error = task.error as NSError? {


print("Error occurred: \(error)")
}

if let result = task.result {


var urlComponents = URLComponents(url: (result as URL),
resolvingAgainstBaseURL: false)!
// re-use the original path; workaround for https://github.com/aws-amplify/aws-
sdk-ios/issues/3215
urlComponents.path = url.path

// have Mapbox GL fetch the signed URL


return (urlComponents.url)!
}

// fall back to an unsigned URL


return url
}
}

Building the application: Map view

The Map View is responsible for initializing an instance of AWSSignatureV4Delegate and configuring
the underlying MGLMapView, which fetches resources and renders the map. It also handles propagating
attribution strings from the style descriptor's source back to the ContentView.

Create a new Swift file named MapView.swift containing the following struct definition:

import SwiftUI
import AWSCore
import Mapbox

struct MapView: UIViewRepresentable {


@Binding var attribution: String

private var mapView: MGLMapView


private var signingDelegate: MGLOfflineStorageDelegate

init(attribution: Binding<String>) {
let regionName = Bundle.main.object(forInfoDictionaryKey: "AWSRegion") as! String
let identityPoolId = Bundle.main.object(forInfoDictionaryKey: "IdentityPoolId") as!
String
let mapName = Bundle.main.object(forInfoDictionaryKey: "MapName") as! String

let region = (regionName as NSString).aws_regionTypeValue()

// MGLOfflineStorage doesn't take ownership, so this needs to be a member here


signingDelegate = AWSSignatureV4Delegate(region: region, identityPoolId:
identityPoolId)

// register a delegate that will handle SigV4 signing


MGLOfflineStorage.shared.delegate = signingDelegate

mapView = MGLMapView(
frame: .zero,
styleURL: URL(string: "https://maps.geo.\(regionName).amazonaws.com/maps/v0/
maps/\(mapName)/style-descriptor"))

43
Amazon Location Service Developer Guide
Step 3: Display a map in your application

_attribution = attribution
}

func makeCoordinator() -> Coordinator {


Coordinator($attribution)
}

class Coordinator: NSObject, MGLMapViewDelegate {


var attribution: Binding<String>

init(_ attribution: Binding<String>) {


self.attribution = attribution
}

func mapView(_ mapView: MGLMapView, didFinishLoading style: MGLStyle) {


let source = style.sources.first as? MGLVectorTileSource
let attribution = source?.attributionInfos.first
self.attribution.wrappedValue = attribution?.title.string ?? ""
}
}

// MARK: - UIViewRepresentable protocol

func makeUIView(context: UIViewRepresentableContext<MapView>) -> MGLMapView {


mapView.delegate = context.coordinator

mapView.logoView.isHidden = true
mapView.attributionButton.isHidden = true
return mapView
}

func updateUIView(_ uiView: MGLMapView, context: UIViewRepresentableContext<MapView>) {


}

// MARK: - MGLMapView proxy

func centerCoordinate(_ centerCoordinate: CLLocationCoordinate2D) -> MapView {


mapView.centerCoordinate = centerCoordinate
return self
}

func zoomLevel(_ zoomLevel: Double) -> MapView {


mapView.zoomLevel = zoomLevel
return self
}
}

Running this application displays a full-screen map in the style of your choosing. This sample is available
as part of the Amazon Location Service samples repository on GitHub.

Using Tangram with Amazon Location Service


This section provides the following tutorials on how to integrate Tangram with Amazon Location.
Important
The Tangram styles in the following tutorials are only compatible with Amazon Location map
resources configured with the VectorHereBerlin style.

The following is an example of an AWS CLI command to create a new map resource called
TangramExampleMap using the VectorHEREBerlin style:

aws --region us-east-1 \

44
Amazon Location Service Developer Guide
Step 3: Display a map in your application

location \
create-map \
--map-name "TangramExampleMap" \
--configuration "Style=VectorHereBerlin" \
--pricing-plan "RequestBasedUsage"

Topics
• Using Tangram with Amazon Location Service (p. 45)
• Using Tangram ES for Android with Amazon Location Service (p. 53)
• Using Tangram ES for iOS with Amazon Location Service (p. 58)

Using Tangram with Amazon Location Service


Tangram is a flexible mapping engine, designed for real-time rendering of 2D and 3D maps from vector
tiles. It can be used with Mapzen-designed styles and the HERE tiles provided by the Amazon Location
Service Maps API. This guide describes how to integrate Tangram with Amazon Location within a
basic HTML/JavaScript application, although the same libraries and techniques also apply when using
frameworks like React and Angular.

Tangram is built atop Leaflet, an open-source JavaScript library for mobile-friendly interactive maps.
This means that many Leaflet-compatible plugins and controls also work with Tangram.

Tangram styles built to work with the Tilezen schema are largely compatible with Amazon Location when
using maps from HERE. These include:

• Bubble Wrap – A full-featured wayfinding style with helpful icons for points of interest
• Cinnabar – A classic look and go-to for general mapping applications
• Refill – A minimalist map style designed for data visualization overlays, inspired by the seminal Toner
style by Stamen Design
• Tron – An exploration of scale transformations in the visual language of TRON
• Walkabout – An outdoor-focused style that's perfect for hiking or getting out and about

This guide describes how to integrate Tangram with Amazon Location within a basic HTML/JavaScript
application using the Tangram Style called Bubble Wrap. This sample is available as part of the Amazon
Location Service samples repository on GitHub.

While other Tangram styles are best accompanied by raster tiles, which encode terrain information, this
feature is not yet supported by Amazon Location.
Important
The Tangram styles in the following tutorial are only compatible with Amazon Location map
resources configured with the VectorHereBerlin style.

Building the application: Scaffolding

The application is an HTML page with JavaScript to build the map on your web application. Create an
HTML page (index.html) and create the map's container:

• Enter a div element with an id of map to apply the map's dimensions to the map view.
• The dimensions are inherited from the viewport.

<html>
<head>

45
Amazon Location Service Developer Guide
Step 3: Display a map in your application

<style>
body {
margin: 0;
}

#map {
height: 100vh; /* 100% of viewport height */
}
</style>
</head>
<body>
<!-- map container -->
<div id="map" />
</body>
</html>

Building the application: Adding dependencies

Add the following dependencies:

• Leaflet and its associated CSS.


• Tangram.
• AWS SDK for JavaScript.

<!-- CSS dependencies -->


<link
rel="stylesheet"
href="https://unpkg.com/leaflet@1.7.1/dist/leaflet.css"
integrity="sha512-xodZBNTC5n17Xt2atTPuE1HxjVMSvLVW9ocqUKLsCC5CXdbqCmblAshOMAS6/keqq/
sMZMZ19scR4PsZChSR7A=="
crossorigin=""
/>
<!-- JavaScript dependencies -->
<script src="https://unpkg.com/leaflet@1.7.1/dist/leaflet.js"></script>
<script src="https://unpkg.com/tangram"></script>
<script src="https://sdk.amazonaws.com/js/aws-sdk-2.784.0.min.js"></script>
<script>
// application-specific code
</script>

This creates an empty page with the necessary prerequisites. The next step guides you through writing
the JavaScript code for your application.

Building the application: Configuration

To configure your application with your resources and credentials:

1. Enter the names and identifiers of your resources.

// Cognito Identity Pool ID


const identityPoolId = "us-east-1:54f2ba88-9390-498d-aaa5-0d97fb7ca3bd";
// Amazon Location Service map name; must be HERE-backed
const mapName = "TangramExampleMap";

2. Instantiate a credential provider using the unauthenticated identity pool you created (p. 29).
Since this uses credentials outside the normal AWS SDK work flow, sessions expire after one hour.

// extract the region from the Identity Pool ID; this will be used for both Amazon
Cognito and Amazon Location

46
Amazon Location Service Developer Guide
Step 3: Display a map in your application

AWS.config.region = identityPoolId.split(":", 1)[0];

// instantiate a Cognito-backed credential provider


const credentials = new AWS.CognitoIdentityCredentials({
IdentityPoolId: identityPoolId,
});

3. While Tangram allows you to override the URL(s) used to fetch tiles, it doesn't include the ability to
intercept requests so that they can be signed.

To work around this, override sources.mapzen.url to point to Amazon Location using a synthetic
host name amazon.location, which will be handled by a service worker. The following is an
example of scene configuration using Bubble Wrap:

const scene = {
import: [
// Bubble Wrap style
"https://www.nextzen.org/carto/bubble-wrap-style/10/bubble-wrap-style.zip",
"https://www.nextzen.org/carto/bubble-wrap-style/10/themes/label-7.zip",
"https://www.nextzen.org/carto/bubble-wrap-style/10/themes/bubble-wrap-road-
shields-usa.zip",
"https://www.nextzen.org/carto/bubble-wrap-style/10/themes/bubble-wrap-road-
shields-international.zip",
],
// override values beneath the `sources` key in the style above
sources: {
mapzen: {
// point at Amazon Location using a synthetic URL, which will be handled by the
service
// worker
url: `https://amazon.location/${mapName}/{z}/{x}/{y}`,
},
// effectively disable raster tiles containing encoded normals
normals: {
max_zoom: 0,
},
"normals-elevation": {
max_zoom: 0,
},
},
};

Building the application: Request transformation


To register and initialize the service worker, create a registerServiceWorker function to be called
before the map is initialized. This registers the JavaScript code provided in a separate file called sw.js as
the service worker controlling index.html.

Credentials are loaded from Amazon Cognito and are passed into the service worker alongside the
Region to provide information to sign tile requests with Signature Version 4.

/**
* Register a service worker that will rewrite and sign requests using Signature Version 4.
*/
async function registerServiceWorker() {
if ("serviceWorker" in navigator) {
try {
const reg = await navigator.serviceWorker.register("./sw.js");

// refresh credentials from Amazon Cognito


await credentials.refreshPromise();

47
Amazon Location Service Developer Guide
Step 3: Display a map in your application

await reg.active.ready;

if (navigator.serviceWorker.controller == null) {
// trigger a navigate event to active the controller for this page
window.location.reload();
}

// pass credentials to the service worker


reg.active.postMessage({
credentials: {
accessKeyId: credentials.accessKeyId,
secretAccessKey: credentials.secretAccessKey,
sessionToken: credentials.sessionToken,
},
region: AWS.config.region,
});
} catch (error) {
console.error("Service worker registration failed:", error);
}
} else {
console.warn("Service worker support is required for this example");
}
}

The Service Worker implementation in sw.js listens for message events to pick up credential and
Region configuration changes. It also acts as a proxy server by listening for fetch events. fetch events
targeting the amazon.location synthetic host name will be rewritten to target the appropriate
Amazon Location API and signed using Amplify Core's Signer.

// sw.js
self.importScripts(
"https://unpkg.com/@aws-amplify/core@3.7.0/dist/aws-amplify-core.min.js"
);

const { Signer } = aws_amplify_core;

let credentials;
let region;

self.addEventListener("install", (event) => {


// install immediately
event.waitUntil(self.skipWaiting());
});

self.addEventListener("activate", (event) => {


// control clients ASAP
event.waitUntil(self.clients.claim());
});

self.addEventListener("message", (event) => {


const {
data: { credentials: newCredentials, region: newRegion },
} = event;

if (newCredentials != null) {
credentials = newCredentials;
}

if (newRegion != null) {
region = newRegion;
}
});

async function signedFetch(request) {

48
Amazon Location Service Developer Guide
Step 3: Display a map in your application

const url = new URL(request.url);


const path = url.pathname.slice(1).split("/");

// update URL to point to Amazon Location


url.pathname = `/maps/v0/maps/${path[0]}/tiles/${path.slice(1).join("/")}`;
url.host = `maps.geo.${region}.amazonaws.com`;
// strip params (Tangram generates an empty api_key param)
url.search = "";

const signed = Signer.signUrl(url.toString(), {


access_key: credentials.accessKeyId,
secret_key: credentials.secretAccessKey,
session_token: credentials.sessionToken,
});

return fetch(signed);
}

self.addEventListener("fetch", (event) => {


const { request } = event;

// match the synthetic hostname we're telling Tangram to use


if (request.url.includes("amazon.location")) {
return event.respondWith(signedFetch(request));
}

// fetch normally
return event.respondWith(fetch(request));
});

To automatically renew credentials and send them to the service worker before they expire , use the
following function within index.html:

async function refreshCredentials() {


await credentials.refreshPromise();

if ("serviceWorker" in navigator) {
const controller = navigator.serviceWorker.controller;

controller.postMessage({
credentials: {
accessKeyId: credentials.accessKeyId,
secretAccessKey: credentials.secretAccessKey,
sessionToken: credentials.sessionToken,
},
});
} else {
console.warn("Service worker support is required for this example.");
}

// schedule the next credential refresh when they're about to expire


setTimeout(refreshCredentials, credentials.expireTime - new Date());
}

Building the application: Map initialization

For the map to display after the page is loaded, you must initialize the map. You have the option to
adjust the initial map location, add additional controls, and overlay data.
Note
You must provide wordmark or text attribution for each data provider that you use, either on
your application or your documentation. Attribution strings are included in the style descriptor
response under the sources.esri.attribution and sources.here.attribution keys.

49
Amazon Location Service Developer Guide
Step 3: Display a map in your application

Since Tangram does not request these resources, and is only compatible with maps from HERE,
use "© 2020 HERE". When using Amazon Location resources with data providers, make sure to
read the service terms and conditions.

/**
* Initialize a map.
*/
async function initializeMap() {
// register the service worker to handle requests to https://amazon.location
await registerServiceWorker();

// actually initialize the map


const map = L.map("map").setView([49.2819, -123.1187], 10);
Tangram.leafletLayer({
scene,
}).addTo(map);
map.attributionControl.setPrefix("");
map.attributionControl.addAttribution("© 2020 HERE");
}

initializeMap();

Running the application


To run this sample, you can:

• Use a host that supports HTTPS,


• Use a local web server to comply with service worker security restrictions.

To use a local web server, you can use npx since it's installed as a part of Node.js. You can use npx
serve from within the same directory as index.html and sw.js. This serves the application on
localhost:5000.

The following is the index.html file:

<!-- index.html -->


<html>
<head>
<link
rel="stylesheet"
href="https://unpkg.com/leaflet@1.7.1/dist/leaflet.css"
integrity="sha512-xodZBNTC5n17Xt2atTPuE1HxjVMSvLVW9ocqUKLsCC5CXdbqCmblAshOMAS6/keqq/
sMZMZ19scR4PsZChSR7A=="
crossorigin=""
/>
<style>
body {
margin: 0;
}

#map {
height: 100vh;
}
</style>
</head>

<body>
<div id="map" />
<script src="https://unpkg.com/leaflet@1.7.1/dist/leaflet.js"></script>
<script src="https://unpkg.com/tangram"></script>
<script src="https://sdk.amazonaws.com/js/aws-sdk-2.784.0.min.js"></script>
<script>

50
Amazon Location Service Developer Guide
Step 3: Display a map in your application

// configuration
// Cognito Identity Pool ID
const identityPoolId = "<Identity Pool ID>";
// Amazon Location Service Map name; must be HERE-backed
const mapName = "<Map name>";

AWS.config.region = identityPoolId.split(":")[0];

// instantiate a credential provider


credentials = new AWS.CognitoIdentityCredentials({
IdentityPoolId: identityPoolId,
});

const scene = {
import: [
// Bubble Wrap style
"https://www.nextzen.org/carto/bubble-wrap-style/10/bubble-wrap-style.zip",
"https://www.nextzen.org/carto/bubble-wrap-style/10/themes/label-7.zip",
"https://www.nextzen.org/carto/bubble-wrap-style/10/themes/bubble-wrap-road-
shields-usa.zip",
"https://www.nextzen.org/carto/bubble-wrap-style/10/themes/bubble-wrap-road-
shields-international.zip",
],
// override values beneath the `sources` key in the style above
sources: {
mapzen: {
// point at Amazon Location using a synthetic URL, which will be handled by the
service
// worker
url: `https://amazon.location/${mapName}/{z}/{x}/{y}`,
},
// effectively disable raster tiles containing encoded normals
normals: {
max_zoom: 0,
},
"normals-elevation": {
max_zoom: 0,
},
},
};

/**
* Register a service worker that will rewrite and sign requests using Signature
Version 4.
*/
async function registerServiceWorker() {
if ("serviceWorker" in navigator) {
try {
const reg = await navigator.serviceWorker.register("./sw.js");

// refresh credentials from Amazon Cognito


await credentials.refreshPromise();

await reg.active.ready;

if (navigator.serviceWorker.controller == null) {
// trigger a navigate event to active the controller for this page
window.location.reload();
}

// pass credentials to the service worker


reg.active.postMessage({
credentials: {
accessKeyId: credentials.accessKeyId,
secretAccessKey: credentials.secretAccessKey,
sessionToken: credentials.sessionToken,

51
Amazon Location Service Developer Guide
Step 3: Display a map in your application

},
region: AWS.config.region,
});
} catch (error) {
console.error("Service worker registration failed:", error);
}
} else {
console.warn("Service Worker support is required for this example");
}
}

/**
* Initialize a map.
*/
async function initializeMap() {
// register the service worker to handle requests to https://amazon.location
await registerServiceWorker();

// actually initialize the map


const map = L.map("map").setView([49.2819, -123.1187], 10);
Tangram.leafletLayer({
scene,
}).addTo(map);
map.attributionControl.setPrefix("");
map.attributionControl.addAttribution("© 2020 HERE");
}

initializeMap();
</script>
</body>
</html>

The following is the sw.js file:

// sw.js
self.importScripts(
"https://unpkg.com/@aws-amplify/core@3.7.0/dist/aws-amplify-core.min.js"
);

const { Signer } = aws_amplify_core;

let credentials;
let region;

self.addEventListener("install", (event) => {


// install immediately
event.waitUntil(self.skipWaiting());
});

self.addEventListener("activate", (event) => {


// control clients ASAP
event.waitUntil(self.clients.claim());
});

self.addEventListener("message", (event) => {


const {
data: { credentials: newCredentials, region: newRegion },
} = event;

if (newCredentials != null) {
credentials = newCredentials;
}

if (newRegion != null) {
region = newRegion;

52
Amazon Location Service Developer Guide
Step 3: Display a map in your application

}
});

async function signedFetch(request) {


const url = new URL(request.url);
const path = url.pathname.slice(1).split("/");

// update URL to point to Amazon Location


url.pathname = `/maps/v0/maps/${path[0]}/tiles/${path.slice(1).join("/")}`;
url.host = `maps.geo.${region}.amazonaws.com`;
// strip params (Tangram generates an empty api_key param)
url.search = "";

const signed = Signer.signUrl(url.toString(), {


access_key: credentials.accessKeyId,
secret_key: credentials.secretAccessKey,
session_token: credentials.sessionToken,
});

return fetch(signed);
}

self.addEventListener("fetch", (event) => {


const { request } = event;

// match the synthetic hostname we're telling Tangram to use


if (request.url.includes("amazon.location")) {
return event.respondWith(signedFetch(request));
}

// fetch normally
return event.respondWith(fetch(request));
});

This sample is available as part of the Amazon Location Service samples repository on GitHub.

Using Tangram ES for Android with Amazon Location Service


Tangram ES is a C++ library for rendering 2D and 3D maps from vector data using OpenGL ES. It is the
native counterpart to Tangram.

Tangram styles built to work with the Tilezen schema are largely compatible with Amazon Location when
using maps from HERE. These include:

• Bubble Wrap – A full-featured wayfinding style with helpful icons for points of interest.
• Cinnabar – A classic look and go-to for general mapping applications.
• Refill – A minimalist map style designed for data visualization overlays, inspired by the seminal Toner
style by Stamen Design.
• Tron – An exploration of scale transformations in the visual language of TRON.
• Walkabout – An outdoor-focused style that's perfect for hiking or getting out and about.

This guide describes how to integrate Tangram ES for Android with Amazon Location using the Tangram
style called Cinnabar. This sample is available as part of the Amazon Location Service samples repository
on GitHub.

While other Tangram styles are best accompanied by raster tiles, which encode terrain information, this
feature is not yet supported by Amazon Location.
Important
The Tangram styles in the following tutorial are only compatible with Amazon Location map
resources configured with the VectorHereBerlin style.

53
Amazon Location Service Developer Guide
Step 3: Display a map in your application

Building the application: Initialization

To initialize your application:

1. Create a new Android Studio project from the Empty Activity template.
2. Ensure that Kotlin is selected for the project language.
3. Select a Minimum SDK of API 16: Android 4.1 (Jelly Bean) or newer.
4. Open Project Structure to select File, Project Structure..., and choose the Dependencies section.
5. With <All Modules> selected, choose the + button to add a new Library Dependency.
6. Add AWS Android SDK version 2.19.1 or later. For example: com.amazonaws:aws-android-sdk-
core:2.19.1
7. Add Tangram version 0.13.0 or later. For example: com.mapzen.tangram:tangram:0.13.0.
Note
Searching for Tangram: com.mapzen.tangram:tangram:0.13.0 will generate a
message that it's "not found", but choosing OK will allow it to be added.

Building the application: Configuration

To configure your application with your resources and AWS Region:

1. Create app/src/main/res/values/configuration.xml.
2. Enter the names and identifiers of your resources as well as the AWS Region they were created in:

<?xml version="1.0" encoding="utf-8"?>


<resources>
<string name="identityPoolId">us-east-1:54f2ba88-9390-498d-aaa5-0d97fb7ca3bd</string>
<string name="mapName">TangramExampleMap</string>
<string name="awsRegion">us-east-1</string>
<string name="sceneUrl">https://www.nextzen.org/carto/cinnabar-style/9/cinnabar-
style.zip</string>
<string name="attribution">© 2020 HERE</string>
</resources>

Building the application: Activity layout

Edit app/src/main/res/layout/activity_main.xml:

• Add a MapView, which renders the map. This will also set the map's initial center point.
• Add a TextView, which displays attribution.

This will also set the map's initial center point.


Note
You must provide wordmark or text attribution for each data provider that you use, either on
your application or your documentation. Attribution strings are included in the style descriptor
response under the sources.esri.attribution and sources.here.attribution keys.
Since Tangram does not request these resources, and is only compatible with maps from HERE,
use "© 2020 HERE". When using Amazon Location resources with data providers, make sure to
read the service terms and conditions.

<?xml version="1.0" encoding="utf-8"?>


<androidx.constraintlayout.widget.ConstraintLayout

54
Amazon Location Service Developer Guide
Step 3: Display a map in your application

xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<com.mapzen.tangram.MapView
android:id="@+id/map"
android:layout_height="match_parent"
android:layout_width="match_parent" />

<TextView
android:id="@+id/attributionView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#80808080"
android:padding="5sp"
android:textColor="@android:color/black"
android:textSize="10sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
tools:ignore="SmallSp" />
</androidx.constraintlayout.widget.ConstraintLayout>

Building the application: Request transformation

Create a class named SigV4Interceptor to intercept AWS requests and sign them using Signature
Version 4. This will be registered with the HTTP client used to fetch map resources when the Main
Activity is created.

package aws.location.demo.okhttp

import com.amazonaws.DefaultRequest
import com.amazonaws.auth.AWS4Signer
import com.amazonaws.auth.AWSCredentialsProvider
import com.amazonaws.http.HttpMethodName
import com.amazonaws.util.IOUtils
import okhttp3.HttpUrl
import okhttp3.Interceptor
import okhttp3.Request
import okhttp3.Response
import okio.Buffer
import java.io.ByteArrayInputStream
import java.net.URI

class SigV4Interceptor(
private val credentialsProvider: AWSCredentialsProvider,
private val serviceName: String
) : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response {
val originalRequest = chain.request()

if (originalRequest.url().host().contains("amazonaws.com")) {
val signer = if (originalRequest.url().encodedPath().contains("@")) {
// the presence of "@" indicates that it doesn't need to be double URL-
encoded
AWS4Signer(false)
} else {
AWS4Signer()
}

val awsRequest = toAWSRequest(originalRequest, serviceName)


signer.setServiceName(serviceName)

55
Amazon Location Service Developer Guide
Step 3: Display a map in your application

signer.sign(awsRequest, credentialsProvider.credentials)

return chain.proceed(toSignedOkHttpRequest(awsRequest, originalRequest))


}

return chain.proceed(originalRequest)
}

companion object {
fun toAWSRequest(request: Request, serviceName: String): DefaultRequest<Any> {
// clone the request (AWS-style) so that it can be populated with credentials
val dr = DefaultRequest<Any>(serviceName)

// copy request info


dr.httpMethod = HttpMethodName.valueOf(request.method())
with(request.url()) {
dr.resourcePath = uri().path
dr.endpoint = URI.create("${scheme()}://${host()}")

// copy parameters
for (p in queryParameterNames()) {
if (p != "") {
dr.addParameter(p, queryParameter(p))
}
}
}

// copy headers
for (h in request.headers().names()) {
dr.addHeader(h, request.header(h))
}

// copy the request body


val bodyBytes = request.body()?.let { body ->
val buffer = Buffer()
body.writeTo(buffer)
IOUtils.toByteArray(buffer.inputStream())
}

dr.content = ByteArrayInputStream(bodyBytes ?: ByteArray(0))

return dr
}

fun toSignedOkHttpRequest(
awsRequest: DefaultRequest<Any>,
originalRequest: Request
): Request {
// copy signed request back into an OkHttp Request
val builder = Request.Builder()

// copy headers from the signed request


for ((k, v) in awsRequest.headers) {
builder.addHeader(k, v)
}

// start building an HttpUrl


val urlBuilder = HttpUrl.Builder()
.host(awsRequest.endpoint.host)
.scheme(awsRequest.endpoint.scheme)
.encodedPath(awsRequest.resourcePath)

// copy parameters from the signed request


for ((k, v) in awsRequest.parameters) {
urlBuilder.addQueryParameter(k, v)
}

56
Amazon Location Service Developer Guide
Step 3: Display a map in your application

return builder.url(urlBuilder.build())
.method(originalRequest.method(), originalRequest.body())
.build()
}
}
}

Building the application: Main activity

The Main Activity is responsible for initializing the views that will be displayed to users. This involves:

• Instantiating an Amazon Cognito CredentialsProvider.


• Registering the Signature Version 4 interceptor.
• Configuring the map by pointing it at a map style, overriding tile URLs, and displaying appropriate
attribution.

MainActivity is also responsible for forwarding life cycle events to the map view.

package aws.location.demo.tangram

import android.os.Bundle
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import aws.location.demo.okhttp.SigV4Interceptor
import com.amazonaws.auth.CognitoCachingCredentialsProvider
import com.amazonaws.regions.Regions
import com.mapzen.tangram.*
import com.mapzen.tangram.networking.DefaultHttpHandler
import com.mapzen.tangram.networking.HttpHandler

private const val SERVICE_NAME = "geo"

class MainActivity : AppCompatActivity(), MapView.MapReadyCallback {


private var mapView: MapView? = null

override fun onCreate(savedInstanceState: Bundle?) {


super.onCreate(savedInstanceState)

setContentView(R.layout.activity_main)

mapView = findViewById(R.id.map)

mapView?.getMapAsync(this, getHttpHandler())
findViewById<TextView>(R.id.attributionView).text = getString(R.string.attribution)
}

override fun onMapReady(mapController: MapController?) {


val sceneUpdates = arrayListOf(
SceneUpdate(
"sources.mapzen.url",
"https://maps.geo.${getString(R.string.awsRegion)}.amazonaws.com/maps/v0/
maps/${
getString(
R.string.mapName
)
}/tiles/{z}/{x}/{y}"
)
)

mapController?.let { map ->


map.updateCameraPosition(

57
Amazon Location Service Developer Guide
Step 3: Display a map in your application

CameraUpdateFactory.newLngLatZoom(
LngLat(-123.1187, 49.2819),
12F
)
)
map.loadSceneFileAsync(
getString(R.string.sceneUrl),
sceneUpdates
)
}
}

private fun getHttpHandler(): HttpHandler {


val builder = DefaultHttpHandler.getClientBuilder()

val credentialsProvider = CognitoCachingCredentialsProvider(


applicationContext,
getString(R.string.identityPoolId),
Regions.US_EAST_1
)

return DefaultHttpHandler(
builder.addInterceptor(
SigV4Interceptor(
credentialsProvider,
SERVICE_NAME
)
)
)
}

override fun onResume() {


super.onResume()
mapView?.onResume()
}

override fun onPause() {


super.onPause()
mapView?.onPause()
}

override fun onLowMemory() {


super.onLowMemory()
mapView?.onLowMemory()
}

override fun onDestroy() {


super.onDestroy()
mapView?.onDestroy()
}
}

Running this application displays a full-screen map in the style of your choosing. This sample is available
as part of the Amazon Location Service samples repository on GitHub.

Using Tangram ES for iOS with Amazon Location Service


Tangram ES is a C++ library for rendering 2D and 3D maps from vector data using OpenGL ES. It is the
native counterpart to Tangram.

Tangram styles built to work with the Tilezen schema are largely compatible with Amazon Location when
using maps from HERE. These include:

• Bubble Wrap – A full-featured wayfinding style with helpful icons for points of interest

58
Amazon Location Service Developer Guide
Step 3: Display a map in your application

• Cinnabar – A classic look and go-to for general mapping applications


• Refill – A minimalist map style designed for data visualization overlays, inspired by the seminal Toner
style by Stamen Design
• Tron – An exploration of scale transformations in the visual language of TRON
• Walkabout – An outdoor-focused style that's perfect for hiking or getting out and about

This guide describes how to integrate Tangram ES for iOS with Amazon Location using the Tangram style
called Cinnabar. This sample is available as part of the Amazon Location Service samples repository on
GitHub.

While other Tangram styles are best accompanied by raster tiles, which encode terrain information, this
feature is not yet supported by Amazon Location.
Important
The Tangram styles in the following tutorial are only compatible with Amazon Location map
resources configured with the VectorHereBerlin style.

Building the application: Initialization

To initialize the application:

1. Create a new Xcode project from the App template.


2. Select SwiftUI for its interface.
3. Select SwiftUI application for its Life Cycle.
4. Select Swift for its language.

Building the application: Add dependencies

To add dependencies, you can use a dependency manager such as CocoaPods:

1. In your terminal, install CocoaPods:

sudo gem install cocoapods

2. Navigate to your application's project directory and initialize the Podfile with the CocoaPods
package manager:

pod init

3. Open the Podfile to add AWSCore and Tangram-es as dependencies:

platform :ios, '12.0'

target 'Amazon Location Service Demo' do


use_frameworks!

pod 'AWSCore'
pod 'Tangram-es'
end

4. Download and install dependencies:

pod install --repo-update

5. Open the Xcode workspace that CocoaPods created:

59
Amazon Location Service Developer Guide
Step 3: Display a map in your application

xed .

Building the application: Configuration


Add the following keys and values to Info.plist to configure the application and disable telemetry:

Key Value

AWSRegion us-east-1

IdentityPoolId us-east-1:54f2ba88-9390-498d-
aaa5-0d97fb7ca3bd

MapName ExampleMap

SceneURL https://www.nextzen.org/carto/cinnabar-style/9/
cinnabar-style.zip

Building the application: ContentView layout


To render the map, edit ContentView.swift:

• Add a MapView which renders the map.


• Add a TextField which displays attribution.

This also sets the map's initial center point.


Note
You must provide wordmark or text attribution for each data provider that you use, either on
your application or your documentation. Attribution strings are included in the style descriptor
response under the sources.esri.attribution and sources.here.attribution keys.
When using Amazon Location resources with data providers, make sure to read the service terms
and conditions.

import SwiftUI
import TangramMap

struct ContentView: View {


var body: some View {
MapView()
.cameraPosition(TGCameraPosition(
center: CLLocationCoordinate2DMake(49.2819, -123.1187),
zoom: 10,
bearing: 0,
pitch: 0))
.edgesIgnoringSafeArea(.all)
.overlay(
Text("© 2020 HERE")
.disabled(true)
.font(.system(size: 12, weight: .light, design: .default))
.foregroundColor(.black)
.background(Color.init(Color.RGBColorSpace.sRGB, white: 0.5, opacity:
0.5))
.cornerRadius(1),
alignment: .bottomTrailing)
}
}

60
Amazon Location Service Developer Guide
Step 3: Display a map in your application

struct ContentView_Previews: PreviewProvider {


static var previews: some View {
ContentView()
}
}

Building the application: Request transformation

Create a new Swift file named AWSSignatureV4URLHandler.swift containing the following class
definition to intercept AWS requests and sign them using Signature Version 4. This will be registered as a
URL handler within the Tangram MapView.

import AWSCore
import TangramMap

class AWSSignatureV4URLHandler: TGDefaultURLHandler {


private let region: AWSRegionType
private let identityPoolId: String
private let credentialsProvider: AWSCredentialsProvider

init(region: AWSRegionType, identityPoolId: String) {


self.region = region
self.identityPoolId = identityPoolId
self.credentialsProvider = AWSCognitoCredentialsProvider(regionType: region,
identityPoolId: identityPoolId)
super.init()
}

override func downloadRequestAsync(_ url: URL, completionHandler: @escaping


TGDownloadCompletionHandler) -> UInt {
if url.host?.contains("amazonaws.com") != true {
// not an AWS URL
return super.downloadRequestAsync(url, completionHandler: completionHandler)
}

// URL-encode spaces, etc.


let keyPath = String(url.path.dropFirst())
guard let keyPathSafe =
keyPath.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else {
print("Invalid characters in path '\(keyPath)'; unsafe to sign")
return super.downloadRequestAsync(url, completionHandler: completionHandler)
}

// sign the URL


let endpoint = AWSEndpoint(region: region, serviceName: "geo", url: url)
let requestHeaders: [String: String] = ["host": endpoint!.hostName]
let task = AWSSignatureV4Signer
.generateQueryStringForSignatureV4(
withCredentialProvider: credentialsProvider,
httpMethod: .GET,
expireDuration: 60,
endpoint: endpoint!,
keyPath: keyPathSafe,
requestHeaders: requestHeaders,
requestParameters: .none,
signBody: true)
task.waitUntilFinished()

if let error = task.error as NSError? {


print("Error occurred: \(error)")
}

if let result = task.result {

61
Amazon Location Service Developer Guide
Step 3: Display a map in your application

// have Tangram fetch the signed URL


return super.downloadRequestAsync(result as URL, completionHandler:
completionHandler)
}

// fall back to an unsigned URL


return super.downloadRequestAsync(url, completionHandler: completionHandler)
}
}

Building the application: Map view

The map view is responsible for initializing an instance of AWSSignatureV4Delegate and configuring
the underlying MGLMapView, which fetches resources and renders the map. It also handles propagating
attribution strings from the style descriptor's source back to the ContentView.

Create a new Swift file named MapView.swift containing the following struct definition:

import AWSCore
import TangramMap
import SwiftUI

struct MapView: UIViewRepresentable {


private let mapView: TGMapView

init() {
let regionName = Bundle.main.object(forInfoDictionaryKey: "AWSRegion") as! String
let identityPoolId = Bundle.main.object(forInfoDictionaryKey: "IdentityPoolId") as!
String
let mapName = Bundle.main.object(forInfoDictionaryKey: "MapName") as! String
let sceneURL = URL(string: Bundle.main.object(forInfoDictionaryKey: "SceneURL") as!
String)!

let region = (regionName as NSString).aws_regionTypeValue()

// rewrite tile URLs to point at AWS resources


let sceneUpdates = [
TGSceneUpdate(path: "sources.mapzen.url",
value: "https://maps.geo.\(regionName).amazonaws.com/maps/v0/
maps/\(mapName)/tiles/{z}/{x}/{y}")]

// instantiate a TGURLHandler that will sign AWS requests


let urlHandler = AWSSignatureV4URLHandler(region: region, identityPoolId:
identityPoolId)

// instantiate the map view and attach the URL handler


mapView = TGMapView(frame: .zero, urlHandler: urlHandler)

// load the map style and apply scene updates (properties modified at runtime)
mapView.loadScene(from: sceneURL, with: sceneUpdates)
}

func cameraPosition(_ cameraPosition: TGCameraPosition) -> MapView {


mapView.cameraPosition = cameraPosition

return self
}

// MARK: - UIViewRepresentable protocol

func makeUIView(context: Context) -> TGMapView {


return mapView
}

62
Amazon Location Service Developer Guide
Geocoding, reverse geocoding, and searching

func updateUIView(_ uiView: TGMapView, context: Context) {


}
}

Running this application displays a full-screen map in the style of your choosing. This sample is available
as part of the Amazon Location Service samples repository on GitHub.

Geocoding, reverse geocoding and searching using


Amazon Location
Amazon Location lets you select a data provider for geocoding, reverse-geocoding, and search
operations by creating and configuring a place index.

Once the resource has been created, you can send requests to it using the AWS SDK for your preferred
language, Amplify, or the REST API endpoints. Data returned from these requests can be used to mark
locations on a map, enrich position data, and to convert positions into human-readable text.

Topics
• Create a place index resource (p. 63)
• Create an identity pool to allow unauthenticated access to your application (p. 64)
• Geocoding and reverse geocoding (p. 65)

Create a place index resource


Before you can make geocoding and reverse geocoding queries, you must first create a place index
resource in your AWS account. You can use the Amazon Location console, the AWS CLI, or the Amazon
Location APIs to do this:

Console

To create a place index resource using the Amazon Location console

1. Open the Amazon Location console at https://console.aws.amazon.com/location/.


2. In the left navigation pane, choose Place indexes.
3. Choose Add place index.
4. Fill out the following boxes:

• Name – Enter a name for the place index resource. For example, ExamplePlaceIndex.
Maximum 100 characters. Valid entries include alphanumeric characters, hyphens, periods,
and underscores.
• Description – Enter an optional description.
5. Select the intended use of data from API calls to this resource:

• Single Use – Specifies that the results will not be stored.


• Description – Specifies that the result will be cached or stored.
6. Select an available data provider.
7. Choose Add index.

API

To create a place index resource using the Amazon Location APIs

63
Amazon Location Service Developer Guide
Step 2: Creating an unauthenticated identity pool

Use the CreatePlaceIndex action from the Amazon Location Places APIs.

The following example is an API request to create a place index resource called
ExamplePlaceIndex using the data provider Esri, and a request-based usage pricing plan.
Note
During the preview period, you will not incur Amazon Location Service charges for the
use of the service. You may incur fees for the use of other AWS services. For additional
information on pricing, see the Amazon Location service page.

POST /places/v0/indexes
Content-type: application/json

{
"DataSource": "Esri",
"DataSourceConfiguration": {
"IntendedUse": "SingleUse"
},
"Description": "string",
"IndexName": "ExamplePlaceIndex"
"PricingPlan": "RequestBasedUsage"
}

AWS CLI

To create a place index resource using AWS CLI commands

Use the create-place-index command.

The following example creates a place index resource called ExamplePlaceIndex using Esri as
the data provider, and a request-based usage pricing plan.
Note
During the preview period, you will not incur Amazon Location Service charges for the
use of the service. You may incur fees for the use of other AWS services. For additional
information on pricing, see the Amazon Location service page.

aws location \
create-place-index \
--data-source "Esri" \
--index-name "ExamplePlaceIndex" \
--pricing-plan "RequestBasedUsage"

Create an identity pool to allow unauthenticated


access to your application
Before you can geocode or reverse geocode, use Amazon Cognito to create an unauthenticated identity
pool with a scoped-down AWS Identity and Access Management (IAM) role that allows read-only access
to the Amazon Location Places APIs.
Important
Ensure that the pool you create is in the same AWS Region as the place index resources that
you're using.

The pool's ID will take the form <region>:<GUID>. For example:

us-east-1:54f2ba88-9390-498d-aaa5-0d97fb7ca3bd

64
Amazon Location Service Developer Guide
Step 3: Geocoding and reverse geocoding

The following is an example of a scoped-down IAM policy allowing access to a place index resource
named ExamplePlaceIndex for geocoding or reverse geocoding:

{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "PlacesReadOnly",
"Effect": "Allow",
"Action": [
"geo:SearchPlaceIndex*"
],
"Resource": "arn:aws:geo:region:accountID:place-index/ExamplePlaceIndex"
}
]
}

The following is an example of passing the unauthenticated identity pool you've created to be used as
credentials when using the AWS JavaScript SDK:

const AWS = require("aws-sdk");

const credentials = new AWS.CognitoIdentityCredentials({


IdentityPoolId: "<identity pool ID>" // e.g., us-east-1:54f2ba88-9390-498d-
aaa5-0d97fb7ca3bd
});

const client = new AWS.Location({


credentials,
region: AWS.config.region // region containing Cognito pool
});

// rsp.Results contains search results


const rsp = await location.searchPlaceIndexForText({
IndexName: "ExamplePlaceIndex",
Text: "Anyplace",
BiasPosition: [-123.4567, 45.6789]
}).promise();

Geocoding and reverse geocoding


You can use place indexes to send the following queries:

• Geocoding, which converts an address to a set of coordinates.


• Reverse geocoding, which converts coordinates to a human readable address.

You can incorporate data retrieved from geocoding and reverse geocoding queries to display data on a
map for your web or mobile application.

Search place index resources for text (geocoding)


Once you have a place index resource, you can submit an API request to search the place index for
addresses, cities, regions, business names, or points of interest.

You can use the AWS CLI or the Amazon Location APIs to do this:

API

Use the SearchPlaceIndexForText action from the Amazon Location Places APIs.

65
Amazon Location Service Developer Guide
Step 3: Geocoding and reverse geocoding

The following example is an API request to search the ExamplePlaceIndex place index for the text
Any Town, USA with a bias for results near longitude -123.4567, latitude 45.6789.

POST /places/v0/indexes/ExamplePlaceIndex/search/text
Content-type: application/json

{
"BiasPosition": [ -123.4567,45.6789 ],
"FilterCountries": [ "USA" ],
"Text": "Any Town"
}

AWS CLI

Use the search-place-index-for-text command.

The following example is an AWS CLI command to search the place index ExamplePlaceIndex for
the text Any Town, USA with a bias for results near longitude -123.4567, latitude 45.6789.

aws location \
search-place-index-for-text \
--index-name ExamplePlaceIndex \
--bias-position -123.4567 45.6789 \
--filter-countries "USA" \
--text "Any Town"

Example

Response Example

The following is an example response when calling the SearchPlaceIndexForText action from the
Amazon Location Places APIs.

{
"Results": [
{
"Place": {
"AddressNumber": "123",
"Country": "USA",
"Geometry": {
"Point": [ -123.4567,45.6789 ]
},
"Label": "Any Town, 123 Main St, USA",
"Municipality": "Any Town",
"Neighborhood": "Downtown",
"PostalCode": "12345",
"Region": "Any State",
"Street": "Main St",
"SubRegion": "Any Subregion"
}
}
],
"Summary": {
"BiasPosition": [ -123.4567,45.6789 ],
"DataSource": "Esri",
"FilterBBox": [ number ],
"FilterCountries": [ "USA" ],
"MaxResults": number,
"ResultBBox": [ number ],
"Text": "Any Town"
}

66
Amazon Location Service Developer Guide
Step 3: Geocoding and reverse geocoding

Search place index resources for a position (reverse geocoding)


You can also submit an API request to query the Place Index for a position, also known as reverse
geocoding, to convert coordinates to a meaningful address, a point of interest, or location without an
address.

You can use the AWS CLI or the Amazon Location APIs to do this:

API

Use the SearchPlaceIndexForPosition action from the Amazon Location Places APIs.

The following example is an API request to search the place index ExamplePlaceIndex for places
near longitude -123.4567, latitude 45.6789.

POST /places/v0/indexes/ExamplePlaceIndex/search/position
Content-type: application/json

{
"Position": [ -123.4567,45.6789 ]
}

AWS CLI

Use the search-place-index-for-position command.

The following example is an AWS CLI command to search the place index ExamplePlaceIndex for
a place near longitude -123.4567, latitude 45.6789.

aws location \
search-place-index-for-position \
--index-name ExamplePlaceIndex \
--position -123.4567 45.6789

Example

Response example

The following is an example response when calling the SearchPlaceIndexForPosition action from
the Amazon Location Places APIs.

{
"Results": [
{
"Place": {
"AddressNumber": "123",
"Country": "USA",
"Geometry": {
"Point": [ -123.4567,45.6789 ]
},
"Label": "Any Town, 123 Main St, USA",
"Municipality": "Any Town",
"Neighborhood": "Downtown",
"PostalCode": "12345",
"Region": "Any State",
"Street": "Main Street",

67
Amazon Location Service Developer Guide
Geofencing an area of interest

"SubRegion": "Any Subregion"


}
}
],
"Summary": {
"DataSource": "Esri",
"MaxResults": 100,
"Position": [ -123.4567,45.6789 ]
}
}

Geofencing an area of interest using Amazon


Location
A geofencing application evaluates a tracked device’s position relative to previously registered areas of
interest. This enables actions to be taken based on position updates. For example, you can trigger an
event that prompts a notification when a customer who ordered coffee on their mobile app is near a
store.

This section of the guide provides step-by-step instructions for creating a geofencing application using
Amazon Location Service.

Overview of steps

1. Add geofences around areas of interest and store them in a geofence collection resource.
2. Start tracking your target devices and store the device location history in a tracker resource.
3. Link your tracker resource to your geofence collection resource so that device location updates are
automatically evaluated against all your geofences.
4. You can evaluate device positions directly against your geofence collection resources if you don’t
want to use Amazon Location Trackers to keep your devices’ location history.

After you implement your geofencing solution, your geofence collection resource emits the following
events:

• ENTER — A tracked device enters a geofence within a geofence collection.


• EXIT — A tracked device exits a geofence within a geofence collection.

You can use Amazon EventBridge to react to events by routing them elsewhere. For more information,
see Reacting to Amazon Location Service events with Amazon EventBridge.

Add geofences
Geofences contain points and vertices that form a closed boundary, which defines an area of interest.
Geofence collections store and manage one or multiple geofences.

Amazon Location geofence collections stores geofences defined by using a standard geospatial data
format called GeoJSON (RFC 7946). You can use tools, such as geojson.io, at no charge to draw your
geofences graphically and save the output GeoJSON file.
Note
Amazon Location currently does not support polygons with holes, multipolygons, polygons that
are wound clockwise, and geofences that cross the antimeridian.

68
Amazon Location Service Developer Guide
Step 1: Add geofences

Create a geofence collection


Create a geofence collection to store and manage geofences by using the Amazon Location console, the
AWS CLI, or the Amazon Location APIs.

Console

To create a geofence collection using the Amazon Location console

1. Open the Amazon Location console at https://console.aws.amazon.com/location/.


2. In the left navigation pane, choose Geofence collections.
3. Choose Create geofence collection.
4. Fill out the following boxes:

• Name – Enter a unique name. For example, ExampleGeofenceCollection. Maximum 100


characters. Valid entries include alphanumeric characters, hyphens, periods, and underscores.
• Description – Enter an optional description.
5. Choose Create geofence collection.

API

To create a geofence collection using the Amazon Location APIs

Use the CreateGeofenceCollection action from the Amazon Location Geofences APIs.

The following example uses an API request to create a geofence collection called
ExampleGeofenceCollection, and a request-based usage pricing plan.
Note
During the preview period, you will not incur Amazon Location Service charges for the use
of the service. You may incur fees for using other AWS services. For more information about
pricing, see the Amazon Location service page.

POST /geofencing/v0/collections
Content-type: application/json

{
"CollectionName": "ExampleGeofenceCollection",
"Description": "string"
"PricingPlan": "RequestBasedUsage"
}

AWS CLI

To create a geofence collection using AWS CLI commands

Use the create-geofence-collection command.

The following example uses an AWS CLI to create a geofence collection called
ExampleGeofenceCollection, and a request-based usage pricing plan.
Note
During the preview period, you will not incur Amazon Location Service charges for the use
of the service. You may incur fees for the use of other AWS services. For more information
about pricing, see the Amazon Location service page.

aws location \
create-geofence-collection \
--collection-name "ExampleGeofenceCollection" \

69
Amazon Location Service Developer Guide
Step 1: Add geofences

--pricing-plan "RequestBasedUsage"

Draw geofences using a GeoJSON tool


Now that you've created your geofence collection, you can define your geofences by using a GeoJSON
editing tool, such as geojson.io.

To create a GeoJSON file

1. Open a GeoJSON editing tool. For example, geojson.io.


2. Choose the Draw a polygon icon and draw your area of interest.
3. Choose Save, then choose GeoJSON from the dropdown menu.

Put geofences in a geofence collection


You can use the resulting GeoJSON file to upload your geofences using the Amazon Location console,
the AWS CLI, or the Amazon Location APIs:

Console

To add a geofence to a geofence collection using the Amazon Location console

1. Open the Amazon Location console at https://console.aws.amazon.com/location/.


2. In the left navigation pane, choose Geofence collections.
3. From the Geofence collections list, select the name link for the target geofence collection.
4. Under Geofences, choose Create geofences.
5. In the Add geofences window, drag and drop your GeoJSON into the window.
6. Choose Add geofences.

API

To add geofences using the Amazon Location APIs

Use the PutGeofence action from the Amazon Location Geofences APIs.

The following example uses an API request to add a geofence given the ID GEOFENCE-EXAMPLE1 to
a geofence collection called ExampleGeofenceCollection:

PUT /geofencing/v0/collections/ExampleGeofenceCollection/geofence/GEOFENCE-EXAMPLE1
Content-type: application/json

{
"Geometry": {
"Polygon": [
[
[-5.716667, -15.933333],
[-14.416667, -7.933333],
[-12.316667, -37.066667],
[-5.716667, -15.933333]
]
]
}
}

Alternatively, you can add more than one geofence using the BatchPutGeofence action.

70
Amazon Location Service Developer Guide
Step 2: Start tracking

POST /geofencing/v0/collections/ExampleGeofenceCollection/put-geofences
Content-type: application/json

{
"Entries": [
{
"GeofenceId": "GEOFENCE-EXAMPLE1",
"Geometry": {
"Polygon": [
[
[-5.716667, -15.933333],
[-14.416667, -7.933333],
[-12.316667, -37.066667],
[-5.716667, -15.933333]
]
]
}
}
]
}

AWS CLI

To add a geofence to a geofence collection using AWS CLI commands

Use the put-geofence command.

The following example uses an AWS CLI to add a geofence to a geofence collection called
ExampleGeofenceCollection.

$ aws location \
put-geofence \
--collection-name ExampleGeofenceCollection \
--geofence-id ExampleGeofenceTriangle \
--geometry 'Polygon=[[[-5.716667, -15.933333],[-14.416667, -7.933333],
[-12.316667, -37.066667],[-5.716667, -15.933333]]]'
{
"CreateTime": "2020-11-11T00:16:14.487000+00:00",
"GeofenceId": "ExampleGeofenceTriangle",
"UpdateTime": "2020-11-11T00:19:59.894000+00:00"
}

Start tracking
This section guides you through building a tracking application that captures device locations.

Create a tracker
Create a tracker resource to receive location updates from devices capable of transmitting a location
update, such as a mobile phone or GPS receiver. This allows you to monitor multiple assets as they move.
You can use the Amazon Location console, the AWS CLI, or the Amazon Location APIs.

Console

To create a tracker using the Amazon Location console

1. Open the Amazon Location console at https://console.aws.amazon.com/location/.


2. In the left navigation pane, choose Trackers.

71
Amazon Location Service Developer Guide
Step 2: Start tracking

3. Choose Create tracker.


4. Fill out the following boxes:

• Name – Enter a unique name. For example, ExampleTracker. Maximum 100 characters.
Valid entries include alphanumeric characters, hyphens, periods, and underscores.
• Description – Enter an optional description.
5. Choose Create tracker.

API

To create a tracker using the Amazon Location APIs

Use the CreateTracker action from the Amazon Location Trackers APIs.

The following example uses an API request to create a tracker called ExampleTracker, and a
request-based usage pricing plan.
Note
During the preview period, you will not incur Amazon Location Service charges for the use
of the service. You may incur fees for the use of other AWS services. For more information
about pricing, see the Amazon Location service page.

POST /tracking/v0/trackers
Content-type: application/json

{
"Description": "string",
"PricingPlan": "RequestBasedUsage"
"TrackerName": "ExampleTracker"
}

AWS CLI

To create a tracker using AWS CLI commands

Use the create-tracker command.

The following example uses an AWS CLI to create a tracker called ExampleTracker, and a request-
based usage pricing plan.
Note
During the preview period, you will not incur Amazon Location Service charges for the use
of the service. You may incur fees for the use of other AWS services. For more information
about pricing, see the Amazon Location service page.

aws location \
create-tracker \
--tracker-name "ExampleTracker" \
--pricing-plan "RequestBasedUsage"

Create an identity pool to enable unauthenticated access to


your application
Before you start tracking, use Amazon Cognito to create an unauthenticated identity pool with a scoped-
down AWS Identity and Access Management (IAM) role that allows access to the Amazon Location
Trackers APIs.

72
Amazon Location Service Developer Guide
Step 2: Start tracking

Important
Ensure that the pool you create is in the same AWS Region as the place index resources that
you're using.

The pool's ID will take the form <region>:<GUID>. For example:

us-east-1:54f2ba88-9390-498d-aaa5-0d97fb7ca3bd

The following is an example of a scoped-down IAM policy allowing access to a tracker resource named
ExampleTracker to update device positions.

{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "UpdateDevicePosition",
"Effect": "Allow",
"Action": [
"geo:BatchUpdateDevicePosition"
],
"Resource": "arn:aws:geo:region:accountID:tracker/ExampleTracker"
}
]
}

Update your tracker with a device position


After you've created a tracker, you can post device position updates to your tracker. You can later retrieve
the device position or the device position history.

Use any of these methods to send device updates:

• Integrate the tracking SDK in your Android and iOS application.


• Send MQTT updates to an AWS IoT Core resource and link it to your tracker resource.
• Send location updates using the Amazon Location Trackers API, by using the AWS CLI, or the Amazon
Location APIs.

API

To send a position update using the Amazon Location APIs

Use the BatchUpdateDevicePosition action from the Amazon Location Trackers APIs.

The following example uses an API request to post a device position update for ExampleDevice to
a tracker ExampleTracker.

POST /tracking/v0/trackers/ExampleTracker/positions
Content-type: application/json
{
"Updates": [
{
"DeviceId": "ExampleDevice",
"Position": [-123.17805, 49.19284],
"SampleTime": "2020-10-02T19:09:07.327Z"
}
]
}

73
Amazon Location Service Developer Guide
Step 2: Start tracking

AWS CLI

To send a position update using AWS CLI commands

Use the BatchUpdateDevicePosition command.

The following example uses an AWS CLI to post a device position update for ExampleDevice-1 and
ExampleDevice-2 to a tracker ExampleTracker.

aws location \
batch-update-device-position \
--tracker-name ExampleTracker \
--updates \

"DeviceId=ExampleDevice-1,Position=-123.123,47.123,SampleTime=2020-11-10T12:45:34.123Z"
\

"DeviceId=ExampleDevice-2,Position=-123.123,47.123,SampleTime=2020-11-10T12:45:34.123Z"

Get a device's location history from a tracker


Your Amazon Location tracker resource maintains the location history of all your tracked devices for a
period of one year. You can retrieve device location history from a tracker. The following examples use
the AWS CLI, or the Amazon Location APIs.

API

To get the device location history from a tracker using the Amazon Location APIs

Use the GetDevicePositionHistory action from the Amazon Location Trackers APIs.

The following example uses an API URI request to get the device location history of
ExampleDevice from a tracker called ExampleTracker starting from 19:05:07 (inclusive) and
ends at 19:20:07 (exclusive) on 2020-10-02.

POST /tracking/v0/trackers/ExampleTracker/devices/ExampleDevice/list-positions
Content-type: application/json
{
"StartTimeInclusive": "2020-10-02T19:05:07.327Z",
"EndTimeExclusive": "2020-10-02T19:20:07.327Z"
}

AWS CLI

To get the device location history from a tracker using AWS CLI commands

Use the get-device-position-history command.

The following example uses an AWS CLI to get the device location history of ExampleDevice
from a tracker called ExampleTracker starting from 19:05:07 (inclusive) and ends at 19:20:07
(exclusive) on 2020-10-02.

aws location \
get-device-position-history \
--device-id "ExampleDevice" \
--start-time-inclusive "2020-10-02T19:05:07.327Z" \
--end-time-exclusive "2020-10-02T19:20:07.327Z" \

74
Amazon Location Service Developer Guide
Step 3: Link a tracker to a geofence collection

--tracker-name "ExampleTracker"

Link a tracker to a geofence collection


Now that you have a geofence collection and a tracker, you can link them together so that location
updates are automatically evaluated against all of your geofences. If you don’t want to evaluate all
location updates, or alternatively, if you are not storing some of your locations in a tracker resource, you
can evaluate device positions against geofences on demand.

When device positions are evaluated against geofences, events are generated. You can set an action to
these events. For more information about actions that you can set for geofence events, see Reacting to
Amazon Location Service events with Amazon EventBridge.

The following examples link a tracker resource to a geofence collection using the console, the AWS CLI,
or the Amazon Location APIs.

Console

To link a tracker resource to a geofence collection using the Amazon Location console

1. Open the Amazon Location console at https://console.aws.amazon.com/location/.


2. In the left navigation pane, choose Trackers.
3. Under Device trackers, select the name link of the target tracker.
4. Under Linked Geofence Collections, choose Link Geofence Collection.
5. In the Linked Geofence Collection window, select a geofence collection from the dropdown
menu.
6. Choose Link.

After you link the tracker resource, it will be assigned an Active status.
API

To link a tracker resource to a geofence collection using the Amazon Location APIs

Use the AsssociateTrackerConsumer action from the Amazon Location Trackers APIs.

The following example uses an API request that associates ExampleTracker with a geofence
collection using its Amazon Resource Name (ARN).

POST /tracking/v0/trackers/ExampleTracker/consumers
Content-type: application/json

{
"ConsumerArn": "arn:aws:geo:us-west-2:123456789012:geofence-
collection/ExampleGeofenceCollection"
}

AWS CLI

To link a tracker resource to a geofence collection using AWS CLI commands

Use the associate-tracker-consumer command.

The following example uses an AWS CLI to create a geofence collection called
ExampleGeofenceCollection.

75
Amazon Location Service Developer Guide
Step 4: Evaluate device positions against geofences

aws location \
associate-tracker-consumer \
--consumer-arn "arn:aws:geo:us-west-2:123456789012:geofence-
collection/ExampleGeofenceCollection" \
--tracker-name "ExampleTracker"

Evaluate device positions against geofences


There are two ways to evaluate positions against geofences to generate geofence events:

• You can link Trackers and Geofence Collections. For more information, see the section: the section
called “Step 3: Link a tracker to a geofence collection” (p. 75).
• You can make a direct request to the geofence collection resource to evaluate one or more positions.

If you also want to track your device location history or display locations on a map, link the tracker with a
geofence collection. Alternatively, you may not want to evaluate all location updates, or you don't intend
to store location data in a tracker resource If either of these is the case, you can make a direct request to
the geofence collection and evaluate one or more device positions against its geofences.

Evaluating device positions against geofences generates events. You can react to these events and
route them to other AWS services. For more information about actions that you can take when receiving
geofence events, see Reacting to Amazon Location Service events with Amazon EventBridge.

The following examples use the AWS CLI, or the Amazon Location APIs.

API

To evaluate device positions against the position of geofences using the Amazon Location APIs

Use the BatchEvaluateGeofences action from the Amazon Location Geofences APIs.

The following example uses an API request to evaluate the position of device ExampleDevice to an
associated geofence collection ExampleGeofenceCollection.

POST /geofencing/v0/collections/ExampleGeofenceCollection/positions HTTP/1.1


Content-type: application/json

{
"DevicePositionUpdates": [
{
"DeviceId": "ExampleDevice",
"Position": [-123.17805, 49.19284],
"SampleTime": "2020-10-02T19:09:07.327Z"
}
]
}

AWS CLI

To evaluate device positions against the position of geofences using AWS CLI commands

Use the batch-evaluate-geofences command.

The following example uses an AWS CLI to evaluate the position of ExampleDevice-1 and
ExampleDevice-2 against an associated geofence collection ExampleGeofenceCollection.

aws location \

76
Amazon Location Service Developer Guide
Reacting to geofence events with EventBridge

batch-evaluate-geofences \
--collection-name ExampleGeofenceCollection \
--device-position-updates
"DeviceId=ExampleDevice-1,Position=-123.123,47.123,SampleTime=2020-11-10T12:45:34.123Z"
"DeviceId=ExampleDevice-2,Position=-123.123,47.123,SampleTime=2020-11-10T12:45:34.123Z"

Reacting to Amazon Location Service events with


Amazon EventBridge
Amazon EventBridge is a serverless event bus that efficiently connects applications together using data
from AWS services like Amazon Location. EventBridge receives geofence events from Amazon Location
and routes that data to targets like AWS Lambda. You can set up routing rules to determine where to
send your data to build application architectures that react in real time.

For more information, see the Events and Event Patterns in the Amazon EventBridge User Guide.

Topics
• Create event rules for Amazon Location (p. 77)
• Amazon EventBridge event examples for Amazon Location Service (p. 78)

Create event rules for Amazon Location


You can create rules in EventBridge to configure actions taken in response to an Amazon Location event.

For example, you can create a rule for geofence events where a push notification will be sent when a
phone is detected within a geofenced boundary.

To create a rule for Amazon Location events

1. Log in to AWS using an account that has permissions to use EventBridge and Amazon Location
Service.
2. Open the Amazon EventBridge console at https://console.aws.amazon.com/events/.
3. Choose Create rule.
4. Enter a Name for the rule, and, optionally, a description.
5. Under Define pattern, choose Event pattern.
6. Under Event matching pattern, choose Custom pattern.
7. In the Event pattern box, add the following pattern that filters events by detail-type, which will
be Location Geofence Event, then choose Save.

{
"source": [
"aws.geo"
],
"detail-type": [
"Location Geofence Event"
]
}

You can also filter events associated with specific trackers or geofence collections by matching on
the event’s detail, where the geofence EventType can be ENTER or EXIT. For example:

77
Amazon Location Service Developer Guide
Event examples

{
"source": [
"aws.geo"
],
"detail-type": [
"Location Geofence Event"
],
"detail": {
"EventType": "ENTER"
}
}

8. In the Select event bus section, choose AWS default event bus, and confirm that Enable the rule
on the selected event bus is toggled on.
9. Under Select targets, choose the target action to take when a geofence event is received from
Amazon Location Service.

For example, use an Amazon Simple Notification Service (SNS) topic to send an email or text
message when an event occurs. You first need to create an Amazon SNS topic using the Amazon SNS
console. For more information, see Using Amazon SNS for user notifications.
10. Optionally, choose Add target to specify an additional target action for the event rule.
11. Choose Create.

Warning
It's best practice to confirm that the event rule was successfully applied or your automated
action may not trigger as expected. To verify your event rule, initiate conditions for the event
rule. For example, simulate a device entering a geofenced area.

You can also capture all events from Amazon Location, by just excluding the detail-type section. For
example:

{
"source": [
"aws.geo"
]
}

Amazon EventBridge event examples for Amazon


Location Service
The following is an example of an event for entering a geofence triggered by calling
BatchUpdateDevicePosition.

{
"version": "0",
"id": "aa11aa22-33a-4a4a-aaa5-example",
"detail-type": "Location Geofence Event",
"source": "aws.geo",
"account": "636103698109",
"time": "2020-11-10T23:43:37Z",
"region": "eu-west-1",
"resources": [
"arn:aws:geo:eu-west-1:0123456789101:geofence-collection/GeofenceEvents-
GeofenceCollection_EXAMPLE",
"arn:aws:geo:eu-west-1:0123456789101:tracker/Tracker_EXAMPLE"
],

78
Amazon Location Service Developer Guide
Monitoring with CloudWatch

"detail": {
"EventType": "ENTER",
"GeofenceId": "polygon_14",
"DeviceId": "Device1-EXAMPLE",
"SampleTime": "2020-11-10T23:43:37.531Z",
"Position": [
-123.12390073297821,
49.23433613216247
]
}
}

The following is an example of an event for exiting a geofence triggered by calling


BatchUpdateDevicePosition.

{
"version": "0",
"id": "aa11aa22-33a-4a4a-aaa5-example",
"detail-type": "Location Geofence Event",
"source": "aws.geo",
"account": "123456789012",
"time": "2020-11-10T23:41:44Z",
"region": "eu-west-1",
"resources": [
"arn:aws:geo:eu-west-1:0123456789101:geofence-collection/GeofenceEvents-
GeofenceCollection_EXAMPLE",
"arn:aws:geo:eu-west-1:0123456789101:tracker/Tracker_EXAMPLE"
],
"detail": {
"EventType": "EXIT",
"GeofenceId": "polygon_10",
"DeviceId": "Device1-EXAMPLE",
"SampleTime": "2020-11-10T23:41:43.826Z",
"Position": [
-123.08569321875426,
49.23766166742559
]
}
}

Monitoring Amazon Location Service with Amazon


CloudWatch
Amazon CloudWatch monitors your AWS resources and the applications that you run on AWS in real
time. You can monitor Amazon Location resources using CloudWatch, which collects raw data and
processes metrics into meaningful statistics in near-real time. You can view historical information for up
to 15 months, or search metrics to view in the Amazon CloudWatch console for more perspective about
your Amazon Location resources. You can also set alarms by defining thresholds, and send notifications
or take actions when those thresholds are met.

For more information, see the Amazon CloudWatch User Guide

Topics
• Amazon Location Service metrics exported to Amazon CloudWatch (p. 80)
• View Amazon Location Service metrics (p. 80)
• Create CloudWatch alarms for Amazon Location Service metrics (p. 81)
• CloudWatch metric examples for Amazon Location Service (p. 82)

79
Amazon Location Service Developer Guide
Metrics

Amazon Location Service metrics exported to


Amazon CloudWatch
Metrics are time-ordered data points that are exported to CloudWatch. A dimension is a name/value
pair that identifies the metric. For more information, see Using CloudWatch metrics and CloudWatch
dimensions in the Amazon CloudWatch User Guide.

The following are metrics that Amazon Location Service exports to CloudWatch in the AWS/Location
namespace.

Metric Description

CallCount The number of calls made to a given API endpoint.

Valid Dimensions: Amazon Location Service API names

Valid Statistic: Sum

Units: Count

ErrorCount The number of error responses from calls made to a given API endpoint.

Valid Dimensions: Amazon Location Service API names

Valid Statistic: Sum

Units: Count

SuccessCount The number of successful calls made to a given API endpoint.

Valid Dimensions: Amazon Location Service API names

Valid Statistic: Sum

Units: Count

CallLatency The amount of time the operation takes to process and return a response
when a call is made to a given API endpoint.

Valid Dimensions: Amazon Location Service API names

Valid Statistic: Sum

Units: Milliseconds

View Amazon Location Service metrics


You can view metrics for Amazon Location Service on the Amazon CloudWatch console or by using the
Amazon CloudWatch API.

To view metrics using the CloudWatch console

Example

1. Open the CloudWatch console at https://console.aws.amazon.com/cloudwatch/.


2. In the navigation pane, choose Metrics.

80
Amazon Location Service Developer Guide
Create CloudWatch alarms

3. On the All metrics tab, choose the Amazon Location namespace.


4. Select the type of metric to view.
5. Select the metric and add it to the chart.

For more information, see View Available Metrics in the Amazon CloudWatch User Guide.

Create CloudWatch alarms for Amazon Location


Service metrics
You can use CloudWatch to set alarms on your Amazon Location Service metrics. For example, you can
create an alarm in CloudWatch to send an email any time a spike in error count occurs.

The following topics give you a high-level overview of how to set alarms using CloudWatch. For detailed
instructions, see Using Alarms in the Amazon CloudWatch User Guide.

To set alarms using the CloudWatch console

Example

1. Open the CloudWatch console at https://console.aws.amazon.com/cloudwatch/.


2. In the navigation pane, choose Alarm.
3. Choose Create Alarm.
4. Choose Select metric.
5. On the All metrics tab, select the Amazon Location namespace.
6. Select a metric category.
7. Find the row with the metric you want to create an alarm for, then select the check box next to this
row.
8. Choose Select metric.
9. Under Metric, fill in the values .
10.Specify the alarm Conditions .
11.Choose Next.
12.If you want to send a notification when the alarm conditions are met:
• Under Alarm state trigger, select the alarm state to prompt a notification to be sent.
• Under Select an SNS topic, choose Create new topic. Enter the topic name and the email to send
the notification to.
• Under Send a notification to enter additional email addresses to send the notification to.
• Choose Add notification. This list is saved and appears in the field for future alarms.
13.When done, choose Next.
14.Enter a name and description for the alarm, then choose Next.
15.Confirm the alarm details, then choose Next.

Note
When creating a new Amazon SNS topic, you must verify the email address before a notification
can be sent. If the email is not verified, the notification will not be received when an alarm is
initiated by a state change.

For more information about how to set alarms using the CloudWatch console, see Create an Alarm that
Sends Email in the Amazon CloudWatch User Guide.

81
Amazon Location Service Developer Guide
Metric output examples

CloudWatch metric examples for Amazon Location


Service
You can use the GetMetricData API to retrieve metrics for Amazon Location.

• For example, you can monitor CallCount and set an alarm for when a drop in number occurs.

Monitoring the CallCount metrics for SendDeviceLocation can help give you perspective on
tracked assets. If the CallCount drops, it means that tracked assets, such as a fleet of trucks, have
stopped sending their current locations. Setting an alarm for this can help notify you an issue has
occurred.
• For another example, you can monitor ErrorCount and set an alarm for when a spike in number
occurs.

Trackers need to be associated with geofence collections in order for device locations to be evaluated
against geofences. If you have a device fleet that requires continuous location updates, seeing the
CallCount for BatchEvaluateGeofence or BatchPutDevicePosition drop to zero indicates
that updates are no longer flowing.

The following is an example output for GetMetricData with the metrics for CallCount and ErrorCount
for creating map resources.

{
"StartTime": 1518867432,
"EndTime": 1518868032,
"MetricDataQueries": [
{
"Id": "m1",
"MetricStat": {
"Metric": {
"Namespace": "AWS/Location",
"MetricName": "CallCount",
"Dimensions": [
{
"Name": "SendDeviceLocation",
"Value": "100"
}
]
},
"Period": 300,
"Stat": "SampleCount",
"Unit": "Count"
}
},
{
"Id": "m2",
"MetricStat": {
"Metric": {
"Namespace": "AWS/Location",
"MetricName": "ErrorCount",
"Dimensions": [
{
"Name": "AssociateTrackerConsumer",
"Value": "0"
}
]
},
"Period": 1,
"Stat": "SampleCount",
"Unit": "Count"

82
Amazon Location Service Developer Guide
Using CloudTrail with Amazon Location

}
}
]
}

Logging and monitoring with AWS CloudTrail


AWS CloudTrail is a service that provides a record of actions taken by a user, role, or an AWS service.
CloudTrail records all API calls as events. You can use Amazon Location Service with CloudTrail to
monitor your API calls, which includes calls from the Amazon Location Service console and AWS SDK
calls to the Amazon Location Service API operations.

When you create a trail, you can enable continuous delivery of CloudTrail events to an Amazon S3
bucket, including events for Amazon Location Service. If you don't configure a trail, you can still view
the most recent events in the CloudTrail console in Event history. Using the information collected by
CloudTrail, you can determine the request that was made to Amazon Location Service, the IP address
from which the request was made, who made the request, when it was made, and additional details.

For more information about CloudTrail, see the AWS CloudTrail User Guide.

Topics
• Amazon Location Service Information in CloudTrail (p. 83)
• Understanding Amazon Location Service Log File Entries (p. 84)

Amazon Location Service Information in CloudTrail


CloudTrail is enabled on your AWS account when you create the account. When activity occurs in Amazon
Location Service, that activity is recorded in a CloudTrail event along with other AWS service events
in Event history. You can view, search, and download recent events in your AWS account. For more
information, see Viewing Events with CloudTrail Event History.

For an ongoing record of events in your AWS account, including events for Amazon Location Service,
create a trail. A trail enables CloudTrail to deliver log files to an Amazon S3 bucket. By default, when you
create a trail in the console, the trail applies to all AWS Regions. The trail logs events from all Regions in
the AWS partition and delivers the log files to the Amazon S3 bucket that you specify. Additionally, you
can configure other AWS services to further analyze and act upon the event data collected in CloudTrail
logs.

For more information, see the following:

• Overview for Creating a Trail


• CloudTrail Supported Services and Integrations
• Configuring Amazon SNS Notifications for CloudTrail
• Receiving CloudTrail Log Files from Multiple Regions and Receiving CloudTrail Log Files from Multiple
Accounts

All Amazon Location Service actions are logged by CloudTrail and are documented in the Amazon
Location Service API references. For example, calls to the CreateTracker, UpdateTracker and
DescribeTracker actions generate entries in the CloudTrail log files.

Every event or log entry contains information about who generated the request. The identity
information helps you determine whether the request was made:

• With root or AWS Identity and Access Management (IAM) user credentials.

83
Amazon Location Service Developer Guide
Understanding Amazon Location Service Log File Entries

• With temporary security credentials for a role or federated user.


• By another AWS service.

For more information, see the CloudTrail userIdentity Element.

Understanding Amazon Location Service Log File


Entries
A trail is a configuration that enables delivery of events as log files to an Amazon S3 bucket that you
specify, or to Amazon CloudWatch Logs. For more information, see Working with CloudTrail log files in
the AWS CloudTrail User Guide.

CloudTrail log files contain one or more log entries. An event represents a single request from any
source and includes information about the requested action, the date and time of the action, request
parameters, and so on.
Note
CloudTrail log files aren't an ordered stack trace of the public API calls, so they don't appear in
any specific order. To determine the order of operations, use eventTime.

The following example shows a CloudTrail log entry that demonstrates the CreateTracker action,
which creates a tracker resource.

{
"eventVersion": "1.05",
"userIdentity": {
"type": "AssumedRole",
"principalId": "123456789012",
"arn": "arn:aws:geo:us-east-1:123456789012:tracker/ExampleTracker"
"accountId": "123456789012",
"accessKeyId": "123456789012",
"sessionContext": {
"sessionIssuer": {
"type": "Role",
"principalId": "123456789012",
"arn": "arn:aws:geo:us-east-1:123456789012:tracker/ExampleTracker",
"accountId": "123456789012",
"userName": "exampleUser",
},
"webIdFederationData": {},
"attributes": {
"mfaAuthenticated": "false",
"creationDate": "2020-10-22T16:36:07Z"
}
}
},
"eventTime": "2020-10-22T17:43:30Z",
"eventSource": "geo.amazonaws.com",
"eventName": "CreateTracker",
"awsRegion": "us-east-1",
"sourceIPAddress": "192.0.2.0/24—TEST-NET-1",
"userAgent": "aws-internal/3 aws-sdk-java/1.11.864 Linux/4.14.193-110.317.amzn2.x86_64
OpenJDK_64-Bit_Server_VM/11.0.8+10-LTS java/11.0.8 kotlin/1.3.72 vendor/Amazon.com_Inc.
exec-env/AWS_Lambda_java11",
"requestParameters": {
"TrackerName": "ExampleTracker",
"Description": "Resource description"
},
"responseElements": {
"TrackerName": "ExampleTracker",

84
Amazon Location Service Developer Guide
Understanding Amazon Location Service Log File Entries

"Description": "Resource description"


"TrackerArn": "arn:partition:service:region:account-id:resource-id",
"CreateTime": "2020-10-22T17:43:30.521Z"
},
"requestID": "557ec619-0674-429d-8e2c-eba0d3f34413",
"eventID": "3192bc9c-3d3d-4976-bbef-ac590fa34f2c",
"readOnly": false,
"eventType": "AwsApiCall",
"recipientAccountId": "123456789012",
}

The following shows a log entry for the UpdateTracker action, which updates a tracker resource's
description.

{
"eventVersion": "1.05",
"userIdentity": {
"type": "AssumedRole",
"principalId": "123456789012",
"arn": "arn:partition:service:region:account-id:resource-id",
"accountId": "123456789012",
"accessKeyId": "123456789012",
"sessionContext": {
"sessionIssuer": {
"type": "Role",
"principalId": "123456789012",
"arn": "arn:partition:service:region:account-id:resource-id",
"accountId": "123456789012",
"userName": "exampleUser",
},
"webIdFederationData": {},
"attributes": {
"mfaAuthenticated": "false",
"creationDate": "2020-10-22T16:36:07Z"
}
}
},
"eventTime": "2020-10-22T17:43:37Z",
"eventSource": "geo.amazonaws.com",
"eventName": "UpdateTracker",
"awsRegion": "us-east-1",
"sourceIPAddress": "192.0.2.0/24—TEST-NET-1",
"userAgent": "aws-internal/3 aws-sdk-java/1.11.864 Linux/4.14.193-110.317.amzn2.x86_64
OpenJDK_64-Bit_Server_VM/11.0.8+10-LTS java/11.0.8 kotlin/1.3.72 vendor/Amazon.com_Inc.
exec-env/AWS_Lambda_java11",
"requestParameters": {
"TrackerName": "ExampleTracker",
"Description": "Resource description Updated"
},
"responseElements": {
"UpdateTime": "2020-10-22T17:43:37.226Z",
"TrackerName": "ExampleTracker",
"Description": "Resource description Updated",
"CreateTime": "2020-10-22T17:43:37.187Z"
},
"requestID": "27a0aeac-c050-471f-a6a5-c8e3381f8bdc",
"eventID": "4a6a56c0-e82c-467e-b11e-7e0e2e1dca35",
"readOnly": false,
"eventType": "AwsApiCall",
"recipientAccountId": "123456789012",
}

The following shows a log entry for the DescribeTracker action, which returns the details of a tracker
resource.

85
Amazon Location Service Developer Guide
Tracking using MQTT

{
"eventVersion": "1.05",
"userIdentity": {
"type": "AssumedRole",
"principalId": "123456789012",
"arn": "arn:partition:service:region:account-id:resource-id",
"accountId": "123456789012",
"accessKeyId": "123456789012",
"sessionContext": {
"sessionIssuer": {
"type": "Role",
"principalId": "123456789012",
"arn": "arn:partition:service:region:account-id:resource-id",
"accountId": "123456789012",
"userName": "exampleUser",
},
"webIdFederationData": {},
"attributes": {
"mfaAuthenticated": "false",
"creationDate": "2020-10-22T16:36:07Z"
}
}
},
"eventTime": "2020-10-22T17:43:33Z",
"eventSource": "geo.amazonaws.com",
"eventName": "DescribeTracker",
"awsRegion": "us-east-1",
"sourceIPAddress": "192.0.2.0/24—TEST-NET-1",
"userAgent": "aws-internal/3 aws-sdk-java/1.11.864 Linux/4.14.193-110.317.amzn2.x86_64
OpenJDK_64-Bit_Server_VM/11.0.8+10-LTS java/11.0.8 kotlin/1.3.72 vendor/Amazon.com_Inc.
exec-env/AWS_Lambda_java11",
"requestParameters": {
"TrackerName": "ExampleTracker"
},
"responseElements": null,
"requestID": "997d5f93-cfef-429a-bbed-daab417ceab4",
"eventID": "d9e0eebe-173c-477d-b0c9-d1d8292da103",
"readOnly": true,
"eventType": "AwsApiCall",
"recipientAccountId": "123456789012",
}

Tracking using MQTT with Amazon Location


Service
MQTT is a lightweight and widely adopted messaging protocol designed for constrained devices. AWS
IoT Core supports device connections that use the MQTT protocol and MQTT over WebSocket Secure
(WSS) protocol.

AWS IoT Core connects devices to AWS and enables you to send and receive messages between them.
The AWS IoT Core rules engine stores queries about your devices' message topics and enables you to
define actions for sending messages to other AWS services, such as Amazon Location Service. Devices
that are aware of their location as coordinates can have their locations forwarded to Amazon Location
through the rules engine. For more information about this pattern, see the reference architecture.

Topics
• Prerequisite (p. 87)
• Create a Lambda function (p. 87)

86
Amazon Location Service Developer Guide
Prerequisite

• Create an AWS IoT Core rule (p. 89)


• Test your AWS IoT Core rule in the console (p. 90)

Prerequisite
Before you can begin tracking, you must create a tracker resource (p. 71). To create a tracker resource,
you can use the Amazon Location console, the AWS CLI, or the Amazon Location APIs.

The following example uses the Amazon Location console to create the tracker resource:

1. Open the Amazon Location console at https://console.aws.amazon.com/location/.


2. In the left navigation pane, choose Trackers.
3. Choose Create tracker.
4. Fill out the following boxes:

• Name – Enter a unique name that has a maximum of 100 characters. Valid entries include
alphanumeric characters, hyphens, and underscores. For example, MyTracker.
• Description – Enter an optional description. For example, Tracker for storing AWS IoT
Core device positions.
5. Choose Create tracker.

Create a Lambda function


To create a connection between AWS IoT Core and Amazon Location Service, you need an AWS Lambda
function to process messages forwarded by AWS IoT Core. This function will extract any positional data,
format it for Amazon Location Service, and submit it through the Amazon Location Tracker API. You can
create this function through the AWS Lambda console, or you can use the AWS Command Line Interface
(AWS CLI) or the AWS Lambda APIs.

To create a Lambda function that publishes position updates to Amazon Location using the console:

1. Open the AWS Lambda console at https://console.aws.amazon.com/lambda/.


2. From the left navigation, choose Functions.
3. Choose Create Function, and make sure that Author from scratch is selected.
4. Fill out the following boxes:

• Function name – Enter a unique name for your function. Valid entries include alphanumeric
characters, hyphens, and underscores with no spaces. For example, MyLambda.
• Runtime – Choose Python 3.8.
5. Choose Create function.
6. Choose the latest alias.
7. Choose the Code tab to open the editor.
8. Overwrite the placeholder code in lambda_function.py with the following, replacing
the value assigned to TRACKER_NAME with the name of the tracker that you created as a
prerequisite (p. ).

from datetime import datetime


import json
import os

import boto3

# Update this to match the name of your Tracker resource

87
Amazon Location Service Developer Guide
Create a Lambda function

TRACKER_NAME = "MyTracker"

"""
This Lambda function receives a payload from AWS IoT Core and publishes device updates
to Amazon Location Service via the BatchUpdateDevicePosition API.

Parameter 'event' is the payload delivered from AWS IoT Core.

In this sample, we assume that the payload has a single top-level key 'payload' and a
nested key
'location' with keys 'lat' and 'long'. We also assume that the name of the device is
nested in
the payload as 'deviceid'. Finally, the timestamp of the payload is present as
'timestamp'. For
example:

>>> event
{ 'payload': { 'deviceid': 'thing123', 'timestamp': 1604940328,
'location': { 'lat': 49.2819, 'long': -123.1187 } } }

If your data does not match this schema, you can either use the AWS IoT Core rules
engine to
format the data before delivering it to this Lambda function, or you can modify the
code below to
match it.
"""
def lambda_handler(event, context):
# load the side-loaded Amazon Location Service model; needed during Public Preview
os.environ["AWS_DATA_PATH"] = os.environ["LAMBDA_TASK_ROOT"]

updates = [
{
"DeviceId": event["payload"]["deviceid"],
"SampleTime": datetime.fromtimestamp(event["payload"]["timestamp"]).isoformat(),
"Position": [
event["payload"]["location"]["long"],
event["payload"]["location"]["lat"]
]
}
]

client = boto3.client("location")
response = client.batch_update_device_position(TrackerName=TRACKER_NAME,
Updates=updates)

return {
"statusCode": 200,
"body": json.dumps(response)
}

Note
Because Lambda runtimes don't include the latest boto3 and botocore releases, you must
provide the service model for Amazon Location. While you can use the following steps to do
so, we recommend that you package all of your dependencies explicitly, even those known
to be included in the runtime.
9. In the Environment panel, create a new folder named location/2020-11-19.
10. Create a new file in location/2020-11-19 named service-2.json containing the contents of
service-2.json.
11. Choose Deploy as latest to save the updated function.
12. Choose the Latest configuration tab.
13. In the Permissions section, choose the hyperlinked Role name to grant Amazon Location Service
permissions to your Lambda function.

88
Amazon Location Service Developer Guide
Create an AWS IoT Core rule

14. From your role's Summary page, choose Add inline policy.
15. Choose the JSON tab, and overwrite the policy with the following document. This allows your
Lambda function to update device positions managed by all tracker resources across all Regions.

{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "WriteDevicePosition",
"Effect": "Allow",
"Action": "geo:BatchUpdateDevicePosition",
"Resource": "arn:aws:geo:*:*:tracker/*"
}
]
}

16. Choose Review policy.


17. Enter a policy name. For example, AmazonLocationTrackerWriteOnly.
18. Choose Create policy.

You can modify this function code, as necessary, to adapt to your own device message schema.

Create an AWS IoT Core rule


Next, create an AWS IoT Core rule to forward your devices' positional telemetry to the AWS Lambda
function for transformation and publication to Amazon Location Service. The example rule provided
assumes that any necessary transformation of device payloads is handled by your Lambda function. You
can create this rule through the AWS IoT Core console, the AWS Command Line Interface (AWS CLI), or
the AWS IoT Core APIs.
Note
While the AWS IoT console handles the permission necessary to allow AWS IoT Core to invoke
your Lambda function, if you are creating your rule from the AWS CLI or SDK, you must
configure a policy to grant permission to AWS IoT.

To create an AWS IoT Core using the console

1. Sign in to the AWS IoT Core console at https://console.aws.amazon.com/iot/.


2. In the left navigation, expand Act, and choose Rules.
3. Choose Create a rule to start the new rule wizard.
4. Enter a name and description for your rule.
5. For the Rule query statement, update the FROM attribute to refer to a topic where at least one
device is publishing telemetry that includes location. If you are testing the solution, no modification
is needed.

SELECT * FROM 'iot/topic'

6. Under Set one or more actions , choose Add action.


7. Select Send a message to a lambda function.
8. Choose Configure action.
9. Find and select your Lambda function from the list.
10. Choose Add action.
11. Choose Create rule.

89
Amazon Location Service Developer Guide
Optional: Test your AWS IoT Core rule

Test your AWS IoT Core rule in the console


If no devices are currently publishing telemetry that includes location, you can test your rule and this
solution using the AWS IoT Core console. The console has a test client where you can publish a sample
message to verify the results of the solution.

1. Sign in to the AWS IoT Core console at https://console.aws.amazon.com/iot/.


2. In the left navigation, expand Act, and choose Test.
3. Under Publish, where the FROM attribute is by default iot/topic, provide the following in the text
area.

{
"payload": {
"deviceid": "thing123",
"timestamp": 1604940328,
"location": { "lat": 49.2819, "long": -123.1187 }
}
}

4. Choose Publish to topic to send the test message.


5. To validate that the message was received by Amazon Location Service, use the following AWS CLI
command.

aws location batch-get-device-position --tracker-name MyTracker --device-ids thing123

Managing resources
This topic guides you through how to manage your Amazon Location Service resources.

Topics
• Managing your map resources (p. 90)
• Managing your place index resources (p. 93)
• Managing your geofence collection resources (p. 95)
• Managing your tracker resources (p. 100)

Managing your map resources


You can manage your map resources using the Amazon Location console, the AWS CLI, or the Amazon
Location APIs.

List map resources


You can view a list of your map resources using the Amazon Location console, the AWS CLI, or the
Amazon Location APIs:

Console

To view a list of existing map resources using the Amazon Location console

1. Open the Amazon Location console at https://console.aws.amazon.com/location/.


2. Choose Maps from the left navigation pane.

90
Amazon Location Service Developer Guide
Maps

3. Under Map resources, you'll be able to view your maps.

API

Use the ListMaps action from the Amazon Location Maps APIs.

The following example is an API request to get a list of map resources in the AWS account.

POST /maps/v0/list-maps

The following is an example response for ListMap:

{
"Entries": [
{
"CreateTime": 2020-10-30T01:38:36Z,
"DataSource": "Esri",
"Description": "string",
"MapName": "ExampleMap",
"UpdateTime": 2020-10-30T01:38:36Z
}
],
"NextToken": "1234-5678-9012"
}

CLI

Use the list-map command.

The following example is an AWS CLI to get a list of map resources in the AWS account.

aws location list-maps

Get map resource details


You can get details about any map resource in your AWS account using the Amazon Location console, the
AWS CLI, or the Amazon Location APIs:

Console

To view the details of a map resource using the Amazon Location console

1. Open the Amazon Location console at https://console.aws.amazon.com/location/.


2. Choose Maps from the left navigation pane.
3. Under Maps, select the name link of the target map resource.
4. Under Information, you can view the map resource details.

API

Use the DescribeMap action from the Amazon Location Maps APIs.

The following example is an API request to get the map resource details for ExampleMap.

GET /maps/v0/maps/ExampleMap

91
Amazon Location Service Developer Guide
Maps

The following is an example response for DescribeMap:

{
"Configuration": {
"Style": "VectorEsriNavigation"
},
"CreateTime": 2020-10-30T01:38:36Z,
"DataSource": "Esri",
"Description": "string",
"MapArn": "arn:aws:geo:us-west-2:123456789012:maps/ExampleMap",
"MapName": "ExampleMap",
"UpdateTime": 2020-10-30T01:40:36Z
}

CLI

Use the describe-map command.

The following example is an AWS CLI to get the map resource details for ExampleMap.

aws location describe-map \


--map-name "ExampleMap"

Delete a map resource


You can delete a map resource from your AWS account using the Amazon Location console, the AWS CLI,
or the Amazon Location APIs:
Warning
This action deletes the resource permanently. You can't undo this action.

Console

To delete an existing map resource using the Amazon Location console

1. Open the Amazon Location console at https://console.aws.amazon.com/location/.


2. Choose Maps from the left navigation pane.
3. From the Maps list, select the map resource button.
4. Choose Delete map.

API

Use the DeleteMap action from the Amazon Location Maps APIs.

The following example is an API request to delete the map resource ExampleMap.

DELETE /maps/v0/maps/ExampleMap

The following is an example success response for DeleteMap:

HTTP/1.1 200

CLI

Use the delete-map command.

92
Amazon Location Service Developer Guide
Place indexes

The following example is an AWS CLI command to delete the map resource ExampleMap.

aws location delete-map \


--map-name "ExampleMap"

Managing your place index resources


You can manage your place index resources using the Amazon Location console, the AWS CLI, or the
Amazon Location APIs.

List your place index resources


You can view your place index resources list using the Amazon Location console, the AWS CLI, or the
Amazon Location APIs:

Console

To view a list of place index resources using the Amazon Location console

1. Open the Amazon Location console at https://console.aws.amazon.com/location/.


2. Choose Place indexes from the left navigation pane.
3. Under the Place indexes list, you’ll be able to view your resources.

API

Use the ListPlaceIndexes action from the Amazon Location Places APIs.

The following example is an API request to get a list of place index resources in the AWS account.

POST /places/v0/list-indexes

The following is an example response for ListPlaceIndexes:

{
"Entries": [
{
"CreateTime": 2020-10-30T01:38:36Z,
"DataSource": "Esri",
"Description": "string",
"IndexName": "ExamplePlaceIndex",
"UpdateTime": 2020-10-30T01:40:36Z
}
],
"NextToken": "1234-5678-9012"
}

CLI

Use the list-place-indexes command.

The following example is an AWS CLI to get a list of place index resources in the AWS account.

aws location list-place-indexes

93
Amazon Location Service Developer Guide
Place indexes

Get place index resource details


You can get details about any place index resource in your AWS account using the Amazon Location
console, the AWS CLI, or the Amazon Location APIs:

Console

To view the details of a place index resource using the Amazon Location console

1. Open the Amazon Location console at https://console.aws.amazon.com/location/.


2. Choose Place indexes from the left navigation pane.
3. Under the Place indexes list, select the link of the target place index.
4. Under Information, you'll be able to view the place index details.

API

Use the DescribePlaceIndex action from the Amazon Location Place APIs.

The following example is an API request to get the place index resource details for
ExamplePlaceIndex.

GET /places/v0/indexes/ExamplePlaceIndex

The following is an example response for DescribePlaceIndex:

{
"CreateTime": 2020-10-30T01:38:36Z,
"DataSource": "Esri",
"DataSourceConfiguration": {
"IntendedUse": "SingleUse"
},
"Description": "string",
"IndexArn": "arn:aws:geo:us-west-2:123456789012:place-indexes/ExamplePlaceIndex",
"IndexName": "string",
"UpdateTime": 2020-10-30T01:40:36Z
}

CLI

Use the describe-place-index command.

The following example is an AWS CLI to get the place index resource details for
ExamplePlaceIndex.

aws location describe-place-index \


--index-name "ExamplePlaceIndex"

Delete a place index resource


You can delete a place index resource from your AWS account using the Amazon Location console, the
AWS CLI, or the Amazon Location APIs:

Console

To delete a place index resource using the Amazon Location console

94
Amazon Location Service Developer Guide
Geofence collections

Warning
This action deletes the resource permanently. You can't undo this action.

1. Open the Amazon Location console at https://console.aws.amazon.com/location/.


2. Choose Place indexes from the left navigation pane
3. Under the Place indexes list, select the target place index button.
4. Choose Delete place index.

API

Use the DeletePlaceIndex action from the Amazon Location Places APIs.

The following example is an API request to delete the place index resource ExamplePlaceIndex.

DELETE /places/v0/indexes/ExamplePlaceIndex

The following is an example success response for DeletePlaceIndex:

HTTP/1.1 200

CLI

Use the delete-place-index command.

The following example is an AWS CLI command to delete the place index resource
ExamplePlaceIndex.

aws location delete-place-index \


--index-name "ExamplePlaceIndex"

Managing your geofence collection resources


You can manage your geofence collections using the Amazon Location console, the AWS CLI, or the
Amazon Location APIs.

List your geofence collection resources


You can view your geofence collection list using the Amazon Location console, the AWS CLI, or the
Amazon Location APIs:

Console

To view a list of geofence collections using the Amazon Location console

1. Open the Amazon Location console at https://console.aws.amazon.com/location/.


2. Choose Geofence collections from the left navigation pane.
3. Under Geofence Collections, you'll be able to view your geofence collections.

API

Use the ListGeofenceCollections action from the Amazon Location Geofences APIs.

95
Amazon Location Service Developer Guide
Geofence collections

The following example is an API request to get a list of geofence collections in the AWS account.

POST /geofencing/v0/list-collections

The following is an example response for ListGeofenceCollections:

{
"Entries": [
{
"CollectionName": "ExampleCollection",
"CreateTime": 2020-09-30T22:59:34.142Z,
"Description": "string",
"UpdateTime": 2020-09-30T23:59:34.142Z
}
],
"NextToken": "1234-5678-9012"
}

CLI

Use the list-geofence-collections command.

The following example is an AWS CLI to get a list of geofence collections in the AWS account.

aws location list-geofence-collections

Get geofence collection details


You can get details about any geofence collection resource in your AWS account using the Amazon
Location console, the AWS CLI, or the Amazon Location APIs:

Console

To view the details of a geofence collection using the Amazon Location console

1. Open the Amazon Location console at https://console.aws.amazon.com/location/.


2. Choose Geofence collections from the left navigation pane.
3. From the Geofence collections list, select the name link for the target geofence collection.
4. Under Information, you'll be able to view the geofence collection details.

API

Use the DescribeGeofenceCollection action from the Amazon Location Geofences APIs.

The following example is an API request to get the geofence collection details for
ExampleCollection.

GET /geofencing/v0/collections/ExampleCollection

The following is an example response for DescribeGeofenceCollection:

{
"CollectionArn": "arn:aws:geo:us-west-2:123456789012:geofence-collection/
GeofenceCollection",

96
Amazon Location Service Developer Guide
Geofence collections

"CollectionName": "ExampleCollection",
"CreateTime": 2020-09-30T22:59:34.142Z,
"Description": "string",
"UpdateTime": 2020-09-30T23:59:34.142Z"
}

CLI

Use the describe-geofence-collection command.

The following example is an AWS CLI to get the geofence collection details for
ExampleCollection.

aws location describe-geofence-collection \


--collection-name "ExampleCollection"

Delete a geofence collection


You can delete a geofence collection from your AWS account using the Amazon Location console, the
AWS CLI, or the Amazon Location APIs:

Console

To delete a geofence collection using the Amazon Location console


Warning
This action deletes the resource permanently. You can't undo this action.

1. Open the Amazon Location console at https://console.aws.amazon.com/location/.


2. Choose Geofence collections from the left navigation pane.
3. From the Geofence collections list, select the geofence collection button.
4. Choose Delete geofence collection.

API

Use the DeleteGeofenceCollection action from the Amazon Location Geofences APIs.

The following example is an API request to delete the geofence collection ExampleCollection.

DELETE /geofencing/v0/collections/ExampleCollection

The following is an example response for DeleteGeofenceCollection:

HTTP/1.1 200

CLI

Use the delete-geofence-collection command.

The following example is an AWS CLI command to delete the geofence collection
ExampleCollection.

aws location delete-geofence-collection \

97
Amazon Location Service Developer Guide
Geofence collections

--collection-name "ExampleCollection"

List stored geofences


You can list geofences stored in a specified geofence collection using the Amazon Location console, the
AWS CLI, or the Amazon Location APIs:

Console

To view a list of geofences using the Amazon Location console

1. Open the Amazon Location console at https://console.aws.amazon.com/location/.


2. Choose Geofence collections from the left navigation pane.
3. From the Geofence collections list, select the name link for the target geofence collection.
4. Under Geofences, you’ll be able to view geofences in the geofence collection.

API

Use the ListGeofences action from the Amazon Location Geofences APIs.

The following example is an API request to get a list of geofences stored in the geofence collection
ExampleCollection.

POST /geofencing/v0/collections/ExampleCollection/list-geofences

The following is an example response for ListGeofences:

{
"Entries": [
{
"CreateTime": 2020-09-30T22:59:34.142Z,
"GeofenceId": "geofence-1",
"Geometry": {
"Polygon": [
[-5.716667, -15.933333,
[-14.416667, -7.933333],,
[-12.316667, -37.066667],,
[-5.716667, -15.933333]
]
},
"Status": "ACTIVE",
"UpdateTime": 2020-09-30T23:59:34.142Z
}
],
"NextToken": "1234-5678-9012"
}

CLI

Use the list-geofences command.

The following example is an AWS CLI to get a list of geofences stored in the geofence collection
ExampleCollection.

aws location list-geofences \


--collection-name "ExampleCollection"

98
Amazon Location Service Developer Guide
Geofence collections

Get geofence details


You can get the details of a specific geofence, such as the create time, update time, geometry and status,
from a geofence collection using the Amazon Location console, AWS CLI, or the Amazon Location APIs:

Console

To view the status of a geofence using the Amazon Location console

1. Open the Amazon Location console at https://console.aws.amazon.com/location/.


2. Choose Geofence collections from the left navigation pane.
3. From the Geofence collections list, select the name link for the target geofence collection.
4. Under Geofences, you’ll be able to view the status of your geofences.

API

Use the GetGeofence action from the Amazon Location Geofences APIs.

The following example is an API request to get the geofence details from a geofence collection
ExampleCollection.

GET /geofencing/v0/collections/ExampleCollection/geofences/ExampleGeofence1

The following is an example response for GetGeofence:

{
"CreateTime": 2020-09-30T22:59:34.142Z,
"GeofenceId": "ExampleGeofence1",
"Geometry": {
"Polygon": [
[-1,-1],
[1,-1],
[0,1],
[-1,-1]
]
},
"Status": "ACTIVE",
"UpdateTime": 2020-09-30T23:59:34.142Z
}

CLI

Use the get-geofence command.

The following example is an AWS CLI to get the geofence collection details for
ExampleCollection.

aws location get-geofence \


--collection-name "ExampleCollection" \
--geofence-id "ExampleGeofence1"

Delete geofences
You can delete geofences from a geofence collection using the Amazon Location console, the AWS CLI, or
the Amazon Location APIs:

99
Amazon Location Service Developer Guide
Trackers

Console

To delete a geofence using the Amazon Location console


Warning
This action deletes the resource permanently. You can't undo this action.

1. Open the Amazon Location console at https://console.aws.amazon.com/location/.


2. Choose Geofence collections from the left navigation pane.
3. From the Geofence collections list, select the name link for the target geofence collection.
4. Under Geofences, select the target geofence.
5. Choose Delete geofence.

API

Use the BatchDeleteGeofence action from the Amazon Location Geofences APIs.

The following example is an API request to delete geofences from the geofence collection
ExampleCollection.

POST /geofencing/v0/collections/ExampleCollection/delete-geofences
Content-type: application/json

{
"GeofenceIds": [ "ExampleGeofence11" ]
}

The following is an example success response for BatchDeleteGeofence:

HTTP/1.1 200

CLI

Use the batch-delete-geofence command.

The following example is an AWS CLI command to delete geofences from the geofence collection
ExampleCollection.

aws location batch-delete-geofence \


--collection-name "ExampleCollection" \
--geofence-ids "ExampleGeofence11"

Managing your tracker resources


You can manage your trackers using the Amazon Location console, the AWS CLI, or the Amazon Location
APIs.

List your trackers


You can view your trackers list using the Amazon Location console, the AWS CLI, or the Amazon Location
APIs:

Console

To view a list of existing trackers using the Amazon Location console

100
Amazon Location Service Developer Guide
Trackers

1. Open the Amazon Location console at https://console.aws.amazon.com/location/.


2. Choose Trackers from the left navigation.
3. Under Trackers, you'll be able to view your list of trackers.

API

Use the ListTrackers action from the Amazon Location Trackers APIs.

The following example is an API request to get a list of trackers in your AWS account.

POST /tracking/v0/list-trackers

The following is an example response for ListTrackers:

{
"Entries": [
{
"CreateTime": 2020-10-02T19:09:07.327Z,
"Description": "string",
"TrackerName": "ExampleTracker",
"UpdateTime": 2020-10-02T19:10:07.327Z
}
],
"NextToken": "1234-5678-9012"
}

CLI

Use the list-trackers command.

The following example is an AWS CLI to get a list of trackers in your AWS account.

aws location list-trackers

Disconnecting a tracker from a geofence collection


You can disconnect a tracker from a geofence collection using the Amazon Location console, the AWS
CLI, or the Amazon Location APIs:

Console

To disassociate a tracker from an associated geofence collection using the Amazon Location
console

1. Open the Amazon Location console at https://console.aws.amazon.com/location/.


2. Choose Trackers from the left navigation pane.
3. Under Trackers, select the name link of the target tracker.
4. Under Linked Geofence Collections, select a geofence collection with a Linked status.
5. Choose Unlink.

API

Use the DisassociateTrackerConsumer action from the Amazon Location Trackers APIs.

101
Amazon Location Service Developer Guide
Trackers

The following example is an API request to disassociate a tracker from an associated geofence
collection.

DELETE /tracking/v0/trackers/ExampleTracker/consumers/arn:aws:geo:us-
west-2:123456789012:geofence-collection/ExampleCollection

The following is an example response for DisassociateTrackerConsumer:

HTTP/1.1 200

CLI

Use the disassociate-tracker-consumer command.

The following example is an AWS CLI command to disassociate a tracker from an associated
geofence collection.

aws location disassociate-tracker-consumer \


--consumer-arn "arn:aws:geo:us-west-2:123456789012:geofence-collection/
ExampleCollection" \
--tracker-name "ExampleTracker"

Get tracker details


You can get details about any tracker in your AWS account using the Amazon Location console, the AWS
CLI, or the Amazon Location APIs:

Console

To view tracker details using the Amazon Location console

1. Open the Amazon Location console at https://console.aws.amazon.com/location/.


2. Choose Trackers from the left navigation.
3. Under Trackers, select the name link of the target tracker.
4. Under Information, you'll be able to view the tracker details.

API

Use the DescribeTracker action from the Amazon Location Tracker APIs.

The following example is an API request to get the tracker details for ExampleTracker.

GET /tracking/v0/trackers/ExampleTracker

The following is an example response for DescribeTracker:

{
"CreateTime": 2020-10-02T19:09:07.327Z,
"Description": "string",
"TrackerArn": "arn:aws:geo:us-west-2:123456789012:tracker/ExampleTracker",
"TrackerName": "ExampleTracker",
"UpdateTime": 2020-10-02T19:10:07.327Z
}

102
Amazon Location Service Developer Guide
Trackers

CLI

Use the describe-tracker command.

The following example is an AWS CLI to get tracker details for ExampleTracker.

aws location describe-tracker \


--tracker-name "ExampleTracker"

Delete a tracker
You can delete a tracker from your AWS account using the Amazon Location console, the AWS CLI, or the
Amazon Location APIs:

Console

To delete an existing map resource using the Amazon Location console


Warning
This action deletes the resource permanently. You can't undo this action. If the tracker
resource is in use, you may encounter an error. Make sure that the target resource is not a
dependency for your applications.

1. Open the Amazon Location console at https://console.aws.amazon.com/location/.


2. Choose Trackers from the left navigation pane.
3. From the Trackers list, select the target tracker.
4. Choose Delete tracker.

API

Use the DeleteTracker action from the Amazon Location Tracker APIs.

The following example is an API request to delete the tracker ExampleTracker.

DELETE /tracking/v0/trackers/ExampleTracker

The following is an example response for DeleteTracker:

HTTP/1.1 200

CLI

Use the delete-tracker command.

The following example is an AWS CLI command to delete the tracker ExampleTracker.

aws location delete-tracker \


--tracker-name "ExampleTracker"

103
Amazon Location Service Developer Guide
Security

Best practices for Amazon Location


Service
This topic provides best practices to help you use Amazon Location Service. While these best practices
can help you take full advantage of the Amazon Location Service, they do not represent a complete
solution. You should follow only the recommendations that are applicable for your environment.

Security
To help manage or even avoid security risks, consider the following best practices:

• Use identity federation, IAM users, and IAM roles to manage, control, or limit access to your Amazon
Location resources. For more information, see IAM Best Practices in the IAM User Guide.
• Follow the Principle of Least Privilege to grant only the minimum required access to your Amazon
Location Service resources. For more information, see the section called “Managing access using
policies” (p. 109).
• Use monitoring and logging tools to track resource access and usage. For more information, see the
section called “Logging and Monitoring” (p. 120) and Logging Data Events for Trails in the AWS
CloudTrail User Guide.
• Use secure connections, such as those that begin with https:// to add security and protect users
against attacks while data is being transmitted between the server and browser.

For more information about detective and preventive security best practices, see the topic on the section
called “Security best practices” (p. 122).

Resource management
To help effectively manage your location resources in Amazon Location Service, consider the following
best practices:

• Use regional endpoints that are central to your expected user base to improve their experience.
• For resources that use data providers, such as map resources and Place index resources, make sure
to follow the terms of use agreement of the specific data provider. For more information, see Data
providers.

Billing and cost management


To help manage your costs and billing, consider the following best practice:

• Use monitoring tools, such as Amazon CloudWatch, to track your resource usage. You can set alerts
that notify you when usage is about to exceed your specified limits. For more information, see Creating
a Billing Alarm to Monitor Your Estimated AWS Charges in the Amazon CloudWatch User Guide.

104
Amazon Location Service Developer Guide
Data protection

Security in Amazon Location Service


Cloud security at AWS is the highest priority. As an AWS customer, you benefit from data centers
and network architectures that are built to meet the requirements of the most security-sensitive
organizations.

Security is a shared responsibility between AWS and you. The shared responsibility model describes this
as security of the cloud and security in the cloud:

• Security of the cloud – AWS is responsible for protecting the infrastructure that runs AWS services in
the AWS Cloud. AWS also provides you with services that you can use securely. Third-party auditors
regularly test and verify the effectiveness of our security as part of the AWS Compliance Programs. For
more information about the compliance programs that apply to Amazon Location Service, see AWS
Services in Scope by Compliance Program.
• Security in the cloud – Your responsibility is determined by the AWS service that you use. You are also
responsible for other factors including the sensitivity of your data, your company’s requirements, and
applicable laws and regulations.

This documentation helps you understand how to apply the shared responsibility model when using
Amazon Location. The following topics show you how to configure Amazon Location to meet your
security and compliance objectives. You also learn how to use other AWS services that help you to
monitor and secure your Amazon Location resources.

Topics
• Data protection in Amazon Location Service (p. 105)
• Identity and Access Management for Amazon Location Service (p. 107)
• Incident Response in Amazon Location Service (p. 120)
• Compliance validation for Amazon Location Service (p. 120)
• Resilience in Amazon Location Service (p. 121)
• Infrastructure security in Amazon Location Service (p. 121)
• Security best practices for Amazon Location Service (p. 122)

Data protection in Amazon Location Service


The AWS shared responsibility model applies to data protection in Amazon Location Service. As
described in this model, AWS is responsible for protecting the global infrastructure that runs all
of the AWS Cloud. You are responsible for maintaining control over your content that is hosted on
this infrastructure. This content includes the security configuration and management tasks for the
AWS services that you use. For more information about data privacy, see the Data Privacy FAQ. For
information about data protection in Europe, see the AWS Shared Responsibility Model and GDPR blog
post on the AWS Security Blog.

For data protection purposes, we recommend that you protect AWS account credentials and set up
individual user accounts with AWS Identity and Access Management (IAM). That way each user is given
only the permissions necessary to fulfill their job duties. We also recommend that you secure your data
in the following ways:

• Use multi-factor authentication (MFA) with each account.

105
Amazon Location Service Developer Guide
Data retention

• Use SSL/TLS to communicate with AWS resources. We recommend TLS 1.2 or later.
• Set up API and user activity logging with AWS CloudTrail.
• Use AWS encryption solutions, along with all default security controls within AWS services.
• Use advanced managed security services such as Amazon Macie, which assists in discovering and
securing personal data that is stored in Amazon S3.
• If you require FIPS 140-2 validated cryptographic modules when accessing AWS through a command
line interface or an API, use a FIPS endpoint. For more information about the available FIPS endpoints,
see Federal Information Processing Standard (FIPS) 140-2.

We strongly recommend that you never put sensitive identifying information, such as your customers'
account numbers, into free-form fields such as a Name field. This includes when you work with Amazon
Location or other AWS services using the console, API, AWS CLI, or AWS SDKs. Any data that you enter
into Amazon Location or other services might get picked up for inclusion in diagnostic logs. When you
provide a URL to an external server, don't include credentials information in the URL to validate your
request to that server.

Data retention in Amazon Location


The following characteristics relate to how Amazon Location collects and stores data for the service:

• Amazon Location Service Trackers – When you use the Trackers APIs to track the location of entities,
their coordinates can be stored. Device locations will be stored for 1 year before being deleted by the
service.
• Amazon Location Service Geofences – When you use the Geofences APIs to define areas of interest,
the service stores the geometries you provided. They must be explicitly deleted.
Note
Deleting your AWS account will delete all resources within it. For additional information, see
the AWS Data Privacy FAQ.

Configuration and vulnerability analysis in Amazon


Location
Configuration and IT controls are a shared responsibility between AWS and you, our customer. For more
information, see the AWS shared responsibility model.

Encryption for data at rest


By default, all data stored by Amazon Location is encrypted at rest using an AWS Key Management
Service (KMS) key.
Note
You can't disable this encryption and you can't provide your own encryption key. For more
information, see the section called “Key management” (p. 107).

Encryption for data in transit


Any customer-identifying data is automatically encrypted while in transit using the Transport Layer
Security (TLS) 1.2 encryption protocol.

When a direct HTTPS request is sent, the request is signed using the AWS Signature Version 4 Algorithm
to establish a secure connection.

106
Amazon Location Service Developer Guide
Key management

Key management in Amazon Location


You can't use your own KMS keys with Amazon Location. Amazon Location manages encryption at rest
using a service-managed KMS key. For more information about encryption keys, see What is AWS KMS?
in the AWS Key Management Service Developer Guide.

Identity and Access Management for Amazon


Location Service
AWS Identity and Access Management (IAM) is an AWS service that helps an administrator securely
control access to AWS resources. IAM administrators control who can be authenticated (signed in) and
authorized (have permissions) to use Amazon Location resources. IAM is an AWS service that you can use
with no additional charge.

Audience
How you use AWS Identity and Access Management (IAM) differs, depending on the work that you do in
Amazon Location.

Service user – If you use the Amazon Location service to do your job, then your administrator provides
you with the credentials and permissions that you need. As you use more Amazon Location features to
do your work, you might need additional permissions. Understanding how access is managed can help
you request the right permissions from your administrator. If you cannot access a feature in Amazon
Location, see Troubleshooting Amazon Location Service identity and access (p. 118).

Service administrator – If you're in charge of Amazon Location resources at your company, you probably
have full access to Amazon Location. It's your job to determine which Amazon Location features and
resources your employees should access. You must then submit requests to your IAM administrator to
change the permissions of your service users. Review the information on this page to understand the
basic concepts of IAM. To learn more about how your company can use IAM with Amazon Location, see
How Amazon Location Service works with IAM (p. 111).

IAM administrator – If you're an IAM administrator, you might want to learn details about how you can
write policies to manage access to Amazon Location. To view example Amazon Location identity-based
policies that you can use in IAM, see Amazon Location Service identity-based policy examples (p. 114).

Authenticating with identities


Authentication is how you sign in to AWS using your identity credentials. For more information about
signing in using the AWS Management Console, see Signing in to the AWS Management Console as an
IAM user or root user in the IAM User Guide.

You must be authenticated (signed in to AWS) as the AWS account root user, an IAM user, or by assuming
an IAM role. You can also use your company's single sign-on authentication or even sign in using Google
or Facebook. In these cases, your administrator previously set up identity federation using IAM roles.
When you access AWS using credentials from another company, you are assuming a role indirectly.

To sign in directly to the AWS Management Console, use your password with your root user email
address or your IAM user name. You can access AWS programmatically using your root user or IAM
users access keys. AWS provides SDK and command line tools to cryptographically sign your request
using your credentials. If you don't use AWS tools, you must sign the request yourself. Do this using
Signature Version 4, a protocol for authenticating inbound API requests. For more information about
authenticating requests, see Signature Version 4 signing process in the AWS General Reference.

107
Amazon Location Service Developer Guide
Authenticating with identities

Regardless of the authentication method that you use, you might also be required to provide additional
security information. For example, AWS recommends that you use multi-factor authentication (MFA) to
increase the security of your account. To learn more, see Using multi-factor authentication (MFA) in AWS
in the IAM User Guide.

AWS account root user

When you first create an AWS account, you begin with a single sign-in identity that has complete access
to all AWS services and resources in the account. This identity is called the AWS account root user and
is accessed by signing in with the email address and password that you used to create the account. We
strongly recommend that you do not use the root user for your everyday tasks, even the administrative
ones. Instead, adhere to the best practice of using the root user only to create your first IAM user. Then
securely lock away the root user credentials and use them to perform only a few account and service
management tasks.

IAM users and groups

An IAM user is an identity within your AWS account that has specific permissions for a single person or
application. An IAM user can have long-term credentials such as a user name and password or a set of
access keys. To learn how to generate access keys, see Managing access keys for IAM users in the IAM
User Guide. When you generate access keys for an IAM user, make sure you view and securely save the key
pair. You cannot recover the secret access key in the future. Instead, you must generate a new access key
pair.

An IAM group is an identity that specifies a collection of IAM users. You can't sign in as a group. You
can use groups to specify permissions for multiple users at a time. Groups make permissions easier to
manage for large sets of users. For example, you could have a group named IAMAdmins and give that
group permissions to administer IAM resources.

Users are different from roles. A user is uniquely associated with one person or application, but a role
is intended to be assumable by anyone who needs it. Users have permanent long-term credentials, but
roles provide temporary credentials. To learn more, see When to create an IAM user (instead of a role) in
the IAM User Guide.

IAM roles

An IAM role is an identity within your AWS account that has specific permissions. It is similar to an IAM
user, but is not associated with a specific person. You can temporarily assume an IAM role in the AWS
Management Console by switching roles. You can assume a role by calling an AWS CLI or AWS API
operation or by using a custom URL. For more information about methods for using roles, see Using IAM
roles in the IAM User Guide.

IAM roles with temporary credentials are useful in the following situations:

• Temporary IAM user permissions – An IAM user can assume an IAM role to temporarily take on
different permissions for a specific task.
• Federated user access – Instead of creating an IAM user, you can use existing identities from AWS
Directory Service, your enterprise user directory, or a web identity provider. These are known as
federated users. AWS assigns a role to a federated user when access is requested through an identity
provider. For more information about federated users, see Federated users and roles in the IAM User
Guide.
• Cross-account access – You can use an IAM role to allow someone (a trusted principal) in a different
account to access resources in your account. Roles are the primary way to grant cross-account access.
However, with some AWS services, you can attach a policy directly to a resource (instead of using a role

108
Amazon Location Service Developer Guide
Managing access using policies

as a proxy). To learn the difference between roles and resource-based policies for cross-account access,
see How IAM roles differ from resource-based policies in the IAM User Guide.
• Cross-service access – Some AWS services use features in other AWS services. For example, when you
make a call in a service, it's common for that service to run applications in Amazon EC2 or store objects
in Amazon S3. A service might do this using the calling principal's permissions, using a service role, or
using a service-linked role.
• Principal permissions – When you use an IAM user or role to perform actions in AWS, you are
considered a principal. Policies grant permissions to a principal. When you use some services, you
might perform an action that then triggers another action in a different service. In this case, you
must have permissions to perform both actions. To see whether an action requires additional
dependent actions in a policy, see Actions, Resources, and Condition Keys for Amazon Location
Service in the Service Authorization Reference.
• Service role – A service role is an IAM role that a service assumes to perform actions on your behalf.
Service roles provide access only within your account and cannot be used to grant access to services
in other accounts. An IAM administrator can create, modify, and delete a service role from within
IAM. For more information, see Creating a role to delegate permissions to an AWS service in the IAM
User Guide.
• Service-linked role – A service-linked role is a type of service role that is linked to an AWS service.
The service can assume the role to perform an action on your behalf. Service-linked roles appear
in your IAM account and are owned by the service. An IAM administrator can view, but not edit the
permissions for service-linked roles.
• Applications running on Amazon EC2 – You can use an IAM role to manage temporary credentials
for applications that are running on an EC2 instance and making AWS CLI or AWS API requests.
This is preferable to storing access keys within the EC2 instance. To assign an AWS role to an EC2
instance and make it available to all of its applications, you create an instance profile that is attached
to the instance. An instance profile contains the role and enables programs that are running on the
EC2 instance to get temporary credentials. For more information, see Using an IAM role to grant
permissions to applications running on Amazon EC2 instances in the IAM User Guide.

To learn whether to use IAM roles or IAM users, see When to create an IAM role (instead of a user) in the
IAM User Guide.

Managing access using policies


You control access in AWS by creating policies and attaching them to IAM identities or AWS resources. A
policy is an object in AWS that, when associated with an identity or resource, defines their permissions.
You can sign in as the root user or an IAM user, or you can assume an IAM role. When you then make
a request, AWS evaluates the related identity-based or resource-based policies. Permissions in the
policies determine whether the request is allowed or denied. Most policies are stored in AWS as JSON
documents. For more information about the structure and contents of JSON policy documents, see
Overview of JSON policies in the IAM User Guide.

Administrators can use AWS JSON policies to specify who has access to what. That is, which principal can
perform actions on what resources, and under what conditions.

Every IAM entity (user or role) starts with no permissions. In other words, by default, users can
do nothing, not even change their own password. To give a user permission to do something, an
administrator must attach a permissions policy to a user. Or the administrator can add the user to a
group that has the intended permissions. When an administrator gives permissions to a group, all users
in that group are granted those permissions.

IAM policies define permissions for an action regardless of the method that you use to perform the
operation. For example, suppose that you have a policy that allows the iam:GetRole action. A user with
that policy can get role information from the AWS Management Console, the AWS CLI, or the AWS API.

109
Amazon Location Service Developer Guide
Managing access using policies

Identity-based policies

Identity-based policies are JSON permissions policy documents that you can attach to an identity, such
as an IAM user, group of users, or role. These policies control what actions users and roles can perform,
on which resources, and under what conditions. To learn how to create an identity-based policy, see
Creating IAM policies in the IAM User Guide.

Identity-based policies can be further categorized as inline policies or managed policies. Inline policies
are embedded directly into a single user, group, or role. Managed policies are standalone policies that
you can attach to multiple users, groups, and roles in your AWS account. Managed policies include AWS
managed policies and customer managed policies. To learn how to choose between a managed policy or
an inline policy, see Choosing between managed policies and inline policies in the IAM User Guide.

Resource-based policies

Resource-based policies are JSON policy documents that you attach to a resource. Examples of resource-
based policies are IAM role trust policies and Amazon S3 bucket policies. In services that support resource-
based policies, service administrators can use them to control access to a specific resource. For the
resource where the policy is attached, the policy defines what actions a specified principal can perform
on that resource and under what conditions. You must specify a principal in a resource-based policy.
Principals can include accounts, users, roles, federated users, or AWS services.

Resource-based policies are inline policies that are located in that service. You can't use AWS managed
policies from IAM in a resource-based policy.

Access Control Lists (ACLs)

Access control lists (ACLs) control which principals (account members, users, or roles) have permissions to
access a resource. ACLs are similar to resource-based policies, although they do not use the JSON policy
document format.

Amazon S3, AWS WAF, and Amazon VPC are examples of services that support ACLs. To learn more about
ACLs, see Access control list (ACL) overview in the Amazon Simple Storage Service Developer Guide.

Other policy types

AWS supports additional, less-common policy types. These policy types can set the maximum
permissions granted to you by the more common policy types.

• Permissions boundaries – A permissions boundary is an advanced feature in which you set the
maximum permissions that an identity-based policy can grant to an IAM entity (IAM user or role).
You can set a permissions boundary for an entity. The resulting permissions are the intersection of
entity's identity-based policies and its permissions boundaries. Resource-based policies that specify
the user or role in the Principal field are not limited by the permissions boundary. An explicit deny
in any of these policies overrides the allow. For more information about permissions boundaries, see
Permissions boundaries for IAM entities in the IAM User Guide.
• Service control policies (SCPs) – SCPs are JSON policies that specify the maximum permissions for
an organization or organizational unit (OU) in AWS Organizations. AWS Organizations is a service for
grouping and centrally managing multiple AWS accounts that your business owns. If you enable all
features in an organization, then you can apply service control policies (SCPs) to any or all of your
accounts. The SCP limits permissions for entities in member accounts, including each AWS account

110
Amazon Location Service Developer Guide
How Amazon Location Service works with IAM

root user. For more information about Organizations and SCPs, see How SCPs work in the AWS
Organizations User Guide.
• Session policies – Session policies are advanced policies that you pass as a parameter when you
programmatically create a temporary session for a role or federated user. The resulting session's
permissions are the intersection of the user or role's identity-based policies and the session policies.
Permissions can also come from a resource-based policy. An explicit deny in any of these policies
overrides the allow. For more information, see Session policies in the IAM User Guide.

Multiple policy types

When multiple types of policies apply to a request, the resulting permissions are more complicated to
understand. To learn how AWS determines whether to allow a request when multiple policy types are
involved, see Policy evaluation logic in the IAM User Guide.

How Amazon Location Service works with IAM


Before you use IAM to manage access to Amazon Location, you should understand what IAM features are
available to use with Amazon Location. For a high-level view of how Amazon Location and other AWS
services work with IAM, see AWS Services That Work with IAM in the IAM User Guide.

Topics
• Identity-based policies (p. 111)
• Amazon Location resource-based policies (p. 113)
• Amazon Location IAM roles (p. 113)

Identity-based policies
With IAM identity-based policies, you can specify allowed or denied actions and resources as well as
the conditions under which actions are allowed or denied. Amazon Location supports specific actions,
resources, and condition keys. To learn about all of the elements that you use in a JSON policy, see IAM
JSON Policy Elements Reference in the IAM User Guide.

Actions
Administrators can use AWS JSON policies to specify who has access to what. That is, which principal can
perform actions on what resources, and under what conditions.

The Action element of a JSON policy describes the actions that you can use to allow or deny access in a
policy. Policy actions usually have the same name as the associated AWS API operation. There are some
exceptions, such as permission-only actions that don't have a matching API operation. There are also
some operations that require multiple actions in a policy. These additional actions are called dependent
actions.

Include actions in a policy to grant permissions to perform the associated operation.

Policy actions in Amazon Location use the following prefix: geo:.

Example

To grant someone read-only permission for Amazon Location Service trackers with the Amazon
Location Tracking API operation, you'll need to include geo:BatchGetDevicePosition,
geo:GetDevicePosition and geo:GetDevicePositionHistory in their policy.

111
Amazon Location Service Developer Guide
How Amazon Location Service works with IAM

Policy statements must include either an Action or NotAction element. Amazon Location defines its
own set of actions that describe tasks that you can perform with this service.

To specify multiple actions in a single statement, separate them with commas as follows:

{
"Action": [
"geo:BatchGetDevicePosition",
"geo:GetDevicePosition",
"geo:GetDevicePositionHistory"
]
}

You can specify multiple actions using wildcards (*). For example, to specify all actions that begin with
the word Get, include the following action:

"Action": "geo:Get*"

Warning
Avoid using wildcards (*) to specify all actions for a service. Use the best practice of granting
least privilege and narrow the permissions used in a policy.

To see a list of Amazon Location actions, see the Amazon Location API references.

Resources
Administrators can use AWS JSON policies to specify who has access to what. That is, which principal can
perform actions on what resources, and under what conditions.

The Resource JSON policy element specifies the object or objects to which the action applies.
Statements must include either a Resource or a NotResource element. As a best practice, specify
a resource using its Amazon Resource Name (ARN). You can do this for actions that support a specific
resource type, known as resource-level permissions.

For actions that don't support resource-level permissions, such as listing operations, use a wildcard (*) to
indicate that the statement applies to all resources.

"Resource": "*"

Amazon Location Service uses the following prefixes for resources:

Amazon Location resource prefix

Resource Resource prefix

Map resources map

Place resources place-index

Tracking resources tracker

Geofence Collection resources geofence-collection

Use the following ARN syntax:

arn:Partition:geo:Region:Account:ResourcePrefix/ResourceName

112
Amazon Location Service Developer Guide
How Amazon Location Service works with IAM

For more information about the format of ARNs, see Amazon Resource Names (ARNs) and AWS Service
Namespaces.

Examples

• Use the following ARN to allow access to a specified map resource.

"Resource": "arn:aws:geo:us-west-2:account-id:map/map-resource-name"

• To specify access to all map resources that belong to a specific account, use the wildcard (*):

"Resource": "arn:aws:geo:us-west-2:account-id:map/*"

• Some Amazon Location actions, such as those for creating resources, can't be performed on a specific
resource. In those cases, you must use the wildcard (*).

"Resource": "*"

Many Amazon Location Service API actions involve multiple resources. For example, getting map
tiles requires the IAM user to have permissions to retrieve map tiles, sprite files, glyphs, and the style
descriptor file.

To specify multiple resources in a single statement, separate the ARNs with commas:

{
"Resource": [
"geo:GetMapTile",
"geo:GetMapSprites",
"geo:GetMapGlyphs",
"geo:GetMapStyleDescriptor"
]
}

Condition keys

Amazon Location does not provide any service-specific condition keys, but it does support using some
global condition keys. To see all AWS global condition keys, see AWS Global Condition Context Keys in
the IAM User Guide.

Amazon Location resource-based policies

Amazon Location does not support resource-based policies.

Amazon Location IAM roles


An IAM role is an entity within your AWS account that has specific permissions.

Using temporary credentials with Amazon Location


You can use temporary credentials to sign in with federation, assume an IAM role, or to assume a cross-
account role. You obtain temporary security credentials by calling AWS STS API operations such as
AssumeRole or GetFederationToken.

Amazon Location supports using temporary credentials.

113
Amazon Location Service Developer Guide
Identity-based policy examples

Amazon Location Service identity-based policy


examples
By default, IAM users and roles don't have permission to create or modify Amazon Location resources.
They also can't perform tasks using the AWS Management Console, AWS CLI, or AWS API. An IAM
administrator must create IAM policies that grant users and roles permission to perform specific API
operations on the specified resources they need. The administrator must then attach those policies to
the IAM users or groups that require those permissions.

To learn how to create an IAM identity-based policy using these example JSON policy documents, see
Creating Policies on the JSON Tab in the IAM User Guide.

Policy best practices


Identity-based policies are very powerful. They determine whether someone can create, access, or delete
Amazon Location resources in your account. These actions can incur costs for your AWS account. When
you create or edit identity-based policies, follow these guidelines and recommendations:

• Get started using AWS managed policies – To start using Amazon Location quickly, use AWS
managed policies to give your employees the permissions they need. These policies are already
available in your account and are maintained and updated by AWS. For more information, see Get
started using permissions with AWS managed policies in the IAM User Guide.
• Grant least privilege – When you create custom policies, grant only the permissions required
to perform a task. Start with a minimum set of permissions and grant additional permissions as
necessary. Doing so is more secure than starting with permissions that are too lenient and then trying
to tighten them later. For more information, see Grant least privilege in the IAM User Guide.
• Enable MFA for sensitive operations – For extra security, require IAM users to use multi-factor
authentication (MFA) to access sensitive resources or API operations. For more information, see Using
multi-factor authentication (MFA) in AWS in the IAM User Guide.
• Use policy conditions for extra security – To the extent that it's practical, define the conditions under
which your identity-based policies allow access to a resource. For example, you can write conditions to
specify a range of allowable IP addresses that a request must come from. You can also write conditions
to allow requests only within a specified date or time range, or to require the use of SSL or MFA. For
more information, see IAM JSON policy elements: Condition in the IAM User Guide.

Allow users to view their own permissions


This example shows how you might create a policy that allows IAM users to view the inline and managed
policies that are attached to their user identity. This policy includes permissions to complete this action
on the console or programmatically using the AWS CLI or AWS API.

{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "ViewOwnUserInfo",
"Effect": "Allow",
"Action": [
"iam:GetUserPolicy",
"iam:ListGroupsForUser",
"iam:ListAttachedUserPolicies",
"iam:ListUserPolicies",
"iam:GetUser"
],
"Resource": [

114
Amazon Location Service Developer Guide
Identity-based policy examples

"arn:aws:iam::*:user/${aws:username}"
]
},
{
"Sid": "NavigateInConsole",
"Effect": "Allow",
"Action": [
"iam:GetGroupPolicy",
"iam:GetPolicyVersion",
"iam:GetPolicy",
"iam:ListAttachedGroupPolicies",
"iam:ListGroupPolicies",
"iam:ListPolicyVersions",
"iam:ListPolicies",
"iam:ListUsers"
],
"Resource": "*"
}
]
}

Permissions required to use the Amazon Location console


To access the Amazon Location Service console, and be able to create, delete, list and view details about
Amazon Location resources in your AWS account, you will need to grant permission to access all Amazon
Location resources. For more information, see Adding Permissions to a User in the IAM User Guide.

To grant permission to access to all Amazon Location resources for the Amazon Location Service console:

{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "GeoPowerUser",
"Effect": "Allow",
"Action": [
"geo:*"
],
"Resource": "*"
}
]
}

Alternatively, you can grant read-only permissions to facilitate read-only access. With read-only
permissions, an error message will appear if the user attempts write actions such as creating or deleting
resources. As an example, see the section called “Read-only policy for trackers” (p. 116)

Permissions for updating device positions


To update device positions for multiple trackers, you'll want to grant an IAM user in your AWS account
access to one or more of your tracker resources. You will also want to allow the user to update a batch of
device positions.

In this example, in addition to granting access to the Tracker1 and Tracker2 resources, the following
policy grants permission to use the geo:BatchUpdateDevicePosition action against the Tracker1
and Tracker2 resources.

{
"Version": "2012-10-17",
"Statement": [
{

115
Amazon Location Service Developer Guide
Identity-based policy examples

"Sid": "UpdateDevicePositions",
"Effect": "Allow",
"Action": [
"geo:BatchUpdateDevicePosition"
],
"Resource": [
"arn:aws:geo:us-west-2:account-id:tracker/Tracker1",
"arn:aws:geo:us-west-2:account-id:tracker/Tracker2"
]
}
]
}

Read-only policy for tracker resources


To create a read-only policy for all tracker resources in your AWS account, you'll need to grant access to
all tracker resources. You'll also want to grant an IAM user access to actions that allow them to get the
device position for multiple devices, get the device position from a single device and get the position
history.

In this example, the following policy grants permission to the following actions:

• geo:BatchGetDevicePosition to retrieve the position of multiple devices.


• geo:GetDevicePosition to retrieve the position of a single device.
• geo:GetDevicePositionHistory to retrieve the position history of a device.

{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "GetDevicePositions",
"Effect": "Allow",
"Action": [
"geo:BatchGetDevicePosition",
"geo:GetDevicePosition",
"geo:GetDevicePositionHistory"
],
"Resource": "arn:aws:geo:us-west-2:account-id:tracker/*"
}
]
}

Policy for creating geofences


To create a policy to allow an IAM user to create geofences, you'll need to grant access to specific actions
that allow users to create one or more geofences on a geofence collection.

The policy below grants permission to the following actions on Collection:

• geo:BatchPutGeofence to create multiple geofences.


• geo:PutGeofence to create a single geofence.

{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "CreateGeofences",

116
Amazon Location Service Developer Guide
Identity-based policy examples

"Effect": "Allow",
"Action": [
"geo:BatchPutGeofence",
"geo:PutGeofence"
],
"Resource": "arn:aws:geo:us-west-2:account-id:geofence-collection/Collection"
}
]
}

Read-only policy for geofences


To create a read-only policy for geofences stored in a geofence collection in your AWS account, you'll
need to grant access to actions that read from the geofence collection storing the geofences.

The policy below grants permission to the following actions on Collection:

• geo:ListGeofences to list geofences in the specified geofence collection.


• geo:GetGeofence to retrieve a geofence from the geofence collection.

{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "GetGeofences",
"Effect": "Allow",
"Action": [
"geo:ListGeofences",
"geo:GetGeofence"
],
"Resource": "arn:aws:geo:us-west-2:account-id:geofence-collection/Collection"
}
]
}

Permissions for rendering a map resource


To grant sufficient permissions to render maps, you'll need to grant access to map tiles, sprites, glyphs,
and the style descriptor:

• geo:GetMapTile retrieves map tiles used to selectively render features on a map.


• geo:GetMapSprites retrieves the PNG sprite sheet and corresponding JSON document describing
offsets within it.
• geo:GetMapGlyphs retrieves the glyphs used for displaying text.
• geo:GetMapStyleDescriptor retrieves the map’s style descriptor, containing rendering rules.

{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "GetTiles",
"Effect": "Allow",
"Action": [
"geo:GetMapTile",
"geo:GetMapSprites",
"geo:GetMapGlyphs",
"geo:GetMapStyleDescriptor"

117
Amazon Location Service Developer Guide
Troubleshooting

],
"Resource": "arn:aws:geo:us-west-2:account-id:map/Map"
}
]
}

Permissions to allow search operations


To create a policy to allow search operations, you'll first need to grant access to the place index resource
in your AWS account. You'll also want to grant access to actions that let the IAM user search using text by
geocoding and search using a position by reverse geocoding.

In this example, in addition to granting access to PlaceIndex, the following policy also grants
permission to the following actions:

• geo:SearchPlaceIndexForPosition allows you to search for places, or points of interest near a


given position.
• geo:SearchPlaceIndexForText allows you to search for an address, name, city or region using
free-form text.

{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "Search",
"Effect": "Allow",
"Action": [
"geo:SearchPlaceIndexForPosition",
"geo:SearchPlaceIndexForText"
],
"Resource": "arn:aws:geo:us-west-2:account-id:place-index/PlaceIndex"
}
]
}

Troubleshooting Amazon Location Service identity


and access
Use the following information to help you diagnose and fix common issues that you might encounter
when working with Amazon Location and IAM.

Topics
• I am not authorized to perform an action in Amazon Location Service (p. 118)
• I want to view my access keys (p. 119)
• I'm an administrator and want to allow others to access Amazon Location (p. 119)
• I want to allow people outside of my AWS account to access my Amazon Location resources (p. 119)

I am not authorized to perform an action in Amazon Location


Service
If the AWS Management Console tells you that you're not authorized to perform an action, then you
must contact your administrator for assistance. Your administrator is the person that provided you with
your user name and password.

118
Amazon Location Service Developer Guide
Troubleshooting

The following example error occurs when the mateojackson IAM user tries to create a Map resource but
does not have geo:CreateMap permissions.

User: arn:aws:iam::123456789012:user/mateojackson is not authorized to perform:


geo:CreateMap on resource: Map

In this case, Mateo asks his administrator to update his policies to allow him to access the Map resource
using the geo:CreateMap action.

I want to view my access keys


After you create your IAM user access keys, you can view your access key ID at any time. However, you
can't view your secret access key again. If you lose your secret key, you must create a new access key pair.

Access keys consist of two parts: an access key ID (for example, AKIAIOSFODNN7EXAMPLE) and a secret
access key (for example, wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY). Like a user name and
password, you must use both the access key ID and secret access key together to authenticate your
requests. Manage your access keys as securely as you do your user name and password.
Important
Do not provide your access keys to a third party, even to help find your canonical user ID. By
doing this, you might give someone permanent access to your account.

When you create an access key pair, you are prompted to save the access key ID and secret access key in
a secure location. The secret access key is available only at the time you create it. If you lose your secret
access key, you must add new access keys to your IAM user. You can have a maximum of two access keys.
If you already have two, you must delete one key pair before creating a new one. To view instructions,
see Managing access keys in the IAM User Guide.

I'm an administrator and want to allow others to access Amazon


Location
To allow others to access Amazon Location, you must create an IAM entity (user or role) for the person or
application that needs access. They will use the credentials for that entity to access AWS. You must then
attach a policy to the entity that grants them the correct permissions in Amazon Location.

To get started right away, see Creating your first IAM delegated user and group in the IAM User Guide.

I want to allow people outside of my AWS account to access my


Amazon Location resources
You can create a role that users in other accounts or people outside of your organization can use to
access your resources. You can specify who is trusted to assume the role. For services that support
resource-based policies or access control lists (ACLs), you can use those policies to grant people access to
your resources.

To learn more, consult the following:

• To learn whether Amazon Location supports these features, see How Amazon Location Service works
with IAM (p. 111).
• To learn how to provide access to your resources across AWS accounts that you own, see Providing
access to an IAM user in another AWS account that you own in the IAM User Guide.
• To learn how to provide access to your resources to third-party AWS accounts, see Providing access to
AWS accounts owned by third parties in the IAM User Guide.
• To learn how to provide access through identity federation, see Providing access to externally
authenticated users (identity federation) in the IAM User Guide.

119
Amazon Location Service Developer Guide
Incident response

• To learn the difference between using roles and resource-based policies for cross-account access, see
How IAM roles differ from resource-based policies in the IAM User Guide.

Incident Response in Amazon Location Service


Security is the highest priority at AWS. As part of the AWS Cloud shared responsibility model, AWS
manages a data center and network architecture that meets the requirements of the most security-
sensitive organizations. As an AWS customer, you share a responsibility for maintaining security in the
cloud. This means you control the security you choose to implement from the AWS tools and features
you have access to.

By establishing a security baseline that meets the objectives for your applications running in the cloud,
you're able to detect deviations that you can respond to. Since security incident response can be a
complex topic, we encourage you to review the following resources so that you are better able to
understand the impact that incident response (IR) and your choices have on your corporate goals: AWS
Security Incident Response Guide, AWS Security Best Practices whitepaper, and the Security Perspective
of the AWS Cloud Adoption Framework (CAF) white paper.

Logging and Monitoring in Amazon Location Service


Logging and monitoring are an important part of incident response. It lets you establish a security
baseline to detect deviations that you can investigate and respond to. By implementing logging
and monitoring for Amazon Location Service, you're able to maintain the reliability, availability and
performance for your projects and resources.

AWS provides several tools that can help you log and collect data for incident response:

AWS CloudTrail

Amazon Location Service integrates with AWS CloudTrail, which is a service that provides a record of
actions taken by a user, role or AWS service. This includes actions from the Amazon Location Service
console, and programmatic calls to Amazon Location API operations. These records of action are
called Insights, which are logged as Insight events to monitor for unusual API activity to allow you
the ability to identify when a request was made, the IP address from which it was made and the
user who made it along with additional details. For more information, see Logging and monitoring
Amazon Location Service with AWS CloudTrail.
Amazon CloudWatch

You can use Amazon CloudWatch to collect and analyze metrics related to your Amazon Location
Service account. You can enable CloudWatch alarms to notify you if a metric meets certain
conditions, and has reached a specified threshold. When you create an alarm, CloudWatch sends a
notification to an Amazon Simple Notification Service that you define. For more information, see the
Monitoring Amazon Location Service with Amazon CloudWatch.
AWS Health Dashboards

Using AWS Health Dashboards, you can check the status of the Amazon Location Service service.
You can also monitor and view historical data about any events or issues that might affect your AWS
environment. For more information, see the AWS Health User Guide.

Compliance validation for Amazon Location


Service
Third-party auditors assess the security and compliance of Amazon Location Service as part of multiple
AWS compliance programs. These include SOC, PCI, FedRAMP, HIPAA, and others.

120
Amazon Location Service Developer Guide
Resilience

For a list of AWS services in scope of specific compliance programs, see AWS Services in Scope by
Compliance Program. For general information, see AWS Compliance Programs.

You can download third-party audit reports using AWS Artifact. For more information, see Downloading
Reports in AWS Artifact.

Your compliance responsibility when using AWS services is determined by the sensitivity of your data,
your company's compliance objectives, and applicable laws and regulations. AWS provides the following
resources to help with compliance:

• Security and Compliance Quick Start Guides – These deployment guides discuss architectural
considerations and provide steps for deploying security- and compliance-focused baseline
environments on AWS.
• Architecting for HIPAA Security and Compliance Whitepaper – This whitepaper describes how
companies can use AWS to create HIPAA-compliant applications.
• AWS Compliance Resources – This collection of workbooks and guides might apply to your industry
and location.
• Evaluating Resources with Rules in the AWS Config Developer Guide – The AWS Config service assesses
how well your resource configurations comply with internal practices, industry guidelines, and
regulations.
• AWS Security Hub – This AWS service provides a comprehensive view of your security state within AWS
that helps you check your compliance with security industry standards and best practices.

Resilience in Amazon Location Service


The AWS global infrastructure is built around AWS Regions and Availability Zones. AWS Regions provide
multiple physically separated and isolated Availability Zones, which are connected with low-latency,
high-throughput, and highly redundant networking. With Availability Zones, you can design and operate
applications and databases that automatically fail over between zones without interruption. Availability
Zones are more highly available, fault tolerant, and scalable than traditional single or multiple data
center infrastructures.

For more information about AWS Regions and Availability Zones, see AWS Global Infrastructure.

In addition to the AWS global infrastructure, Amazon Location offers several features to help support
your data resiliency and backup needs.

Infrastructure security in Amazon Location Service


As a managed service, Amazon Location Service is protected by the AWS global network security
procedures that are described in the Amazon Web Services: Overview of Security Processes whitepaper.

You use AWS published API calls to access Amazon Location through the network. Clients must support
Transport Layer Security (TLS) 1.0 or later. We recommend TLS 1.2 or later. Clients must also support
cipher suites with Perfect Forward Secrecy, such as Ephemeral Diffie-Hellman (DHE) or Elliptic Curve
Ephemeral Diffie-Hellman (ECDHE). Most modern systems, such as Java 7 and later, support these
modes.

Additionally, requests must be signed by using an access key ID and a secret access key that is associated
with an IAM principal. Or you can use the AWS Security Token Service (AWS STS) to generate temporary
security credentials to sign requests.

121
Amazon Location Service Developer Guide
Security best practices

Security best practices for Amazon Location


Service
Amazon Location Service provides a number of security features to consider as you develop and
implement your own security policies. The following best practices are general guidelines and don’t
represent a complete security solution. Because these best practices might not be appropriate or
sufficient for your environment, treat them as helpful considerations rather than prescriptions.

Detective security best practices for Amazon Location


Service
The following best practices for Amazon Location Service can help detect security incidents:

Implement AWS monitoring tools

Monitoring is critical to incident response and maintains the reliability and security of Amazon
Location Service resources and your solutions. You can implement monitoring tools from the several
tools and services available through AWS to monitor your resources and your other AWS services.

For example, Amazon CloudWatch allows you to monitor metrics for Amazon Location Service and
enables you to setup alarms to notify you if a metric meets certain conditions you've set and has
reached a threshold you've defined. When you create an alarm, you can set CloudWatch to sent a
notification to alert using Amazon Simple Notification Service. For more information, see the section
called “Logging and Monitoring” (p. 120).
Enable AWS logging tools

Logging provides a record of actions taken by a user, role or an AWS service in Amazon Location
Service. You can implement logging tools such as AWS CloudTrail to collect data on actions to detect
unusual API activity.

When you create a trail, you can configure CloudTrail to log events. Events are records of resource
operations performed on or within a resource such as the request made to Amazon Location, the
IP address from which the request was made, who made the request, when the request was made,
along with additional data. For more information, see Logging Data Events for Trails in the AWS
CloudTrail User Guide.

Preventive security best practices for Amazon


Location Service
The following best practices for Amazon Location Service can help prevent security incidents:

Use secure connections

Always use encrypted connections, such as those that begin with https:// to keep sensitive
information secure in transit.
Implement least privilege access to resources

When you create custom policies to Amazon Location resources, grant only the permissions
required to perform a task. It's recommended to start with a minimum set of permissions and grant
additional permissions as needed. Implementing least privilege access is essential to reducing the
risk and impact that could result from errors or malicious attacks. For more information, see the
section called “Identity and Access Management” (p. 107).

122
Amazon Location Service Developer Guide

Amazon Location Service Quotas


The following table lists the service quotas for Amazon Location Service, also referred to as limits, or the
maximum number of service resources or operations for your AWS account.
Note
The Service Quotas console provides information about Amazon Location quotas. You can use
the Service Quotas console to view the default service quotas or to request quota increases for
adjustable quotas. Most service quotas are specific to an AWS Region, select the Region you
require the quota increase in.

Resource Description Quota Adjustable

Map resources per The maximum number 20 Yes


account and region of Map resources that
you can create per
account and region.

Place Index resources The maximum number 20 Yes


per account and region. of Place Index resources
that you can create per
account and region.

Tracker resources per The maximum number 100 Yes


account and region. of Tracker resources
that you can create per
account and region.

Geofence Collection The maximum number 1000 Yes


resources per account of Geofence Collection
and region resources that you can
create per account and
region.

Geofences per The maximum number 50000 Yes


Geofence Collection of Geofences that you
can create per Geofence
Collection.

Tracker consumers per The maximum number 10 Yes


tracker of Geofence Collection
that Tracker resource
can be associated with.

Rate of CreateMap API The maximum number 10 Yes


requests of CreateMap requests
that you can make per
second. Additional
requests are throttled.

Rate of DeleteMap API The maximum number 10 Yes


requests of DeleteMap requests
that you can make per
second. Additional
requests are throttled.

123
Amazon Location Service Developer Guide

Resource Description Quota Adjustable

Rate of DescribeMap The maximum number 10 Yes


API requests of DescribeMap
requests that you
can make per second.
Additional requests are
throttled.

Rate of ListMaps API The maximum number 10 Yes


requests of ListMaps requests
that you can make per
second. Additional
requests are throttled.

Rate of GetMapGlyphs The maximum number 50 Yes


API requests of GetMapGlyphs
requests that you
can make per second.
Additional requests are
throttled.

Rate of The maximum number 50 Yes


GetMapSprites API of GetMapSprites
requests requests that you
can make per second.
Additional requests are
throttled.

Rate of The maximum 50 Yes


number of
GetMapStyleDescriptor
API requests GetMapStyleDescriptor
requests that you
can make per second.
Additional requests are
throttled.

Rate of GetMapTile The maximum number 500 Yes


API requests of GetMapTile
requests that you
can make per second.
Additional requests are
throttled.

Rate of The maximum number 10 Yes


CreatePlaceIndex of CreatePlaceIndex
API requests requests that you
can make per second.
Additional requests are
throttled.

Rate of The maximum number 10 Yes


DeletePlaceIndex of DeletePlaceIndex
API requests requests that you
can make per second.
Additional requests are
throttled.

124
Amazon Location Service Developer Guide

Resource Description Quota Adjustable

Rate of The maximum 10 Yes


DescribePlaceIndex number of
API requests DescribePlaceIndex
requests that you
can make per second.
Additional requests are
throttled.

Rate of The maximum number 10 Yes


ListPlaceIndexes of ListPlaceIndexes
API requests requests that you
can make per second.
Additional requests are
throttled.

Rate of The maximum 50 Yes


number of
SearchPlaceIndexForPosition
API requests SearchPlaceIndexForPosition
requests that you
can make per second.
Additional requests are
throttled.

During preview release: During preview 10,000 No


Maximum monthly release, the
maximum number of
SearchPlaceIndexForPosition
API requests with SearchPlaceIndexForPosition
results stored. requests you can make
per month for a Place
index resource with
IntendedUse set to
Storage.

Rate of The maximum 50 Yes


number of
SearchPlaceIndexForText
API requests SearchPlaceIndexForText
requests that you
can make per second.
Additional requests are
throttled.

During preview release: During preview 1,000 No


Maximum monthly release, the
SearchPlaceIndexForText maximum number of
API requests with SearchPlaceIndexforText
results stored. requests you can make
per month for a Place
index resource with
IntendedUse set to
Storage.

125
Amazon Location Service Developer Guide

Resource Description Quota Adjustable

Rate of The maximum number 10 Yes


CreateTracker API of CreateTracker
requests requests that you
can make per second.
Additional requests are
throttled.

Rate of The maximum number 10 Yes


DeleteTracker API of DeleteTracker
requests requests that you
can make per second.
Additional requests are
throttled.

Rate of The maximum number 10 Yes


DescribeTracker API of DescribeTracker
requests requests that you
can make per second.
Additional requests are
throttled.

Rate of ListTrackers The maximum number 10 Yes


API requests of ListTrackers
requests that you
can make per second.
Additional requests are
throttled.

Rate of The maximum 10 Yes


number of
AssociateTrackerConsumer
API requests AssociateTrackerConsumer
requests that you
can make per second.
Additional requests are
throttled.

Rate of The maximum 10 Yes


number of
DisassociateTrackerConsumer
API requests DisassociateTrackerConsumerrequests
that you can make per
second. Additional
requests are throttled.

Rate of The maximum 10 Yes


ListTrackerConsumersnumber of
API requests ListTrackerConsumers
requests that you
can make per second.
Additional requests are
throttled.

126
Amazon Location Service Developer Guide

Resource Description Quota Adjustable

Rate of The maximum 50 Yes


number of
BatchGetDevicePosition
API requests BatchGetDevicePosition
requests that you
can make per second.
Additional requests are
throttled.

Rate of The maximum 50 Yes


number of
BatchUpdateDevicePosition
API requests BatchUpdateDevicePosition
requests that you
can make per second.
Additional requests are
throttled.

Rate of The maximum 50 Yes


GetDevicePosition number of
API requests GetDevicePosition
requests that you
can make per second.
Additional requests are
throttled.

Rate of The maximum 50 Yes


number of
GetDevicePositionHistory
API requests GetDevicePositionHistory
requests that you
can make per second.
Additional requests are
throttled.

Rate of The maximum 10 Yes


number of
CreateGeofenceCollection
API requests CreateGeofenceCollection
requests that you
can make per second.
Additional requests are
throttled.

Rate of The maximum 10 Yes


number of
DeleteGeofenceCollection
API requests DeleteGeofenceCollection
requests that you
can make per second.
Additional requests are
throttled.

Rate of The maximum 10 Yes


number of
DescribeGeofenceCollection
API requests DescribeGeofenceCollection
requests that you
can make per second.
Additional requests are
throttled.

127
Amazon Location Service Developer Guide

Resource Description Quota Adjustable

Rate of The maximum 50 Yes


BatchDeleteGeofence number of
API requests BatchDeleteGeofence
requests that you
can make per second.
Additional requests are
throttled.

Rate of The maximum 50 Yes


number of
BatchEvaluateGeofences
API requests BatchEvaluateGeofences
requests that you
can make per second.
Additional requests are
throttled.

Rate of The maximum number 50 Yes


BatchPutGeofence of BatchPutGeofence
API requests requests that you
can make per second.
Additional requests are
throttled.

Rate of GetGeofence The maximum number 50 Yes


API requests of GetGeofence
requests that you
can make per second.
Additional requests are
throttled.

Rate of PutGeofence The maximum number 50 Yes


API requests of PutGeofence
requests that you
can make per second.
Additional requests are
throttled.

Rate of The maximum number 50 Yes


ListGeofences API of ListGeofences
requests requests that you
can make per second.
Additional requests are
throttled.

128
Amazon Location Service Developer Guide

Amazon Location APIs


For additional information on API actions, see the following API references:

• Amazon Location Service Maps API reference


• Amazon Location Service Places API reference
• Amazon Location Service Trackers API reference
• Amazon Location Service Geofences API reference

129
Amazon Location Service Developer Guide

Document history
The following table describes the documentation for Amazon Location Service.

• API version: Public preview


• Latest documentation update: Mar 17, 2020

update-history-change update-history-description update-history-date

Public preview release (p. 130) Initial release of the public December 16, 2020
preview documentation.

Tutorial update: Displaying Tutorials for displaying maps March 17, 2020
maps (p. 130) using Mapbox GL for Android
and iOS has been updated to
using MapLibre GL native SDK.

130
Amazon Location Service Developer Guide

AWS glossary
For the latest AWS terminology, see the AWS glossary in the AWS General Reference.

131

You might also like