Page updated Jan 16, 2024

Work with maps

Note: Please reach out to us for any feedback and/or issues here

Display a map

First, ensure you've provisioned an Amazon Location Service Map resource and configured your app using the instructions in either Configure maps or Use existing resources guide.

Note: For React, you can use the Amplify React MapView component

To render a map, the MapLibre GL and the maplibre-gl-js-amplify libraries are required. MapLibre GL is an open source map rendering library and maplibre-gl-js-amplify library makes it easy to integrate MapLibre with Amplify Geo and handles Authentication.

Add the dependencies to your app:

1npm install maplibre-gl maplibre-gl-js-amplify

Verify the following:

  • maplibre-gl-js-amplify version 4.0.0 or above is installed
  • Any package bundlers (webpack, rollup, etc) are configured to handle css files. Check out the webpack documentation here.

Import the library into your application:

1import { createMap } from 'maplibre-gl-js-amplify';
2import 'maplibre-gl/dist/maplibre-gl.css';

Next, create and render the Map with the help of createMap.

Note: There must be a div with an id="map" on the DOM before making the call to createMap in this way.

1async function initializeMap() {
2 const map = await createMap({
3 container: 'map', // An HTML Element or HTML element ID to render the map in https://maplibre.org/maplibre-gl-js/docs/API/classes/Map/
4 center: [-123.1187, 49.2819], // [Longitude, Latitude]
5 zoom: 11
6 });
7}
8
9initializeMap();

To render a map using a className or something other than the ID you can pass in a reference to the HTML Element itself.

1const element = document.getElementsByClassName("class")[0];
2
3const map = await createMap({
4 container: element,
5 ...
6})

The MapLibre canvas requires a defined height to display properly, otherwise you may end up with a blank screen where the map is supposed to be.

The amplify-map.css file has a few commonly used methods for setting the height of the map component. You can add some of the examples listed to your own styles or directly import amplify-map.css like so:

1import "maplibre-gl-js-amplify/dist/public/amplify-map.css";

To render a map using percentage based height you need to ensure that all ancestor elements to the map container have a height:

1html,
2body,
3#root {
4 /* The ancestors of the map element */
5 height: 100%;
6}
7
8#map {
9 height: 50%;
10}

A map centered on Vancouver

Display markers on map

To display markers on a map, use the drawPoints function. drawPoints expects:

  • sourceName - specifies the layer on which the markers are rendered on. You can edit existing markers by passing the same sourceName
  • coordinate data - (longitude, latitude) the coordinate data of the markers to be displayed
  • a maplibre-gl-js Map - the map object on which to render the markers

First, import the drawPoints method in your app. Your import section should include look like this

1import { drawPoints } from 'maplibre-gl-js-amplify';

The drawPoints method returns ids of the source and layers used to display the markers on the map. These ids can be used for further customization through maplibre-gl-js source, paint, and layer options.

For more information about the parameters and options that can be used with drawPoints check the documentation here.

Next, use the following code snippet when you want to display the markers on the map. Add it to the initializeMap() function if you want the markers to show up on map load.

1map.on('load', function () {
2 drawPoints(
3 'mySourceName', // Arbitrary source name
4 [
5 {
6 coordinates: [-122.483696, 37.833818], // [Longitude, Latitude]
7 title: 'Golden Gate Bridge',
8 address: 'A suspension bridge spanning the Golden Gate'
9 },
10 {
11 coordinates: [-122.477, 37.8105] // [Longitude, Latitude]
12 }
13 ], // An array of coordinate data, an array of Feature data, or an array of [NamedLocations](https://github.com/aws-amplify/maplibre-gl-js-amplify/blob/main/src/types.ts#L8)
14 map,
15 {
16 showCluster: true,
17 unclusteredOptions: {
18 showMarkerPopup: true
19 },
20 clusterOptions: {
21 showCount: true
22 }
23 }
24 );
25});

A map with points

Display different map styles

The getAvailableMaps API fetches information for all maps that are available to be displayed.

This is useful if you would like to give your users a variety of maps styles to choose from.

