Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lernen Working with Markers and Popups | Customizing Map Styles and Layers
Practice
Projects
Quizzes & Challenges
Quizzes
Challenges
/
Mapbox Vector Maps in React Apps

bookWorking with Markers and Popups

To make your map more interactive and useful, you can add custom markers and display popups that show information when users interact with those markers. In React, you typically use refs to access the underlying Mapbox map instance and work directly with the Mapbox GL JS APIs.

Begin by creating a React ref for your map container and another for your markers. Once the map is initialized, you can add a marker by creating a new mapboxgl.Marker instance. You can customize the marker's appearance by passing a custom DOM element or by setting options like color and size. Attach the marker to specific coordinates using the setLngLat method, and then add it to the map using the addTo method.

For example, to add a custom marker, you can use the following approach:

  1. Create a ref for the map container and initialize the map inside a useEffect hook;
  2. Create a marker and attach it to the map after the map has loaded;
  3. Optionally, style the marker with a custom HTML element for unique visuals.

This pattern allows you to manage markers dynamically and update them based on your application's state.

To further enhance user interaction, you can display popups with dynamic content when markers are clicked. A popup in Mapbox GL JS is created using the mapboxgl.Popup class. You can set the content of the popup using the setHTML or setText method, and then associate the popup with a marker. When a user clicks the marker, the popup appears at the marker's location, showing information such as a place name, description, or any custom React-rendered HTML.

To implement this, add an event listener to your marker for the 'click' event. In the event handler, create a new popup, set its content dynamically based on your application's data, and use the addTo method to display it on the map. This approach ensures that each marker can display different information, making your map more engaging and informative.

import { useRef, useEffect } from "react";
import mapboxgl from "mapbox-gl";
import "mapbox-gl/dist/mapbox-gl.css";

mapboxgl.accessToken = import.meta.env.VITE_MAPBOX_TOKEN;

function MapWithMarker() {
  const mapContainer = useRef(null);
  const map = useRef(null);

  useEffect(() => {
    if (map.current) return;

    map.current = new mapboxgl.Map({
      container: mapContainer.current,
      style: "mapbox://styles/mapbox/streets-v11",
      center: [-74.5, 40],
      zoom: 9,
    });

    // Create a marker
    const marker = new mapboxgl.Marker({ color: "red" })
      .setLngLat([-74.5, 40])
      .addTo(map.current);

    // Show popup on marker click
    marker.getElement().addEventListener("click", () => {
      new mapboxgl.Popup()
        .setLngLat([-74.5, 40])
        .setHTML("<strong>Hello!</strong><br/>This is a popup.")
        .addTo(map.current);
    });

    return () => map.current.remove();
  }, []);

  return <div ref={mapContainer} style={{ height: "400px" }} />;
}
question mark

How can popups be displayed with dynamic content when a user interacts with a marker on a Mapbox map in a React app?

Select the correct answer

War alles klar?

Wie können wir es verbessern?

Danke für Ihr Feedback!

Abschnitt 3. Kapitel 3

Fragen Sie AI

expand

Fragen Sie AI

ChatGPT

Fragen Sie alles oder probieren Sie eine der vorgeschlagenen Fragen, um unser Gespräch zu beginnen

bookWorking with Markers and Popups

Swipe um das Menü anzuzeigen

To make your map more interactive and useful, you can add custom markers and display popups that show information when users interact with those markers. In React, you typically use refs to access the underlying Mapbox map instance and work directly with the Mapbox GL JS APIs.

Begin by creating a React ref for your map container and another for your markers. Once the map is initialized, you can add a marker by creating a new mapboxgl.Marker instance. You can customize the marker's appearance by passing a custom DOM element or by setting options like color and size. Attach the marker to specific coordinates using the setLngLat method, and then add it to the map using the addTo method.

For example, to add a custom marker, you can use the following approach:

  1. Create a ref for the map container and initialize the map inside a useEffect hook;
  2. Create a marker and attach it to the map after the map has loaded;
  3. Optionally, style the marker with a custom HTML element for unique visuals.

This pattern allows you to manage markers dynamically and update them based on your application's state.

To further enhance user interaction, you can display popups with dynamic content when markers are clicked. A popup in Mapbox GL JS is created using the mapboxgl.Popup class. You can set the content of the popup using the setHTML or setText method, and then associate the popup with a marker. When a user clicks the marker, the popup appears at the marker's location, showing information such as a place name, description, or any custom React-rendered HTML.

To implement this, add an event listener to your marker for the 'click' event. In the event handler, create a new popup, set its content dynamically based on your application's data, and use the addTo method to display it on the map. This approach ensures that each marker can display different information, making your map more engaging and informative.

import { useRef, useEffect } from "react";
import mapboxgl from "mapbox-gl";
import "mapbox-gl/dist/mapbox-gl.css";

mapboxgl.accessToken = import.meta.env.VITE_MAPBOX_TOKEN;

function MapWithMarker() {
  const mapContainer = useRef(null);
  const map = useRef(null);

  useEffect(() => {
    if (map.current) return;

    map.current = new mapboxgl.Map({
      container: mapContainer.current,
      style: "mapbox://styles/mapbox/streets-v11",
      center: [-74.5, 40],
      zoom: 9,
    });

    // Create a marker
    const marker = new mapboxgl.Marker({ color: "red" })
      .setLngLat([-74.5, 40])
      .addTo(map.current);

    // Show popup on marker click
    marker.getElement().addEventListener("click", () => {
      new mapboxgl.Popup()
        .setLngLat([-74.5, 40])
        .setHTML("<strong>Hello!</strong><br/>This is a popup.")
        .addTo(map.current);
    });

    return () => map.current.remove();
  }, []);

  return <div ref={mapContainer} style={{ height: "400px" }} />;
}
question mark

How can popups be displayed with dynamic content when a user interacts with a marker on a Mapbox map in a React app?

Select the correct answer

War alles klar?

Wie können wir es verbessern?

Danke für Ihr Feedback!

Abschnitt 3. Kapitel 3
some-alt