Amazon Location Developer Guide - Pdfhhhfss
Amazon Location Developer Guide - Pdfhhhfss
Developer Guide
Amazon Location Service Developer Guide
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
iv
Amazon Location Service Developer Guide
v
Amazon Location Service Developer Guide
Key features
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.
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.
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.
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
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:
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:
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).
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.
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.
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
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.
[
[
[-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.
Amazon Location Service Trackers uses the RFC 3339 format, which follows the International
Organization for Standardization (ISO) 8601 format for dates and time.
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
Regions
Region name Region code
9
Amazon Location Service Developer Guide
Endpoints
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:
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
• 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/.
Map Description
12
Amazon Location Service Developer Guide
Esri map styles
Map Description
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.
• 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).
14
Amazon Location Service Developer Guide
Terms of use
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/.
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.
Data attribution
Ensure that you provide attribution to each data provider you use, either on your application or your
documentation.
15
Amazon Location Service Developer Guide
User engagement and geomarketing applications
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)
• 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).
• 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.
• 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
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
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.
When you sign up for an AWS account, you start with a root account.
• 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
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
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.
To grant access to Amazon Location, you must create an IAM policy to assign to IAM users.
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:
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
• 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.
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
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
The following are policy examples for Maps, Places and Trackers. Note that you will need to replace
region and account ID :
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"
}
]
}
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"
}
]
}
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).
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:
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
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)
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.
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
API
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
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"
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"
}
]
}
Topics
• Using the MapLibre library with Amazon Location Service (p. 30)
• Using Tangram with Amazon Location Service (p. 44)
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)
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.
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>
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];
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:
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.
/**
* 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 };
}
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.
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,
});
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.
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.
#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
/**
* 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();
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.
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()
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
<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.
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()
}
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 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))
}
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
return builder.url(urlBuilder.build())
.method(originalRequest.method(), originalRequest.body())
.build()
}
}
}
The Main Activity is responsible for initializing the views that will be displayed to users. This involves:
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
// 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
// initialize Mapbox GL
Mapbox.getInstance(this, null)
HttpRequestUtil.setOkHttpClient(
OkHttpClient.Builder()
.addInterceptor(SigV4Interceptor(credentialProvider, SERVICE_NAME))
.build()
)
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.
4. Navigate to your application's project directory and initialize the Podfile with the CocoaPods
package manager:
pod init
pod 'AWSCore'
40
Amazon Location Service Developer Guide
Step 3: Display a map in your application
end
xed .
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
import SwiftUI
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.
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
42
Amazon Location Service Developer Guide
Step 3: Display a map in your application
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
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
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
}
mapView.logoView.isHidden = true
mapView.attributionButton.isHidden = true
return mapView
}
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.
The following is an example of an AWS CLI command to create a new map resource called
TangramExampleMap using the VectorHEREBerlin style:
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)
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.
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>
This creates an empty page with the necessary prerequisites. The next step guides you through writing
the JavaScript code for your application.
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
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,
},
},
};
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");
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();
}
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"
);
let credentials;
let region;
if (newCredentials != null) {
credentials = newCredentials;
}
if (newRegion != null) {
region = newRegion;
}
});
48
Amazon Location Service Developer Guide
Step 3: Display a map in your application
return fetch(signed);
}
// 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:
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.");
}
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();
initializeMap();
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.
#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];
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");
await reg.active.ready;
if (navigator.serviceWorker.controller == null) {
// trigger a navigate event to active the controller for this page
window.location.reload();
}
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();
initializeMap();
</script>
</body>
</html>
// sw.js
self.importScripts(
"https://unpkg.com/@aws-amplify/core@3.7.0/dist/aws-amplify-core.min.js"
);
let credentials;
let region;
if (newCredentials != null) {
credentials = newCredentials;
}
if (newRegion != null) {
region = newRegion;
52
Amazon Location Service Developer Guide
Step 3: Display a map in your application
}
});
return fetch(signed);
}
// fetch normally
return event.respondWith(fetch(request));
});
This sample is available as part of the Amazon Location Service samples repository on GitHub.
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
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.
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:
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.
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>
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()
}
55
Amazon Location Service Developer Guide
Step 3: Display a map in your application
signer.sign(awsRequest, credentialsProvider.credentials)
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 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))
}
return dr
}
fun toSignedOkHttpRequest(
awsRequest: DefaultRequest<Any>,
originalRequest: Request
): Request {
// copy signed request back into an OkHttp Request
val builder = Request.Builder()
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()
}
}
}
The Main Activity is responsible for initializing the views that will be displayed to users. This involves:
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
setContentView(R.layout.activity_main)
mapView = findViewById(R.id.map)
mapView?.getMapAsync(this, getHttpHandler())
findViewById<TextView>(R.id.attributionView).text = getString(R.string.attribution)
}
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
)
}
}
return DefaultHttpHandler(
builder.addInterceptor(
SigV4Interceptor(
credentialsProvider,
SERVICE_NAME
)
)
)
}
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.
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
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.
2. Navigate to your application's project directory and initialize the Podfile with the CocoaPods
package manager:
pod init
pod 'AWSCore'
pod 'Tangram-es'
end
59
Amazon Location Service Developer Guide
Step 3: Display a map in your application
xed .
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
import SwiftUI
import TangramMap
60
Amazon Location Service Developer Guide
Step 3: Display a map in your application
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
61
Amazon Location Service Developer Guide
Step 3: Display a map in your application
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
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)!
// load the map style and apply scene updates (properties modified at runtime)
mapView.loadScene(from: sceneURL, with: sceneUpdates)
}
return self
}
62
Amazon Location Service Developer Guide
Geocoding, reverse geocoding, and searching
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.
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)
Console
• 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:
API
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
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"
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:
You can incorporate data retrieved from geocoding and reverse geocoding queries to display data on a
map for your web or mobile application.
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
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
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
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
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:
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
Console
API
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
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"
Console
API
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
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
71
Amazon Location Service Developer Guide
Step 2: Start tracking
• 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
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
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"
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.
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"
}
]
}
API
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
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"
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
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"
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
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
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"
• 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.
{
"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
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"
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)
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.
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"
]
}
{
"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
]
}
}
{
"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
]
}
}
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
The following are metrics that Amazon Location Service exports to CloudWatch in the AWS/Location
namespace.
Metric Description
Units: Count
ErrorCount The number of error responses from calls made to a given API endpoint.
Units: Count
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.
Units: Milliseconds
Example
80
Amazon Location Service Developer Guide
Create CloudWatch alarms
For more information, see View Available Metrics in the Amazon CloudWatch User Guide.
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.
Example
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
• 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
}
}
]
}
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)
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.
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
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
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",
}
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
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:
• 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.
To create a Lambda function that publishes position updates to Amazon Location using the console:
• 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. ).
import boto3
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.
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/*"
}
]
}
You can modify this function code, as necessary, to adapt to your own device message schema.
89
Amazon Location Service Developer Guide
Optional: Test your AWS IoT Core rule
{
"payload": {
"deviceid": "thing123",
"timestamp": 1604940328,
"location": { "lat": 49.2819, "long": -123.1187 }
}
}
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)
Console
To view a list of existing map resources using the Amazon Location console
90
Amazon Location Service Developer Guide
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
{
"Entries": [
{
"CreateTime": 2020-10-30T01:38:36Z,
"DataSource": "Esri",
"Description": "string",
"MapName": "ExampleMap",
"UpdateTime": 2020-10-30T01:38:36Z
}
],
"NextToken": "1234-5678-9012"
}
CLI
The following example is an AWS CLI to get a list of map resources in the AWS account.
Console
To view the details of a map resource using the Amazon Location console
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
{
"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
The following example is an AWS CLI to get the map resource details for ExampleMap.
Console
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
HTTP/1.1 200
CLI
92
Amazon Location Service Developer Guide
Place indexes
The following example is an AWS CLI command to delete the map resource ExampleMap.
Console
To view a list of place index resources using the Amazon Location console
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
{
"Entries": [
{
"CreateTime": 2020-10-30T01:38:36Z,
"DataSource": "Esri",
"Description": "string",
"IndexName": "ExamplePlaceIndex",
"UpdateTime": 2020-10-30T01:40:36Z
}
],
"NextToken": "1234-5678-9012"
}
CLI
The following example is an AWS CLI to get a list of place index resources in the AWS account.
93
Amazon Location Service Developer Guide
Place indexes
Console
To view the details of a place index resource using the Amazon Location console
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
{
"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
The following example is an AWS CLI to get the place index resource details for
ExamplePlaceIndex.
Console
94
Amazon Location Service Developer Guide
Geofence collections
Warning
This action deletes the resource permanently. You can't undo this action.
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
HTTP/1.1 200
CLI
The following example is an AWS CLI command to delete the place index resource
ExamplePlaceIndex.
Console
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
{
"Entries": [
{
"CollectionName": "ExampleCollection",
"CreateTime": 2020-09-30T22:59:34.142Z,
"Description": "string",
"UpdateTime": 2020-09-30T23:59:34.142Z
}
],
"NextToken": "1234-5678-9012"
}
CLI
The following example is an AWS CLI to get a list of geofence collections in the AWS account.
Console
To view the details of a geofence collection using the Amazon Location console
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
{
"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
The following example is an AWS CLI to get the geofence collection details for
ExampleCollection.
Console
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
HTTP/1.1 200
CLI
The following example is an AWS CLI command to delete the geofence collection
ExampleCollection.
97
Amazon Location Service Developer Guide
Geofence collections
--collection-name "ExampleCollection"
Console
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
{
"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
The following example is an AWS CLI to get a list of geofences stored in the geofence collection
ExampleCollection.
98
Amazon Location Service Developer Guide
Geofence collections
Console
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
{
"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
The following example is an AWS CLI to get the geofence collection details for
ExampleCollection.
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
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" ]
}
HTTP/1.1 200
CLI
The following example is an AWS CLI command to delete geofences from the geofence collection
ExampleCollection.
Console
100
Amazon Location Service Developer Guide
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
{
"Entries": [
{
"CreateTime": 2020-10-02T19:09:07.327Z,
"Description": "string",
"TrackerName": "ExampleTracker",
"UpdateTime": 2020-10-02T19:10:07.327Z
}
],
"NextToken": "1234-5678-9012"
}
CLI
The following example is an AWS CLI to get a list of trackers in your AWS account.
Console
To disassociate a tracker from an associated geofence collection using the Amazon Location
console
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
HTTP/1.1 200
CLI
The following example is an AWS CLI command to disassociate a tracker from an associated
geofence collection.
Console
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
{
"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
The following example is an AWS CLI to get tracker details for 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
API
Use the DeleteTracker action from the Amazon Location Tracker APIs.
DELETE /tracking/v0/trackers/ExampleTracker
HTTP/1.1 200
CLI
The following example is an AWS CLI command to delete the tracker ExampleTracker.
103
Amazon Location Service Developer Guide
Security
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.
• 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 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)
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:
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.
• 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.
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
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).
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.
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.
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.
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) 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.
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.
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.
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.
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": "*"
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
"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.
113
Amazon Location Service Developer Guide
Identity-based policy examples
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.
• 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.
{
"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": "*"
}
]
}
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)
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"
]
}
]
}
In this example, the following policy grants permission to the following actions:
{
"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/*"
}
]
}
{
"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"
}
]
}
{
"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"
}
]
}
{
"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"
}
]
}
In this example, in addition to granting access to PlaceIndex, the following policy also grants
permission to the following actions:
{
"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"
}
]
}
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)
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.
In this case, Mateo asks his administrator to update his policies to allow him to access the Map resource
using the geo:CreateMap action.
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.
To get started right away, see Creating your first IAM delegated user and group in the IAM User Guide.
• 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.
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.
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.
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.
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.
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
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.
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
123
Amazon Location Service Developer Guide
124
Amazon Location Service Developer Guide
125
Amazon Location Service Developer Guide
126
Amazon Location Service Developer Guide
127
Amazon Location Service Developer Guide
128
Amazon Location Service Developer Guide
129
Amazon Location Service Developer Guide
Document history
The following table describes the documentation for Amazon Location Service.
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