1import { Geo } from '@aws-amplify/geo';
2
3Geo.getAvailableMaps();

The available maps are returned as an array with the following contents:

1//returns
2[
3 {
4 mapName: 'myAmplifyGeoEsriStreetMap',
5 style: 'VectorEsriStreets'
6 },
7 {
8 mapName: 'myAmplifyGeoEsriTopographicMap',
9 style: 'VectorEsriTopographic'
10 }
11];

You can resize and customize a map with the resize and setStyle functions:

1map.setStyle('myAmplifyGeoEsriTopographicMap'); // map name received from getAvailableMaps()
2map.resize(); // forces the map to re-render

Removing a map from the DOM

When it's time to remove the map from the DOM, you can use the .remove method of the generated map. This will clean up and release all resources associated with the map (DOM elements, event bindings, web workers, and WebGL resources).

1map.remove();

After calling .remove(), you must not call any other methods on the map.

For React users:

Not removing the map on component unmount can cause memory leaks in your application. It's recommended to call .remove() in either the return function of a React useEffect hook or the componentWillUnmount lifecycle hook of a class component.

Add map to html website

To display a map on your html website, add the following scripts to your html webpage.

1<link href="https://cdn.amplify.aws/packages/maplibre-gl/1.15.2/maplibre-gl.css" rel="stylesheet" integrity="sha384-DrPVD9GufrxGb7kWwRv0CywpXTmfvbKOZ5i5pN7urmIThew0zXKTME+gutUgtpeD" crossorigin="anonymous" referrerpolicy="no-referrer"></link>
2<script src="https://cdn.amplify.aws/packages/maplibre-gl/1.15.2/maplibre-gl.js" integrity="sha384-rwYfkmAOpciZS2bDuwZ/Xa/Gog6jXem8D/whm3wnsZSVFemDDlprcUXHnDDUcrNU" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
3<script src="https://cdn.amplify.aws/packages/core/4.3.0/aws-amplify-core.min.js" integrity="sha384-7Oh+5w0l7XGyYvSqbKi2Q7SA5K640V5nyW2/LEbevDQEV1HMJqJLA1A00z2hu8fJ" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
4<script src="https://cdn.amplify.aws/packages/auth/4.3.8/aws-amplify-auth.min.js" integrity="sha384-jfkXCEfYyVmDXYKlgWNwv54xRaZgk14m7sjeb2jLVBtUXCD2p+WU8YZ2mPZ9Xbdw" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
5<script src="https://cdn.amplify.aws/packages/geo/1.1.0/aws-amplify-geo.min.js" integrity="sha384-TFMTyWuCbiptXTzvOgzJbV8TPUupG1rA1AVrznAhCSpXTIdGw82bGd8RTk5rr3nP" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
6<script src="https://cdn.amplify.aws/packages/maplibre-gl-js-amplify/1.1.0/maplibre-gl-js-amplify.umd.min.js" integrity="sha384-7/RxWonKW1nM9zCKiwU9x6bkQTjldosg0D1vZYm0Zj+K/vUSnA3sOMhlRRWAtHPi" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

Next, add a div element with id map anywhere in your webpage where you want to render the map. Include the following code snippet to configure Amplify (update the amplifyconfiguration.json file path accordingly) and instantiate the map.

1<script type="module">
2 import amplifyconfig from './amplifyconfiguration.json' assert { type: 'json' };
3 const { Amplify } = aws_amplify_core;
4 const { createMap } = AmplifyMapLibre;
5 Amplify.configure(amplifyconfig);
6 createMap({
7 container: 'map',
8 center: [-123.1187, 49.2819], // [Longitude, Latitude]
9 zoom: 13
10 });
11</script>

Sample application

