Dwight Watson's blog

Use Amazon Location Service to render maps in the browser

June 12, 2022

I've been exploring using Amazon Location Service as an alternative to Google Maps and Mapbox. It has a number of core features like autocomplete, geocoding and maps. I wanted to give the maps a go - but a lot of the documentation seemed pretty tied to AWS's Amplify product which I don't use. It would be overkill for me to import the Amplify SDK just to authenticate the maps so I wanted to get it working with Cognito for guest users.

The documentation will guide you through setting up an Identity Pool which you can configure for unauthenticated access and restrict to your application domains. Once you have your identityPoolId you can use the amazon-location-helpers npm package to wrap up maplibre with authentication handled. First install the required dependencies (including Mapbox, which maplibre appears to depend upon).

yarn add amazon-location-helpers mapbox-gl maplibre-gl

Then use createMap to pop the map on your page. The first argument will be your AWS authentication and the second argument will be passed into maplibre as if you were using it directly.

import maplibregl from "maplibre-gl";
import AmazonLocation from "amazon-location-helpers";
import "maplibre-gl/dist/maplibre-gl.css";

const IDENTITY_POOL_ID = "get-your-credentials";
// const latitude = ...
// const longitude = ...

const map = await AmazonLocation.createMap({
  identityPoolId: IDENTITY_POOL_ID
}, {
  container: document.getElementById("map"),
  center: [longitude, latitude],
  zoom: 10,
  style: "explore.places",
  attributionControl: false;

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

A blog about Laravel & Rails by Dwight Watson;
developer of Roomies.com, myRent.co.nz, High School Notes & StudentVIP.com.au.

Follow me on Twitter, or GitHub.