Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Aprende Custom Controls and UI Integration | Advanced Map Interactivity
Mapbox Vector Maps in React Apps

bookCustom Controls and UI Integration

To enhance user experience in your React app, you can add Mapbox's built-in controls such as navigation, fullscreen, and geolocate controls. These controls provide out-of-the-box functionality for common map interactions. To add a navigation control, first ensure you have access to the map instance after it loads. You can then call map.addControl() with the specific control you want. For example, to add navigation and fullscreen controls, you might use:

import mapboxgl from "mapbox-gl";
import { useRef, useEffect } from "react";

function MapComponent() {
  const mapContainer = useRef(null);
  const mapRef = useRef(null);

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

    mapRef.current.addControl(new mapboxgl.NavigationControl(), "top-right");
    mapRef.current.addControl(new mapboxgl.FullscreenControl(), "top-right");

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

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

This approach allows you to position built-in controls anywhere on the map. You can also add the geolocate control or scale control in the same way by using their respective constructors.

Sometimes you need map controls that are specific to your application's needs, such as a button that resets the map view to a default location. You can create a custom React component that interacts with the map instance held in state or a ref. Here is a simple example of a custom control:

import { useRef, useEffect, useState } from "react";
import mapboxgl from "mapbox-gl";

function MapWithReset() {
  const mapContainer = useRef(null);
  const mapRef = useRef(null);
  const [mapLoaded, setMapLoaded] = useState(false);

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

    mapRef.current.on("load", () => setMapLoaded(true));

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

  const handleReset = () => {
    if (mapRef.current) {
      mapRef.current.flyTo({ center: [-74.5, 40], zoom: 9 });
    }
  };

  return (
    <div style={{ position: "relative", height: "400px" }}>
      <div ref={mapContainer} style={{ height: "100%" }} />
      {mapLoaded && (
        <button
          onClick={handleReset}
          style={{
            position: "absolute",
            top: 10,
            left: 10,
            background: "#fff",
            border: "none",
            padding: "8px 12px",
            borderRadius: "4px",
            cursor: "pointer",
            boxShadow: "0 2px 6px rgba(0,0,0,0.15)"
          }}
        >
          Reset View
        </button>
      )}
    </div>
  );
}

This pattern lets you fully integrate custom controls into your app's design, using React to manage both the UI and the map's behavior. Your custom control can trigger any map action, such as panning, zooming, or changing styles, based on your application's requirements.

question mark

Which of the following best describes the difference between built-in and custom controls when integrating Mapbox with React?

Select the correct answer

¿Todo estuvo claro?

¿Cómo podemos mejorarlo?

¡Gracias por tus comentarios!

Sección 4. Capítulo 3

Pregunte a AI

expand

Pregunte a AI

ChatGPT

Pregunte lo que quiera o pruebe una de las preguntas sugeridas para comenzar nuestra charla

bookCustom Controls and UI Integration

Desliza para mostrar el menú

To enhance user experience in your React app, you can add Mapbox's built-in controls such as navigation, fullscreen, and geolocate controls. These controls provide out-of-the-box functionality for common map interactions. To add a navigation control, first ensure you have access to the map instance after it loads. You can then call map.addControl() with the specific control you want. For example, to add navigation and fullscreen controls, you might use:

import mapboxgl from "mapbox-gl";
import { useRef, useEffect } from "react";

function MapComponent() {
  const mapContainer = useRef(null);
  const mapRef = useRef(null);

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

    mapRef.current.addControl(new mapboxgl.NavigationControl(), "top-right");
    mapRef.current.addControl(new mapboxgl.FullscreenControl(), "top-right");

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

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

This approach allows you to position built-in controls anywhere on the map. You can also add the geolocate control or scale control in the same way by using their respective constructors.

Sometimes you need map controls that are specific to your application's needs, such as a button that resets the map view to a default location. You can create a custom React component that interacts with the map instance held in state or a ref. Here is a simple example of a custom control:

import { useRef, useEffect, useState } from "react";
import mapboxgl from "mapbox-gl";

function MapWithReset() {
  const mapContainer = useRef(null);
  const mapRef = useRef(null);
  const [mapLoaded, setMapLoaded] = useState(false);

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

    mapRef.current.on("load", () => setMapLoaded(true));

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

  const handleReset = () => {
    if (mapRef.current) {
      mapRef.current.flyTo({ center: [-74.5, 40], zoom: 9 });
    }
  };

  return (
    <div style={{ position: "relative", height: "400px" }}>
      <div ref={mapContainer} style={{ height: "100%" }} />
      {mapLoaded && (
        <button
          onClick={handleReset}
          style={{
            position: "absolute",
            top: 10,
            left: 10,
            background: "#fff",
            border: "none",
            padding: "8px 12px",
            borderRadius: "4px",
            cursor: "pointer",
            boxShadow: "0 2px 6px rgba(0,0,0,0.15)"
          }}
        >
          Reset View
        </button>
      )}
    </div>
  );
}

This pattern lets you fully integrate custom controls into your app's design, using React to manage both the UI and the map's behavior. Your custom control can trigger any map action, such as panning, zooming, or changing styles, based on your application's requirements.

question mark

Which of the following best describes the difference between built-in and custom controls when integrating Mapbox with React?

Select the correct answer

¿Todo estuvo claro?

¿Cómo podemos mejorarlo?

¡Gracias por tus comentarios!

Sección 4. Capítulo 3
some-alt