### Install react-map-gl with Maplibre Source: https://visgl.github.io/react-map-gl/docs/get-started Installs the react-map-gl library along with maplibre-gl. Requires Node.js version 12 or higher and React version 16.3 or higher. ```bash npm install react-map-gl maplibre-gl ``` -------------------------------- ### Install react-map-gl with Mapbox Source: https://visgl.github.io/react-map-gl/docs/get-started Installs the react-map-gl library along with mapbox-gl and its types. Requires Node.js version 12 or higher and React version 16.3 or higher. ```bash npm install react-map-gl mapbox-gl @types/mapbox-gl ``` -------------------------------- ### Include Mapbox GL JS CSS Source: https://visgl.github.io/react-map-gl/docs/get-started HTML link tag to include the Mapbox GL JS stylesheet. Replace with your mapbox-gl-js version found via `npm ls mapbox-gl`. ```html ``` -------------------------------- ### Include MapLibre GL JS CSS Source: https://visgl.github.io/react-map-gl/docs/get-started HTML link tag to include the MapLibre GL JS stylesheet. Replace with your maplibre-gl version found via `npm ls maplibre-gl`. ```html ``` -------------------------------- ### Basic Mapbox Integration with react-map-gl Source: https://visgl.github.io/react-map-gl/docs/get-started A React component that renders a Mapbox map using react-map-gl. It requires a Mapbox access token and initializes the map with specific view state and map style. ```tsx import * as React from 'react'; import Map from 'react-map-gl/mapbox'; // If using with mapbox-gl v1: // import Map from 'react-map-gl/mapbox-legacy'; import 'mapbox-gl/dist/mapbox-gl.css'; function App() { return ( ); } ``` -------------------------------- ### Basic MapLibre Integration with react-map-gl Source: https://visgl.github.io/react-map-gl/docs/get-started A React component that renders a MapLibre map using react-map-gl. It initializes the map with a specific view state, style, and dimensions. ```tsx import * as React from 'react'; import Map from 'react-map-gl/maplibre'; import 'maplibre-gl/dist/maplibre-gl.css'; function App() { return ( ); } ``` -------------------------------- ### FitBounds Utility Function Usage with viewport-mercator-project Source: https://visgl.github.io/react-map-gl/docs/upgrade-guide Shows how to use the `fitBounds` utility function, now part of the `math.gl` library, via `viewport-mercator-project`. This example demonstrates initializing a `WebMercatorViewport` and then calling `fitBounds` with geographic coordinates and optional padding/offset to calculate the appropriate viewport parameters. The output is an instance of `WebMercatorViewport` containing updated longitude, latitude, and zoom. ```javascript import WebMercatorViewport from 'viewport-mercator-project'; const viewport = new WebMercatorViewport({width: 600, height: 400}); const bound = viewport.fitBounds( [[-73.9876, 40.7661], [-72.9876, 41.7661]], {padding: 20, offset: [0, -40]} ); // => bounds: instance of WebMercatorViewport // {longitude: -73.48760000000007, latitude: 41.268014439447484, zoom: 7.209231188444142} ``` -------------------------------- ### React Map with Many Markers (Initial Setup) Source: https://visgl.github.io/react-map-gl/docs/get-started/tips-and-tricks This setup demonstrates a basic React Map GL component that renders multiple markers. It uses Redux for camera state management and renders markers directly. A limitation is potential performance lag with hundreds of markers due to rerendering on every animation frame. ```javascript import {useSelector, useDispatch} from 'react-redux'; import Map, {Marker} from 'react-map-gl/maplibre'; function MapView() { const viewState = useSelector((s: RootState) => s.viewState); const vehicles = useSelector((s: RootState) => s.vehicles); const dispatch = useDispatch(); const onMove = useCallback(evt => { dispatch({type: 'setViewState', payload: evt.viewState}); }, []); return ( > {vehicles.map(vehicle => ( // vehicle icon ) )} ); } ``` -------------------------------- ### Basic ScaleControl Integration in react-map-gl Source: https://visgl.github.io/react-map-gl/docs/api-reference/mapbox/scale-control Demonstrates how to import and use the ScaleControl component within a react-map-gl application. It requires react and react-map-gl/mapbox, and mapbox-gl CSS. The example initializes a Map component with a Mapbox access token and initial view state, then includes the ScaleControl. ```javascript import * as React from 'react'; import Map, {ScaleControl} from 'react-map-gl/mapbox'; import 'mapbox-gl/dist/mapbox-gl.css'; function App() { return ; } ``` -------------------------------- ### Map Component Import for Mapbox GL (pre-v3.5.0) (v8.0+) Source: https://visgl.github.io/react-map-gl/docs/upgrade-guide For older versions of mapbox-gl (prior to 3.5.0) when upgrading to react-map-gl v8.0+, use the 'react-map-gl/mapbox-legacy' import path. ```javascript import Map from 'react-map-gl/mapbox-legacy'; ``` -------------------------------- ### Map Component Usage with MapLibre GL (v7.0) Source: https://visgl.github.io/react-map-gl/docs/upgrade-guide Example of using the Map component with maplibre-gl in react-map-gl v7.0. Note the explicit 'mapLib' prop is required when not using the dedicated 'react-map-gl/maplibre' import. ```jsx import Map from 'react-map-gl'; import maplibregl from 'maplibre-gl'; function App() { return ; } ``` -------------------------------- ### Map Component Import for Mapbox GL (v8.0+) Source: https://visgl.github.io/react-map-gl/docs/upgrade-guide When using react-map-gl with mapbox-gl version 3.5.0 or greater, imports should be directed to the 'react-map-gl/mapbox' endpoint. ```javascript import Map from 'react-map-gl/mapbox'; ``` -------------------------------- ### Basic Popup Implementation in React Source: https://visgl.github.io/react-map-gl/docs/api-reference/maplibre/popup This snippet demonstrates how to use the Popup component within a react-map-gl application. It shows basic setup including state management for visibility and rendering a simple popup with text content. Dependencies include React, react-map-gl, and maplibre-gl CSS. ```jsx import * as React from 'react'; import {useState} from 'react'; import {Map, Popup} from 'react-map-gl/maplibre'; import 'maplibre-gl/dist/maplibre-gl.css'; function App() { const [showPopup, setShowPopup] = useState(true); return {showPopup && ( setShowPopup(false)}> You are here )} ; } ``` -------------------------------- ### Touch Event Handlers Source: https://visgl.github.io/react-map-gl/docs/api-reference/maplibre/map Handlers for touch events on the map, including start, end, move, and cancel. ```APIDOC ## Touch Event Handlers ### `onTouchStart` - **Description**: Called when a `touchstart` event occurs within the map. If `interactiveLayerIds` is specified, the event will contain an additional `features` field. - **Type**: `(event: MapLayerTouchEvent) => void` ### `onTouchEnd` - **Description**: Called when a `touchend` event occurs within the map. If `interactiveLayerIds` is specified, the event will contain an additional `features` field. - **Type**: `(event: MapLayerTouchEvent) => void` ### `onTouchMove` - **Description**: Called when a `touchmove` event occurs within the map. If `interactiveLayerIds` is specified, the event will contain an additional `features` field. - **Type**: `(event: MapLayerTouchEvent) => void` ### `onTouchCancel` - **Description**: Called when a `touchcancel` event occurs within the map. If `interactiveLayerIds` is specified, the event will contain an additional `features` field. - **Type**: `(event: MapLayerTouchEvent) => void` ``` -------------------------------- ### Accessing Popup Methods via Ref in React Source: https://visgl.github.io/react-map-gl/docs/api-reference/maplibre/popup This example illustrates how to get a reference to the underlying maplibre-gl Popup instance using `useRef` in React. This allows for imperative calls to methods like `trackPointer` after the component has mounted. It requires React, react-map-gl, and maplibre-gl. ```jsx import * as React from 'react'; import {useRef, useEffect} from 'react'; import {Map, Popup} from 'react-map-gl/maplibre'; import maplibregl from 'maplibre-gl'; function App() { const popupRef = useRef(); useEffect(() => { popupRef.current?.trackPointer(); }, [popupRef.current]) return Tooltip ; } ``` -------------------------------- ### Basic Map Component Initialization in React Source: https://visgl.github.io/react-map-gl/docs/api-reference/mapbox/map Demonstrates the basic setup for rendering a map using the react-map-gl Map component. It requires a Mapbox access token and initial view state including longitude, latitude, and zoom level. The component also accepts custom map styles. ```tsx import * as React from 'react'; import Map from 'react-map-gl/mapbox'; import 'mapbox-gl/dist/mapbox-gl.css'; function App() { return ( ); } ``` -------------------------------- ### MapProvider Usage in React Source: https://visgl.github.io/react-map-gl/docs/api-reference/maplibre/map-provider This snippet demonstrates how to use the MapProvider component to wrap the application tree. This setup allows any child component to access map-related functionalities through the context. Ensure that at least one Map component is rendered within this provider for it to be effective. ```javascript import {MapProvider} from 'react-map-gl/maplibre'; function Root() { return ( { // Application tree, somewhere one or more component(s) are rendered } ); } ``` -------------------------------- ### Marker with Popup and Ref Access Source: https://visgl.github.io/react-map-gl/docs/api-reference/maplibre/marker This example shows how to integrate a Marker with a Popup and access its imperative methods using a React ref. It demonstrates creating a Popup instance, attaching it to the Marker, and toggling the popup's visibility via a button click, utilizing `useRef`, `useMemo`, and `useCallback` for efficient management. ```jsx import * as React from 'react'; import {useRef, useMemo, useCallback} from 'react'; import {Map, Marker} from 'react-map-gl/maplibre'; import maplibregl from 'maplibre-gl'; function App() { const markerRef = useRef(); const popup = useMemo(() => { return maplibregl.Popup().setText('Hello world!'); }, []) const togglePopup = useCallback(() => { markerRef.current?.togglePopup(); }, []); return <> ; } ``` -------------------------------- ### Access GeolocateControl Methods via Ref Source: https://visgl.github.io/react-map-gl/docs/api-reference/mapbox/geolocate-control This example shows how to get a reference to the underlying native GeolocateControl instance using `useRef`. This allows imperative access to methods like `trigger()` to activate geolocation on component mount. It requires 'react', 'react-map-gl/mapbox', and 'mapbox-gl' for type definitions. ```jsx import * as React from 'react'; import {useRef, useEffect} from 'react'; import Map, {GeolocateControl} from 'react-map-gl/mapbox'; import type mapboxgl from 'mapbox-gl'; function App() { const geoControlRef = useRef(); useEffect(() => { // Activate as soon as the control is loaded geoControlRef.current?.trigger(); }, [geoControlRef.current]); return ; } ``` -------------------------------- ### Specify Map Library (maplibre-gl) from pre-bundled script Source: https://visgl.github.io/react-map-gl/docs/api-reference/maplibre/map This example illustrates how to configure the Map component to use a pre-bundled maplibre-gl library loaded via a script tag in the HTML. The component accesses the library through the global `window` object. ```html ``` ```typescript import * as React from 'react'; import {Map} from 'react-map-gl/maplibre'; function App() { return ; } ``` -------------------------------- ### Box Zoom Handlers Source: https://visgl.github.io/react-map-gl/docs/api-reference/maplibre/map Handlers for the 'box zoom' interaction, including start, end, and cancel events. ```APIDOC ## Box Zoom Handlers ### `onBoxZoomStart` - **Description**: Called when a "box zoom" interaction starts. - **Type**: `(event: MapBoxZoomEvent) => void` ### `onBoxZoomEnd` - **Description**: Called when a "box zoom" interaction ends. - **Type**: `(event: MapBoxZoomEvent) => void` ### `onBoxZoomCancel` - **Description**: Called when the user cancels a "box zoom" interaction, or when the bounding box does not meet the minimum size threshold. - **Type**: `(event: MapBoxZoomEvent) => void` ``` -------------------------------- ### Basic React Map Marker Example Source: https://visgl.github.io/react-map-gl/docs/api-reference/maplibre/marker This code snippet demonstrates the basic usage of the Marker component within a react-map-gl Map. It initializes a map and places a Marker with a custom image at specific coordinates. If the Marker is mounted with child components, its content is rendered; otherwise, a default marker is used. ```jsx import * as React from 'react'; import {Map, Marker} from 'react-map-gl/maplibre'; import 'maplibre-gl/dist/maplibre-gl.css'; function App() { return ; } ``` -------------------------------- ### Configure Rollup for Mapbox Token Source: https://visgl.github.io/react-map-gl/docs/get-started/tips-and-tricks This snippet demonstrates how to configure Rollup to inject the Mapbox access token using the '@rollup/plugin-replace' plugin. It allows conditional assignment of production or development tokens based on the environment. Ensure '@rollup/plugin-replace' is installed. ```javascript /// rollup.config.js const replace = require('@rollup/plugin-replace').default; module.exports = { ... plugins: [ replace({ 'process.env.MapboxAccessToken': JSON.stringify(process.env.NODE_ENV == 'production' ? process.env.MapboxAccessTokenProd : process.env.MapboxAccessTokenDev) }) ] }; ``` -------------------------------- ### Minimize Map Re-mounting with reuseMaps Source: https://visgl.github.io/react-map-gl/docs/get-started/tips-and-tricks This example illustrates how to prevent frequent re-initialization of map components when navigating between tabs in a single-page application. By setting the `reuseMaps` prop to `true`, the map instance is preserved, reducing billable events from Mapbox GL. This requires the `react-map-gl` library. ```jsx {items.map(renderMarker)} ``` -------------------------------- ### Configure Webpack for Mapbox Token Source: https://visgl.github.io/react-map-gl/docs/get-started/tips-and-tricks This snippet shows how to configure Webpack to inject the Mapbox access token into your application's environment variables. It differentiates between production and development tokens using Node.js environment variables. Ensure 'webpack' is installed as a dev dependency. ```javascript /// webpack.config.js const {DefinePlugin} = require('webpack'); module.exports = { ... plugins: [ new DefinePlugin({ 'process.env.MapboxAccessToken': JSON.stringify(process.env.NODE_ENV == 'production' ? process.env.MapboxAccessTokenProd : process.env.MapboxAccessTokenDev) }) ] }; ``` -------------------------------- ### Accessing Multiple Maps with useMap and MapProvider (React) Source: https://visgl.github.io/react-map-gl/docs/api-reference/maplibre/use-map This example shows how to use the `useMap` hook in conjunction with `MapProvider` to access multiple Map instances by their IDs. This allows a single component to control different maps rendered elsewhere in the component tree. It requires importing `MapProvider`, `Map`, and `useMap` from 'react-map-gl/maplibre'. ```jsx import {MapProvider, Map, useMap} from 'react-map-gl/maplibre'; function Root() { return ( ); } function NavigateButton() { const {myMapA, myMapB} = useMap(); const onClick = () => { myMapA.flyTo({center: [-122.4, 37.8]}); myMapB.flyTo({center: [-74, 40.7]}); }; return ; } ``` -------------------------------- ### Enabling RTLTextPlugin in MapLibre (v7.0+) Source: https://visgl.github.io/react-map-gl/docs/upgrade-guide In react-map-gl v7.0 and later, the default for RTLTextPlugin has been removed for MapLibre. To retain previous behavior, explicitly set the 'RTLTextPlugin' prop with the CDN URL. ```jsx ``` -------------------------------- ### Specify Map Library via Script Tag (HTML/React) Source: https://visgl.github.io/react-map-gl/docs/api-reference/mapbox/map This example illustrates how to reference a pre-bundled Mapbox GL JS library loaded via a script tag in an HTML file. The Map component then accesses the library through the global `window` object. This approach is useful when the map library is loaded externally and not part of the application's JavaScript bundle. ```html ``` ```jsx import * as React from 'react'; import Map from 'react-map-gl/mapbox'; function App() { return ; } ``` -------------------------------- ### Initialize GeolocateControl in react-map-gl Source: https://visgl.github.io/react-map-gl/docs/api-reference/mapbox/geolocate-control This snippet demonstrates how to import and use the GeolocateControl component within a react-map-gl application. It includes basic map setup and places the GeolocateControl on the map. Dependencies include 'react', 'react-map-gl/mapbox', and 'mapbox-gl/dist/mapbox-gl.css'. ```jsx import * as React from 'react'; import Map, {GeolocateControl} from 'react-map-gl/mapbox'; import 'mapbox-gl/dist/mapbox-gl.css'; function App() { return ; } ``` -------------------------------- ### React Map GL: Viewport Width and Height Handling Source: https://visgl.github.io/react-map-gl/docs/upgrade-guide Demonstrates the correct way to handle viewport width and height when using the `ReactMapGL` component. It highlights how `width` and `height` props should be placed after the viewport spread to ensure they override any conflicting values within the viewport object. Incorrect usage can lead to unexpected overrides. ```javascript // BAD: 'width' and 'height' below will be overridden by what's in the 'viewport' object // GOOD: 'width' and 'height' below will override the values in 'viewport' ``` -------------------------------- ### High-Performance Rendering with Symbol Layers Source: https://visgl.github.io/react-map-gl/docs/get-started/tips-and-tricks This example shows how to leverage symbol layers for significantly improved performance, especially when dealing with many data points. It converts vehicle data into GeoJSON and uses a Mapbox `Source` and `Layer` to render them using WebGL, which is more efficient than individual markers. This approach is ideal for complex DOM objects and CSS styling alternatives. ```javascript const vehiclesGeoJSON = useMemo(() => { return { type: 'FeatureCollection', features: vehicles.map(vehicle => turf.point(vehicle.coordinates, vehicle)) }; }, [vehicles]); return ( > ); ``` -------------------------------- ### Referencing Multiple Maps with useMap and MapProvider (React) Source: https://visgl.github.io/react-map-gl/docs/api-reference/mapbox/use-map This example shows how to use the useMap hook in conjunction with MapProvider to access multiple Map instances rendered within the same provider. It allows components to interact with different maps simultaneously, such as updating their centers independently. ```javascript import {MapProvider, Map, useMap} from 'react-map-gl/mapbox'; function Root() { // Note: `useMap` will not work in , only children of can use `useMap` return ( ); } function NavigateButton() { const {myMapA, myMapB} = useMap(); const onClick = () => { myMapA.flyTo({center: [-122.4, 37.8]}); myMapB.flyTo({center: [-74, 40.7]}); }; return ; } ``` -------------------------------- ### React Map GL: Importing Overlays in v1.0 vs v0.6 Source: https://visgl.github.io/react-map-gl/docs/upgrade-guide Illustrates the change in how overlay components are imported in `react-map-gl`. Version 1.0 introduced named exports for overlays like `SVGOverlay`, allowing them to be imported directly from the library. In contrast, version 0.6 required importing these overlays from their relative source paths within the library structure. ```javascript // v1.0 import MapGL, {SVGOverlay} from 'react-map-gl'; // v0.6 import MapGL from 'react-map-gl'; import SVGOverlay from 'react-map-gl/src/api-reference/svg-overlay'; ``` -------------------------------- ### Implement 3D Terrain with TerrainControl in React Source: https://visgl.github.io/react-map-gl/docs/api-reference/maplibre/terrain-control This code demonstrates how to set up a map with 3D terrain enabled using the TerrainControl component from react-map-gl. It defines a map style with raster DEM source and applies it to a Map component, then includes the TerrainControl. The TerrainControl component itself accepts properties like 'position' and options from the underlying maplibre-gl TerrainControl class. ```jsx import * as React from 'react'; import {Map, MapStyle, TerrainControl} from 'react-map-gl/maplibre'; import 'maplibre-gl/dist/maplibre-gl.css'; // https://maplibre.org/maplibre-gl-js/docs/examples/3d-terrain/ const MAP_STYLE: MapStyle = { version: 8, sources: { osm: { type: 'raster', tiles: ['https://a.tile.openstreetmap.org/{z}/{x}/{y}.png'], tileSize: 256, attribution: '© OpenStreetMap Contributors', maxzoom: 19 }, terrainSource: { type: 'raster-dem', url: 'https://demotiles.maplibre.org/terrain-tiles/tiles.json', tileSize: 256 } }, layers: [ { id: 'osm', type: 'raster', source: 'osm' } ], terrain: { source: 'terrainSource', exaggeration: 1 }, sky: {} }; function App() { return ; } ``` -------------------------------- ### Marker with Ref for Imperative Control (e.g., Toggle Popup) Source: https://visgl.github.io/react-map-gl/docs/api-reference/mapbox/marker This example shows how to use a React ref to access the underlying Mapbox GL Marker instance. This allows for imperative control, such as toggling a popup associated with the marker. It utilizes `useRef`, `useMemo`, and `useCallback` hooks for managing the ref and memoizing the popup instance. ```jsx import * as React from 'react'; import {useRef, useMemo, useCallback} from 'react'; import Map, {Marker} from 'react-map-gl/mapbox'; import mapboxgl from 'mapbox-gl'; function App() { const markerRef = useRef(); const popup = useMemo(() => { return mapboxgl.Popup().setText('Hello world!'); }, []) const togglePopup = useCallback(() => { markerRef.current?.togglePopup(); }, []); return <> ; } ``` -------------------------------- ### Specify Map Library with Module Import (React) Source: https://visgl.github.io/react-map-gl/docs/api-reference/mapbox/map This snippet demonstrates how to specify the underlying Mapbox GL JS library for the Map component using a direct module import. It ensures the library is bundled with the application. This is useful for standard setups where bundle size is not a primary concern. ```jsx import * as React from 'react'; import Map from 'react-map-gl/mapbox'; import mapboxgl from 'mapbox-gl'; function App() { return ; } ``` -------------------------------- ### Setting Up Development Environment for react-map-gl Source: https://visgl.github.io/react-map-gl/docs/contributing Instructions to set up the local development environment for react-map-gl. Requires Node.js >= 8 and Yarn. This involves checking out the master branch, bootstrapping dependencies, and running initial tests. ```shell git checkout master yarn bootstrap yarn test ``` -------------------------------- ### Initialize react-map-gl Map Component Source: https://visgl.github.io/react-map-gl/docs/api-reference/maplibre/map This snippet demonstrates the basic initialization of the `Map` component from `react-map-gl/maplibre`. It sets initial view state, map dimensions, and a map style URL. Dependencies include `react`, `react-map-gl/maplibre`, and `maplibre-gl/dist/maplibre-gl.css`. ```jsx import * as React from 'react'; import {Map} from 'react-map-gl/maplibre'; import 'maplibre-gl/dist/maplibre-gl.css'; function App() { return ( ); } ``` -------------------------------- ### Marker Component API Source: https://visgl.github.io/react-map-gl/docs/api-reference/mapbox/marker Documentation for the Marker React component, including its properties, callbacks, and how to use it with imperative methods. ```APIDOC ## Marker Component API ### Description The `Marker` component in `react-map-gl` is a React wrapper for the Mapbox GL JS `Marker` class. It allows you to easily add interactive markers to your map. ### Properties #### Reactive Properties - **`draggable`** (boolean) - Default: `false` If `true`, the marker can be dragged to a new position on the map. - **`latitude`** (number) - Required The latitude of the marker's anchor location. - **`longitude`** (number) - Required The longitude of the marker's anchor location. - **`offset`** (PointLike) - Default: `null` An offset in pixels to apply relative to the marker's center. Negative values move the marker left and up. - **`pitchAlignment`** ('map' | 'viewport' | 'auto') - Default: `'auto'` Specifies how the marker's pitch should align: `'map'` aligns with the map's plane, `'viewport'` aligns with the viewport's plane, and `'auto'` matches `rotationAlignment`. - **`popup`** (Popup | null) - An instance of a Mapbox or Maplibre `Popup` class to attach to this marker. If `null` or `undefined`, any associated popup is removed. - **`rotation`** (number) - Default: `0` The rotation angle of the marker in degrees, relative to its `rotationAlignment`. Positive values rotate clockwise. - **`rotationAlignment`** ('map' | 'viewport' | 'auto') - Default: `'auto'` Specifies how the marker's rotation should align: `'map'` aligns with the map's bearing, `'viewport'` aligns with the viewport (agnostic to map rotation), and `'auto'` is equivalent to `'viewport'`. - **`style`** (CSSProperties) - CSS style overrides applied to the marker's container. #### Callbacks - **`onClick`** ((evt: MapEvent) => void) Callback function executed when the marker is clicked. - **`onDragStart`** ((evt: MarkerDragEvent) => void) Callback function executed when dragging starts (only if `draggable` is `true`). - **`onDrag`** ((evt: MarkerDragEvent) => void) Callback function executed during dragging (only if `draggable` is `true`). - **`onDragEnd`** ((evt: MarkerDragEvent) => void) Callback function executed when dragging ends (only if `draggable` is `true`). ### Other Properties These properties are non-reactive and used only during component mounting. They correspond to options supported by the underlying Mapbox GL JS `Marker` class, such as: - `anchor` - `color` - `scale` - `clickTolerance` ### Methods Imperative methods can be called on the underlying native `Marker` instance using a React ref. For example: ```javascript import * as React from 'react'; import { useRef, useMemo, useCallback } from 'react'; import Map, { Marker } from 'react-map-gl/mapbox'; import mapboxgl from 'mapbox-gl'; function App() { const markerRef = useRef(null); const popup = useMemo(() => { return new mapboxgl.Popup().setText('Hello world!'); }, []); const togglePopup = useCallback(() => { markerRef.current?.togglePopup(); }, []); return ( <> ); } ``` ### Request Body This component does not accept a request body as it is a client-side React component. ### Response This component does not perform network requests and thus does not have defined success or error responses in the traditional API sense. Its output is rendering a marker on a map. ``` -------------------------------- ### Popup Component API Source: https://visgl.github.io/react-map-gl/docs/api-reference/maplibre/popup Documentation for the React Popup component, including its properties, callbacks, and how to access its methods. ```APIDOC ## Popup Component React component that wraps maplibre-gl's Popup class. ### Properties #### Reactive Properties - **anchor** (string) - Optional - A string indicating the part of the popup that should be positioned closest to the coordinate, set via `longitude` and `latitude`. If unset, the anchor will be dynamically set to ensure the popup falls within the map container with a preference for `'bottom'`. - **className** (string) - Optional - Space-separated CSS class names to add to popup container. - **offset** (number | PointLike | Record) - Optional - Default: `null` - A pixel offset applied to the popup's location. - **maxWidth** (string) - Optional - Default: `240px` - A string that sets the CSS property of the popup's maximum width. - **style** (CSSProperties) - Optional - CSS style override that applies to the popup's container. #### Callbacks - **onOpen** (function) - Optional - Called when the popup is opened. - **onClose** (function) - Optional - Called when the popup is closed by the user clicking on the close button or outside (if `closeOnClick: true`). #### Other Properties These properties are not reactive and are only used when the component first mounts. They include any options supported by the native `Popup` class, such as `closeButton`, `closeOnClick`, `closeOnMove`, and `focusAfterOpen`. ### Methods The underlying native `Popup` instance is accessible via a React ref hook. You may use it to call any imperative methods on the `Popup` instance. ``` -------------------------------- ### Popup Component API Source: https://visgl.github.io/react-map-gl/docs/api-reference/mapbox/popup Documentation for the Popup React component, including its properties, callbacks, and how to access the underlying Mapbox GL Popup instance. ```APIDOC ## Popup Component React component that wraps Mapbox GL's Popup class. ### Properties #### Reactive Properties * **`anchor`** (string) - Optional - A string indicating the part of the popup that should be positioned closest to the coordinate. Possible values: `'center' | 'left' | 'right' | 'top' | 'bottom' | 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right'`. If unset, the anchor will be dynamically set. * **`className`** (string) - Optional - Space-separated CSS class names to add to the popup container. * **`offset`** (number | PointLike | Record) - Optional - Default: `null` - A pixel offset applied to the popup's location. * **`maxWidth`** (string) - Optional - Default: `"240px"` - A string that sets the CSS property of the popup's maximum width. * **`style`** (CSSProperties) - Optional - CSS style override that applies to the popup's container. #### Callbacks * **`onOpen`** (function) - Optional - Called when the popup is opened. Receives `evt: PopupEvent`. * **`onClose`** (function) - Optional - Called when the popup is closed by the user clicking on the close button or outside (if `closeOnClick: true`). Receives `evt: PopupEvent`. ### Other Properties These properties are not reactive and are only used when the component first mounts. They correspond to options supported by the `Popup` class (Mapbox | Maplibre), such as: * `closeButton` (boolean) * `closeOnClick` (boolean) * `closeOnMove` (boolean) * `focusAfterOpen` (boolean) ### Methods The underlying native `Popup` instance is accessible via a React ref hook. You may use it to call any imperative methods. Example: ```javascript import * as React from 'react'; import {useRef, useEffect} from 'react'; import Map, {Popup} from 'react-map-gl/mapbox'; import mapboxgl from 'mapbox-gl'; function App() { const popupRef = useRef(); useEffect(() => { popupRef.current?.trackPointer(); }, [popupRef.current]); return Tooltip ; } ``` ``` -------------------------------- ### Map Component Import for MapLibre GL (v7.1+) Source: https://visgl.github.io/react-map-gl/docs/upgrade-guide Upgrading to react-map-gl v7.1+ for MapLibre users requires changing the import path to 'react-map-gl/maplibre'. This change removes the need for the 'mapLib' prop as it defaults to 'maplibre-gl'. ```jsx import Map from 'react-map-gl/maplibre'; function App() { return } ``` -------------------------------- ### Mouse and Touch Event Handlers Source: https://visgl.github.io/react-map-gl/docs/api-reference/mapbox/map Handlers for mouse clicks, context menus, wheel events, and various touch gestures. ```APIDOC ## Mouse and Touch Event Handlers ### Description These handlers are triggered by user interactions with the map, including double-clicks, context menus, mouse wheel events, and touch gestures. ### onDblClick #### Description Called when a pointing device (usually a mouse) is pressed and released twice at the same point on the map in rapid succession. If `interactiveLayerIds` is specified, the event will contain an additional `features` field that contains features under the cursor from the specified layers. #### Method Callback function, typically assigned to the `onDblClick` prop. #### Parameters - **event** (MapLayerMouseEvent) - The event object containing information about the double-click interaction. ### onContextMenu #### Description Called when the right button of the mouse is clicked or the context menu key is pressed within the map. If `interactiveLayerIds` is specified, the event will contain an additional `features` field that contains features under the cursor from the specified layers. #### Method Callback function, typically assigned to the `onContextMenu` prop. #### Parameters - **event** (MapLayerMouseEvent) - The event object containing information about the context menu event. ### onWheel #### Description Called when a wheel event occurs within the map. #### Method Callback function, typically assigned to the `onWheel` prop. #### Parameters - **event** (MapWheelEvent) - The event object containing information about the wheel event. ### onTouchStart #### Description Called when a `touchstart` event occurs within the map. If `interactiveLayerIds` is specified, the event will contain an additional `features` field that contains features under the cursor from the specified layers. #### Method Callback function, typically assigned to the `onTouchStart` prop. #### Parameters - **event** (MapLayerTouchEvent) - The event object containing information about the touch start event. ### onTouchEnd #### Description Called when a `touchend` event occurs within the map. If `interactiveLayerIds` is specified, the event will contain an additional `features` field that contains features under the cursor from the specified layers. #### Method Callback function, typically assigned to the `onTouchEnd` prop. #### Parameters - **event** (MapLayerTouchEvent) - The event object containing information about the touch end event. ### onTouchMove #### Description Called when a `touchmove` event occurs within the map. If `interactiveLayerIds` is specified, the event will contain an additional `features` field that contains features under the cursor from the specified layers. #### Method Callback function, typically assigned to the `onTouchMove` prop. #### Parameters - **event** (MapLayerTouchEvent) - The event object containing information about the touch move event. ### onTouchCancel #### Description Called when a `touchcancel` event occurs within the map. If `interactiveLayerIds` is specified, the event will contain an additional `features` field that contains features under the cursor from the specified layers. #### Method Callback function, typically assigned to the `onTouchCancel` prop. #### Parameters - **event** (MapLayerTouchEvent) - The event object containing information about the touch cancel event. ``` -------------------------------- ### Handle Box Zoom Interactions in react-map-gl Source: https://visgl.github.io/react-map-gl/docs/api-reference/maplibre/map These handlers manage the 'box zoom' interaction, allowing users to draw a rectangle to zoom into a specific area of the map. They cover the start, end, and cancellation of this interaction. ```typescript Map.onBoxZoomStart = (event: MapBoxZoomEvent) => void; Map.onBoxZoomEnd = (event: MapBoxZoomEvent) => void; Map.onBoxZoomCancel = (event: MapBoxZoomEvent) => void; ``` -------------------------------- ### Data and Style Event Handlers Source: https://visgl.github.io/react-map-gl/docs/api-reference/maplibre/map Handlers for map data and style loading and changes. ```APIDOC ## Data and Style Event Handlers ### `onData` - **Description**: Called when any map data loads or changes. See MapDataEvent for more information. - **Type**: `(event: MapStyleDataEvent | MapSourceDataEvent) => void` ### `onStyleData` - **Description**: Called when the map's style loads or changes. See MapDataEvent for more information. - **Type**: `(event: MapStyleDataEvent) => void` ``` -------------------------------- ### Add FullscreenControl to react-map-gl Map Source: https://visgl.github.io/react-map-gl/docs/api-reference/mapbox/fullscreen-control This example demonstrates how to integrate the FullscreenControl component into a react-map-gl map. It requires importing React, mapbox-gl CSS, and the Map and FullscreenControl components from 'react-map-gl/mapbox'. The control is rendered as a child of the Map component. ```jsx import * as React from 'react'; import Map, {FullscreenControl} from 'react-map-gl/mapbox'; import 'mapbox-gl/dist/mapbox-gl.css'; function App() { return ; } ``` -------------------------------- ### Basic AttributionControl Usage in react-map-gl Source: https://visgl.github.io/react-map-gl/docs/api-reference/maplibre/attribution-control This example demonstrates how to use the AttributionControl component within a react-map-gl map. It shows how to import the necessary components, set initial map view state, and disable the default attribution while enabling a custom one. ```javascript import * as React from 'react'; import {Map, AttributionControl} from 'react-map-gl/maplibre'; import 'maplibre-gl/dist/maplibre-gl.css'; function App() { return ; } ```