This is part 2 of a multi-part React tutorial on Mapbox.

In part 1, we simply focus on displaying a map and adding a geocoder to look up addresses. We even managed to re-center our map to the selected address. Note: Here is the link to Part 1 in case you missed it.

While very nice, a map doesn’t quite feel as complete without markers to show us what’s important.

So let’s get started!


Display a marker

We have our map and our geocoder. We can look up addresses and select one.

Let’s now display a marker on that particular address. Our react-map-gl library also comes with a handy Marker component.

import ReactMapGL, { Marker } from 'react-map-gl';

This component will allow us to display a marker if we have selected an address. In our state, we will add a tempMarker set to null and in our onSelected function, we will set tempMarker to the latitude/longitude it returned.

onSelected = (viewport, item) => {
      this.setState({
        viewport,
        tempMarker: {
          name: item.place_name,
          longitude: item.center[0],
          latitude: item.center[1]
        }
      })
}

Then inside our ReactMapGL component, we can display our Marker component:

{ tempMarker &&
    <Marker
      longitude={tempMarker.longitude}
      latitude={tempMarker.latitude}>
      <div className="marker temporary-marker"><span></span></div>
    </Marker>
}

Our Marker component takes a latitude and a longitude along with its content. You can style your marker however you want. I am simply going to use an empty div with some CSS to make it look like a normal marker.

#react #tutorial #programming #mapbox #javascript

How to display Markers on a Mapbox Map — Mapbox/React Tutorial Part 2
3.75 GEEK