1<!DOCTYPE html>
2<html>
3 <head>
4 <meta charset="utf-8">
5 <title>Display a map on a webpage</title>
6 <meta name="viewport" content="initial-scale=1,maximum-scale=1,user-scalable=no">
7 <link href="https://cdn.amplify.aws/packages/maplibre-gl/1.15.2/maplibre-gl.css" rel="stylesheet" integrity="sha384-DrPVD9GufrxGb7kWwRv0CywpXTmfvbKOZ5i5pN7urmIThew0zXKTME+gutUgtpeD" crossorigin="anonymous" referrerpolicy="no-referrer"></link>
8 <script src="https://cdn.amplify.aws/packages/maplibre-gl/1.15.2/maplibre-gl.js" integrity="sha384-rwYfkmAOpciZS2bDuwZ/Xa/Gog6jXem8D/whm3wnsZSVFemDDlprcUXHnDDUcrNU" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
9 <script src="https://cdn.amplify.aws/packages/core/5.0.5/aws-amplify-core.min.js" integrity="sha384-eM2urkpomL9SRm/kuPHZG3XPEItAiUAAyotT/AqlhSus8iAqs/EfHaYy1Jn5ih7K" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
10 <script src="https://cdn.amplify.aws/packages/auth/5.0.5/aws-amplify-auth.min.js" integrity="sha384-H25CFLYd7YHa1Oib73fs3kJN36VhaHHkLjo4AhGrhJ4HuKam05pg2/0t2MR6epun" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
11 <script src="https://cdn.amplify.aws/packages/geo/2.0.5/aws-amplify-geo.min.js" integrity="sha384-Esc9xx0X7ckb/yeYHuYsZGqBB4FwYr98NFHS3BRXLeRE/eB0uVrad2w+G6cGxYb5" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
12 <script src="https://cdn.amplify.aws/packages/maplibre-gl-js-amplify/1.5.0/maplibre-gl-js-amplify.umd.min.js" integrity="sha384-9kJyZavd3Jk6QzHeaLpugVonfZmZZZdixek6uglOwzKtZvDS9K3W4dshw1uswmlV" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
13 <style>
14 body { margin: 0; padding: 0; }
15 #map { position: absolute; top: 0; bottom: 0; width: 100%; }
16 </style>
17 </head>
18 <body>
19 <div id="map"></div>
20 <script type="module">
21 import amplifyconfig from "./amplifyconfiguration.json" assert { type: "json" };
22 const { Amplify } = aws_amplify_core;
23 const { createMap } = AmplifyMapLibre;
24 Amplify.configure(amplifyconfig);
25 createMap({
26 container: "map",
27 center: [-123.1187, 49.2819], // [Longitude, Latitude]
28 zoom: 13,
29 });
30 </script>
31 </body>
32</html>

Map API's

If you want more information about the maps you currently have configured or want a way to switch between maps programmatically, the @aws-amplify/geo package provides API's that return more information about your currently provisioned maps.

First, you need to import Geo from the @aws-amplify/geo package.

1import { Geo } from '@aws-amplify/geo';

getAvailableMaps

getAvailableMaps will return the map resources you currently have provisioned in your Amplify project. You can switch between any of these different maps and display their different map styles.

API

1Geo.getAvailableMaps() => Promise<AmazonLocationServiceMapStyle[]>;

Parameters

  • N/A

Return

The return from getAvailableMaps is a Promise that resolves to AmazonLocationServiceMapStyle[] which is an array of mapName, style, and region.

Each object has the following properties:

  • mapName - name of the map you created.
  • style - the Amazon Location Service style used to create the map.
  • region - the AWS region the map is hosted in.

Note: When changing a map with Amplify and MapLibre the setStyle function should be called with the name of the Location Service map NOT the style. This is because the transformRequest function uses the Location Service map name to make a new request for map tile data.

Example

1const availableMaps = await Geo.getAvailableMaps();
2
3map.setStyle(availableMaps[0].mapName);

getDefaultMap

getDefaultMap is used to get a the default map object.

API

1Geo.getDefaultMap() => Promise<AmazonLocationServiceMapStyle>;

Parameters

  • N/A

Return

The return from getDefaultMap is a Promise that resolves to a AmazonLocationServiceMapStyle object.

The object has the following properties:

  • mapName - name of the map you created.
  • style - the Amazon Location Service style used to create the map.
  • region - the AWS region the map is hosted in.

Example

1const defaultMap = await Geo.getDefaultMap();