Display Geolocations Using Mapbox

Lauren Cunningham
Geek Culture
Published in
5 min readMay 14, 2021

JavaScript-based Library for Mapping Anything!

https://github.com/laurencun/react-mapbox-geocoder

Getting Started

Geolocation features have many uses in modern applications. The user might be looking for businesses closeby, planning a trip or tracking their workout trail. There are tons of use cases where being able to show and update locations on a map is necessary.

GoogleMaps API is a popular choice, but there’s another tool that I highly recommend called Mapbox. It comes with an extensive list of properties that allow you to customize your view and there’s some fantastic built-in styling features as well. Mapbox GL JS is JavaScript-based as you may have guessed by its name. Its magic comes from the integration of the WebGL API, which allows us to display 2D and 3D graphics that the user can interact with.

React developers can access a suite of components that are compatible with Mapbox through React-Map-GL. Simply install react-map-gl and import ReactMapGL in the file where it is to be rendered. Within the ReactMapGL component, you can add width and height, your mapbox API access token and other helpful properties such as onViewPortChange which adjusts the area that the map covers.

Render a Map

To get started, you’ll need to make sure you have downloaded the mapbox-gl-js library and import it at the top of the file that will be rendering the map.

import mapboxgl from 'mapbox-gl'

Next you’ll need to request an API access token by creating an account on the Mapbox site. Don’t worry, it’s pretty painless. Once you have signed up, you’ll see a blue ‘create a token’ button in your account page. This will give you an access token that you can use to reach the API endpoints from your application. Add the token to a variable.

mapboxgl.accessToken = 'your-access-token-here'

The last thing you need is a style URL. This is crucial for ensuring the map is displayed as you have specified. There are a couple of ways to define the style source. You can include this link tag in the head of your HTML file:

<link href='https://api.mapbox.com/mapbox-gl-js/v2.2.0/mapbox-gl.css' rel='stylesheet' />

Or you can define the style property within your map object like so:

const map = new mapboxgl.Map({container: 'map', // container ID
style: 'mapbox://styles/mapbox/streets-v11', // style URL
center: [-74.5, 40], // starting position [lng, lat]
zoom: 9 // starting zoom
});

As you can see, the container is pointing to an element with an id of ‘map’ that will house the map object. There are many style URL variations that we can choose from. You can find them in the documentation here. This URL points to a map style that includes streets. There is also dark and light mode, satellite view, navigation settings and more. You can even get really fancy and create your own style URL with Mapbox Studio!

Add Markers

The Marker method can be called on your mapboxgl to instantiate a new marker. Once a the marker has been created you can include the location coordinates by using the setLngLat method. The addTo method takes the map object as an argument and displays the marker on top of it.

var marker = new mapboxgl.Marker({
color: "#FFFFFF",
draggable: true
}).setLngLat([30.5, 50.5]).addTo(map);

This is a great start, but don’t expect to see a marker appear yet. We need to give the marker some styling attributes. In your CSS file, you can refer to the marker class and add width, height, background color, etc. Here’s an example to help you get started:

.marker{
display:flex;
justify-content:center;
align-items:center;
box-sizing:border-box;
width: 30px;
height: 30px;
color:#fff;
background: #4D2D73;
border:solid 2px;
border-radius: 0 70% 70%;
box-shadow:0 0 2px #000;
cursor: pointer;
transform-origin:0 0;
transform: rotateZ(-135deg);
}

Map Data

Let’s say you want to represent data for all the Starbuck locations within your map’s viewport. You have the addresses of the physical stores, but need the exact coordinates to display markers. This is where Mapbox’s Geocoding API comes in handy. Forward geocoding allows us to make a get request providing the location name, such as an address or city name and get a JSON object that includes the latitude and longitude of that location. We can also find addresses by making a get request that provides specific coordinates.

To get familiar with this process and the variations of requests that can be made, you can use the Mapbox Geocoding API Playground. In the Starbucks example, we could iterate over a list of Starbuck locations and make a request to the forward geocoding endpoint, then map the coordinates we receive to a marker.

Create Pop-up

Great, now our user can see all the Starbuck locations… but there’s still a bit more that we can do to make our map more user-friendly and interactive. When the user needs a little more information on a specific location, they should be able to click on a marker to view details like contact information, the address and store hours.

We can add a pop-up to our markers by mapping our Starbucks store object to a marker with a unique key that points to the specific store and an openPopup property that points to a function. The openPopup function will need to keep the store object in a variable like selectedLocation (or state if using React). That variable will be mapped to a pop-up element (or component in React) to display the information we want to show.

Of course, we will also need to be able to close the pop up. Our pop-up element needs a closePopup property pointing to a function that will remove this store location from the state and in doing so, effectively closing the pop-up.

That might sound like a lot of work but luckily React-Mapbox-GL comes with a pop-up component that includes all the basic styling we need. All you have to do is import Popup from react-map-gl, add the popup component within the ReactMapGL component, give it a closePopup property that points to a function to remove that store from the state and voila!

More Resources

There’s so much more that you can do with Mapbox. This article just scratches the surface. I encourage you to dig in and play around with your own map styling, geocoding and other API requests. You can get the current user’s location, show the distance between the user’s location and a marker or allow the user to perform a search and add new markers.

The documentation for Mapbox is fairly detailed and includes sample code and tutorials. Keep in mind that React-Map-GL is a wrapper for Map-GL and does have some limitations. If your component is not displaying as expected, try using the getMap function to access the Map-GL API and its properties.

I’ll leave some documentation and the link to my github repo with examples of searching, adding markers and mapping existing data below. Enjoy!

--

--