2023-06-01 17:14:09 -07:00

2.8 KiB

useMap

The useMap hook allows a custom component to reference the Map that contains it.

import Tabs from '@theme/Tabs'; import TabItem from '@theme/TabItem';

import {Map, useMap} from 'react-map-gl';

function Root() {
  return (
    <Map ... >
      <NavigationButton />
    </Map>
  );
}

function NavigateButton() {
  const {current: map} = useMap();

  const onClick = () => {
    map.flyTo({center: [-122.4, 37.8]});
  };

  return <button onClick={onClick}>Go</button>;
}
import {Map, useMap} from 'react-map-gl/maplibre';

function Root() {
  return (
    <Map ... >
      <NavigationButton />
    </Map>
  );
}

function NavigateButton() {
  const {current: map} = useMap();

  const onClick = () => {
    map.flyTo({center: [-122.4, 37.8]});
  };

  return <button onClick={onClick}>Go</button>;
}

When used with the MapProvider, this hook can also reference maps that are rendered outside of the current component's direct render tree.

import {MapProvider, Map, useMap} from 'react-map-gl';

function Root() {
  return (
    <MapProvider>
      <Map id="myMapA" ... />
      <Map id="myMapB" ... />
      <NavigateButton />
    </MapProvider>
  );
}

function NavigateButton() {
  const {myMapA, myMapB} = useMap();

  const onClick = () => {
    myMapA.flyTo({center: [-122.4, 37.8]});
    myMapB.flyTo({center: [-74, 40.7]});
  };

  return <button onClick={onClick}>Go</button>;
}
import {MapProvider, Map, useMap} from 'react-map-gl/maplibre';

function Root() {
  return (
    <MapProvider>
      <Map id="myMapA" ... />
      <Map id="myMapB" ... />
      <NavigateButton />
    </MapProvider>
  );
}

function NavigateButton() {
  const {myMapA, myMapB} = useMap();

  const onClick = () => {
    myMapA.flyTo({center: [-122.4, 37.8]});
    myMapB.flyTo({center: [-74, 40.7]});
  };

  return <button onClick={onClick}>Go</button>;
}

See a full example here.

Signature

useMap(): {current?: MapRef, [id: string]: MapRef}

The hook returns an object that contains all mounted maps under the closest MapProvider. The keys are each map's id and the values are the MapRef.

If the hook is used inside a decendent of a Map component, the returned object also contains a current field that references the containing map.

Source

use-map.tsx