Front-End Web & Mobile

Add a map to your webpage with Amazon Location Service

This article was written by Seth Fitzsimmons, Principal Engineer, and Andrew Johnson, Senior Product Manager, Amazon Location Service

A common use case for web development is to add a map to a webpage with a marker on a specific location, such as an office or retail location. Amazon Location is a great solution because it provides a variety of off-the-shelf map styles from two globally recognized partners, Esri and HERE, at low-cost compared to other alternatives. The service also provides geocoding capabilities that you can use to determine the marker position for an address. Here’s how you can combine these capabilities to satisfy this use case.

Overview of solution

For this solution, we’ll be using a map resource to provide the map data to the MapLibre GL SDK (http://maplibre.org) running in a browser. We’ll use a place index resource to perform the conversion from address to location, and Amazon Cognito to manage credentials that will be used to retrieve maps and places data.

JavaScript code running in the user’s browser obtains credentials using the Amazon Cognito Identity Pool ID. The code uses the credentials to sign map data requests to an Amazon Location Service Map resource. The MapLibre GL SDK uses the resulting map data to display an interactive map to the user. The JavaScript code uses the same credentials are to sign geocoding requests to a Place Index resource and uses the resulting location to display a marker on the map.

Walkthrough

There are three main steps to implement this solution:

  • Step 1: Create the map, place index, and Amazon Cognito identity pool resources
  • Step 2: Add the map to an HTML page using JavaScript
  • Step 3 (optional): Use Places to geocode an address and display a marker on the map

CloudFormation launch stack button

Prerequisites

For this walkthrough, you should have the following prerequisites:

Step 1: Create the map, place index, and Cognito identity pool resources

First, you must create a map, place index (if you’re going to use geocoding to find the latitude and longitude of the position to put the marker), and Cognito identity pool and associated AWS Identity and Access Management (IAM) role (so you can authenticate requests to the map and place index resources). For this example, we’ll use the Esri Navigation vector style (VectorEsriNavigation), but you can swap this for any of the other styles referenced here: MapConfiguration – Amazon Location Service. You can create these resources manually but CloudFormation makes this more convenient. The template above will create all the required resources and restrict usage of the resulting identity pool ID to a specified domain using Condition clauses in the IAM role policy. If you’re trying this out with a webserver on your local machine, use localhost:PORT for the domain otherwise you will get HTTP 403 Forbidden errors.

Steps:

  1. Log in to the CloudFormation console
  2. Select Create stack > With new resources (standard)
  3. Add the location of the CloudFormation template: https://amazon-location-blog-assets.s3.amazonaws.com/add-a-map-to-your-webpage/resource-template.yaml
  4. Click Next
  5. Enter a stack name
  6. Enter the domain name where the page will be hosted
  7. Enter a prefix to use for the map, place index, and identity pool resource names
  8. Click Next > Next
  9. Tick the box saying I acknowledge that AWS CloudFormation might create IAM resources. The IAM role and associated policy will be used to restrict access to only the map and place index.
  10. Click Create stack

Example output from AWS CloudFormation:

A screenshot of the CloudFormation Outputs tab. The tab shows the Identity Pool ID, Map Name and Place Index Name that will be used in steps 2 and 3.

Step 2: Add the map to an HTML page

Next we’ll add the map to your webpage. We’ll be using the MapLibre SDK (https://maplibre.org) along with some helper libraries from Amplify and Amazon Location. Remember to replace YOUR_IDENTITY_POOL_ID and YOUR_MAP_NAME with the IdentityPoolID and MapName outputs from the CloudFormation template.

Here’s the code:

<!-- Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -->
<!-- SPDX-License-Identifier: MIT-0 -->
<html>
  <head>
    <link
      href="https://unpkg.com/maplibre-gl@1/dist/maplibre-gl.css"
      rel="stylesheet"
    />
  </head>

  <body>
    <div id="map" style="height: 400px; width: 650px;"/>
    <script src="https://unpkg.com/maplibre-gl@1"></script>
    <script src="https://unpkg.com/amazon-location-helpers@1"></script>
	<script src="https://sdk.amazonaws.com/js/aws-sdk-2.937.0.min.js"></script>
    <script>
      async function initializeMap() {
        const map = await AmazonLocation.createMap(
          {
            identityPoolId: "YOUR_IDENTITY_POOL_ID",
          },
          {
            container: "map",
            center: [-123.1187, 49.2819], // initial map center point
            zoom: 10, // initial map zoom
            style: "YOUR_MAP_NAME",
            hash: true,
          }
        );

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

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

Step 3: Add a marker to the map

Finally, we’ll add a marker to the map. You can do this easily using the following code after map.addControl(). Alternatively, if you already know the position for the marker, you can skip the geocoding call and just use maplibregl.Marker().setLngLat([longitude,latitude]).addTo(map). Remember to replace YOUR_IDENTITY_POOL_ID and YOUR_PLACE_INDEX_NAME with the IdentityPoolID and PlaceIndexName outputs from the CloudFormation template.

// Find the location and put a marker on the map
const location = new AWS.Location({
  credentials: await AmazonLocation.getCredentialsForIdentityPool("YOUR_IDENTITY_POOL_ID"),
  region: "us-east-1"
});

const data = await location.searchPlaceIndexForText({
  IndexName: "YOUR_PLACE_INDEX_NAME",
  Text: "777 Pacific Blvd, Vancouver"
}).promise();

const position = data.Results[0].Place.Geometry.Point;
const marker = new maplibregl.Marker().setLngLat(position).addTo(map);

Cleaning up

To avoid incurring future charges, simply delete the CloudFormation stack. Go to CloudFormation > Stacks, select the stack you created and click Delete.

Conclusion

In this post, we have learned how to quickly and easily add a map and associated marker to a webpage. Amazon Location Service enables you to do this at low cost and leverage the functionality of Amazon Cognito and AWS Identity and Access Management (IAM) to control access to the associated resources.