Skip to main content

Add points to a web map, part 3: add interactivity

Tutorial series: Add points to a web map
This series of tutorials teaches you how to add markers representing point data to a web map using the Mapbox Studio dataset editor, the Mapbox Studio style editor, and Mapbox GL JS:- Part 1: Prepare your data- Part 2: Create a map style- Part 3: Add interactivity

Part 3: Add interactivity

This part of the tutorial series focuses on using Mapbox GL JS, a JavaScript library, and will require you to write code. In this tutorial, you will learn how to:

  • Add a Mapbox GL JS map to a webpage
  • Use a custom style for the map
  • Add interactivity to your map so users can click a marker and see a popup

The final product for this tutorial series is an interactive web map with markers and popups, as shown in the map below.

Getting started

There are a few resources you will need to follow along with this tutorial:

  • Mapbox access token. You must use a token to associate a map with your account. You can find your access tokens on your Access tokens page.
  • Development environment. This tutorial requires writing code. For tips on how to get started, see Get ready to write code below.
  • A 'Chicago Parks' custom map style. You can use your own style if you completed Part 2 of this tutorial series or you can use this example style containing markers for 10 Chicago parks:


Get ready to write code
To write HTML, CSS, and JavaScript code, you will need a development environment, including a text or code editor. We recommend downloading and installing Sublime Text or Visual Studio Code.To use Mapbox GL JS, our JavaScript library, you will also need some familiarity with JavaScript and front-end development concepts. If you are new to writing code, you may want to explore JavaScript learning resources before you begin building with Mapbox GL JS.

Add a map to a webpage

In this section, you will create a webpage and add a Mapbox map to it.

Create an HTML file

  1. Open your text editor and create a new blank file.
  2. Copy the code below and paste it into your file.
  3. Save your file as index.html.
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<title>Points on a map</title>
<meta name='viewport' content='width=device-width, initial-scale=1' />
<script src='https://api.tiles.mapbox.com/mapbox-gl-js/v3.1.0/mapbox-gl.js'></script>
<link href='https://api.tiles.mapbox.com/mapbox-gl-js/v3.1.0/mapbox-gl.css' rel='stylesheet' />
<style>
body {
margin: 0;
padding: 0;
}

#map {
position: absolute;
top: 0;
bottom: 0;
width: 100%;
}
</style>
</head>
<body>
<div id='map'></div>
<script>
// The value for 'accessToken' begins with 'pk...'
mapboxgl.accessToken = ' <UserAccessToken /> ';
const map = new mapboxgl.Map({
container: 'map',
// Replace YOUR_STYLE_URL with your style URL.
style: 'YOUR_STYLE_URL',
center: [-87.661557, 41.893748],
zoom: 10.7
});

// Code from the next step will go here.

</script>
</body>
</html>

Initialize the map

To initialize your map so it shows on your webpage, you must change some values inside the code you copied in the previous step.

  1. Replace the placeholder string YOUR_STYLE_URL with a style URL for a 'Chicago Parks' style as described in Getting started.
  1. Check the value for mapboxgl.accessToken. If you see the string <your access token here> replace it with your Mapbox access token as described in Getting started.
  2. Save your index.html file and open it in a web browser. You should see a map displaying markers in your browser window.

Add popups to the map

Now that you have a webpage with a Mapbox map, you can add more code to make your markers interactive.

Add an event listener

In this step, you will set an event listener that will respond when a user clicks on your map by performing an action that you specify.

  1. Copy the code below and paste it into your HTML file after the closing parenthesis ); of your Map initialization block, but before the closing </script> tag.
  2. Inside the options argument passed to queryRenderedFeatures, replace the placeholder string YOUR_LAYER_NAME with the name of your layer in your map style that contains your 'Chicago Parks' markers. This is probably chicago-parks if you completed Part 1 of this tutorial series or if you are using the example style URL provided above in Getting started.
/* 
Add an event listener that runs
when a user clicks on the map element.
*/
map.on('click', (event) => {
// If the user clicked on one of your markers, get its information.
const features = map.queryRenderedFeatures(event.point, {
layers: ['YOUR_LAYER_NAME'] // replace with your layer name
});
if (!features.length) {
return;
}
const feature = features[0];

// Code from the next step will go here.
});

Now when a user clicks on your map, your function will pass the point property of the click event to the Mapbox GL JS method queryRenderedFeatures() to check if the click happened on one of the markers in your 'Chicago Parks' layer. If it did, your function creates a constant called feature to hold that feature's information for the next step.

Create and add the popups

In this step, you will add more code to your listener function so that when a user clicks on a 'Chicago Parks' marker, a popup will appear above it.

  1. Copy the code below and paste it before the closing bracket } of the function you added in the last step.
/* 
Create a popup, specify its options
and properties, and add it to the map.
*/
const popup = new mapboxgl.Popup({ offset: [0, -15] })
.setLngLat(feature.geometry.coordinates)
.setHTML(
`<h3>${feature.properties.title}</h3><p>${feature.properties.description}</p>`
)
.addTo(map);

Because the code above is contained inside your event listener's callback function, it will run only when a user clicks on your map. The code uses four methods to create a Popup, define its position and contents, and add it to the map:

  • mapboxgl.Popup() creates a new popup and accepts an options object, { offset: [0, -15] }, that you can use to configure the popup's behavior. In this example, offset adjusts the vertical position of the popup's anchor so the popup doesn't cover up the marker below it.
  • Popup.setLngLat() sets the geographic location of the popup's anchor using the feature's coordinates property.
  • Popup.setHTML() sets the popup's content to the provided string. While you can provide any string, you will most often provide HTML as a string. The code block above combines HTML code with the feature's title and description properties.
  • Popup.addTo(map) associates the popup with your map so it can open when a user clicks on one of the map's markers.
  1. Save your changes and refresh your webpage in your browser. Click on the markers to show popups containing titles and descriptions for each marker.

Final product

If you have completed all three parts of this tutorial series, you have created an interactive web application with Mapbox GL JS, including custom data, a custom style, and custom user interactions. Click on the map markers below to see the interactive popups.

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Demo: Add points to a web map</title>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<script src="https://api.tiles.mapbox.com/mapbox-gl-js/v3.1.0/mapbox-gl.js"></script>
<link
href="https://api.tiles.mapbox.com/mapbox-gl-js/v3.1.0/mapbox-gl.css"
rel="stylesheet"
/>
<style>
body {
margin: 0;
padding: 0;
}

#map {
position: absolute;
top: 0;
bottom: 0;
width: 100%;
}
</style>
</head>
<body>
<div id="map"></div>
<script>
mapboxgl.accessToken = '<your access token here>';
const map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/examples/clg45vm7400c501pfubolb0xz',
center: [-87.661557, 41.893748],
zoom: 10.7
});

map.on('click', (event) => {
const features = map.queryRenderedFeatures(event.point, {
layers: ['chicago-parks']
});
if (!features.length) {
return;
}
const feature = features[0];

const popup = new mapboxgl.Popup({ offset: [0, -15] })
.setLngLat(feature.geometry.coordinates)
.setHTML(
`<h3>${feature.properties.title}</h3><p>${feature.properties.description}</p>`
)
.addTo(map);
});
</script>
</body>
</html>

Next steps

To learn about more things you can do with Mapbox Studio, explore the Mapbox Studio manual. For more information on Mapbox GL JS and how it works, read our guide on how Mapbox web applications work.

Was this page helpful?