mirror of
https://github.com/visgl/react-map-gl.git
synced 2025-12-08 20:16:02 +00:00
2.3 KiB
2.3 KiB
MapContext
MapContext allows components to interact with InteractiveMap or StaticMap via React's context API.
import * as React from 'react';
import MapGL, {MapContext} from 'react-map-gl';
function CurrentZoomLevel() {
const context = React.useContext(MapContext);
return <div>{context.viewport.zoom}</div>;
}
function App() {
return (
<MapGL latitude={37.78} longitude={-122.41} zoom={8}>
<div style={{position: 'absolute', right: 20, bottom: 20}}>
<CurrentZoomLevel />
</div>
</MapGL>
);
}
It is also possible to consume MapContext outside the map component, if you render your own Provider. Note that not all context fields are available if you use it this way.
import * as React from 'react';
import MapGL, {MapContext} from 'react-map-gl';
function MyComponent() {
const {map} = React.useContext(MapContext);
if (map) {
// do something
}
return null;
}
function App() {
return (
<MapContext.Provider>
<div>
<MapGL latitude={37.78} longitude={-122.41} zoom={8}>
<div style={{position: 'absolute', right: 20, bottom: 20}}>
<CurrentZoomLevel />
</div>
</MapGL>
<div>
<MyComponent />
</div>
</div>
</MapContext.Provider>
);
}
Fields
The context value object may contain the following fields:
map(Map) - the mapbox-gl Map instanceviewport(WebMercatorViewport) - the current viewportcontainer(HTMLDivElement) - the outer container of the map componentonViewportChange(Function) - a callback invoked when a map control requests a viewport change, with the signatureonViewportChange(viewState, interactionState, oldViewState)onViewStateChange(Function) - an alternative callback invoked when a map control requests a viewport change, with the signatureonViewStateChange({viewState, interactionState, oldViewState})eventManager(EventManager) - an EventManager instance used to register all interactive events