There are two ways to use a Map:
Map
class.You may clone a full app configuration for this example here.
import * as React from 'react';
import Map from 'react-map-gl';
function App() {
return <Map
initialViewState={{
longitude: -100,
latitude: 40,
zoom: 3.5
}}
mapStyle="mapbox://styles/mapbox/streets-v9"
/>;
}
You may clone a full app configuration for this example here.
import * as React from 'react';
import Map from 'react-map-gl';
function App() {
const [viewState, setViewState] = React.useState({
longitude: -100,
latitude: 40,
zoom: 3.5
});
return <Map
{...viewState}
onMove={evt => setViewState(evt.viewState)}
mapStyle="mapbox://styles/mapbox/streets-v9"
/>;
}
A real-world application likely uses more complicated state flows:
Map
offers props that set basic constraints for the camera, e.g. maxBounds
, minZoom
, maxPitch
. If you need more complicated logic to constrain the camera, you may use it as a controlled component. The following example restricts the map center inside a GeoJSON geofence:
import * as React from 'react';
import Map from 'react-map-gl';
// npm install @turf/turf
import * as turf from '@turf/turf';
// A circle of 5 mile radius of the Empire State Building
const GEOFENCE = turf.circle([-74.0122106, 40.7467898], 5, {units: 'miles'});
function App() {
const [viewState, setViewState] = React.useState({
longitude: -100,
latitude: 40,
zoom: 3.5
});
const onMove = React.useCallback(({viewState}) => {
const newCenter = [viewState.longitude, viewState.latitude];
// Only update the view state if the center is inside the geofence
if (turf.booleanPointInPolygon(newCenter, GEOFENCE)) {
setViewState(newCenter);
}
}, [])
return <Map
{...viewState}
onMove={onMove}
mapStyle="mapbox://styles/mapbox/streets-v9"
/>;
}