Build a store locator using Mapbox

Adding Mapbox-GL Layer to your Angular project

In the previous post I went through adding and initialising the map within our Angular project, in this demonstration I will walk through adding markers to our Mapbox-gl map by adding a layer

For this demonstration I will use the example provided from Build a store locator using Mapbox GL JS example to display locations.

Initialise the map within a map component

Please view Adding Mapbox-GL to your Angular project post to add and initialise the map in our component.

ngAfterContentInit(): void { this.map = new mapboxgl.Map({ container: 'map', style: this.style, zoom: 13, center: [this.lng, this.lat], accessToken: environment.mapbox.accessToken }); }

You may need to change the centre (center) coordinates to match the Mapbox example so the map centre's on the correct location for this demonstration.

initialise map code

Adding geoJSON and geoJSON types

To display location markers with a layer we need the data as geoJSON.

Install and save the geojson and the geojson types packages.

npm install geojson --save npm install @types/geojson --save

Add geoJSON Constant

Create a new file to hold the geoJSON data in a constant and copy and paste the example geoJSON from the Mapbox example and export.

geojson const

Add layer to map

Import the geoJSON (stores) constant into our map component this will be our layer's data.

import stores

We need to make sure the map has loaded before we add a layer this can be done with the map on function passing in a string for the load event and a function, within that function the layer can be added to the map.

The map layer takes an object with an id, type and a source object that contains a type and the data.

  • id: 'locations' - Id of the layer
  • type: 'circle' - The type of the layer in this case markers on the map
  • source: {} - Object containing below datasource infomation
  • type: 'geojson' - Type of data
  • data: stores - The geoJSON data to be displayed

this.map.on('load', () => { this.map.addLayer({ id: 'locations', type: 'circle', /* Add a GeoJSON source containing place coordinates and information. */ source: { type: 'geojson', data: stores } }); })

Add layer to map

Save the changes and run the application.

ng serve

With a zoom of 10 you should see the below map running in your browser (localhost:4200)

Finished map with store locations