Reputation: 535
I am using mapbox-gl in a react app to render an interactive map. On map load, I want to center the map on the user's location while keeping the current level of zoom. Centering on the user's location works fine with geolocate.trigger(); but the map automatically zooms too close to the center. I would like to set the zoom level to 6 when the user open the web and every time he/she clicks the geoControl button.
I tried to set the max zoom to 6 as follows but I would still like to allow user to zoom in and out after clicking the button beyond 6.
// const [settings, setSettings] = useState({
// maxZoom: 6,
// // minPitch: 0,
// // maxPitch: 85,
// });
Here is a simplified version of the map component of the app. Any mapbox tips?
App.tsx
import React, { useState, useEffect, useRef } from "react";
import "./App.css";
import MAP, { Marker, Popup, NavigationControl, FullscreenControl, ScaleControl, GeolocateControl } from "react-map-gl";
import "mapbox-gl/dist/mapbox-gl.css";
function App() {
const [viewport, setViewport] = useState({
// latitude: 0,
// longitude: 0,
// width: "100vw",
// height: "100vh",
// zoom: 6,
});
// const [settings, setSettings] = useState({
// maxZoom: 6,
// // minPitch: 0,
// // maxPitch: 85,
// });
const geoControlRef = useRef<mapboxgl.GeolocateControl>(null);
useEffect(() => {
// Activate as soon as the control is loaded
geoControlRef.current?.trigger();
}, [geoControlRef.current]);
return (
<div style={{ width: "100vw", height: "100vh" }}>
<MAP
initialViewState={viewport}
mapboxAccessToken={process.env.REACT_APP_MAPBOX_TOKEN}
mapStyle="mapbox://styles/rikid/clnfluiya03tm01pjc1ncad93"
>
<GeolocateControl position="top-left" ref={geoControlRef} />
<FullscreenControl position="top-left" />
<NavigationControl position="top-left" />
<ScaleControl />
</MAP>
</div>
);
}
export default App;
Upvotes: 0
Views: 71
Reputation: 335
First, save the map object using the Map on 'load' event. Then use the map.easeTo()
method to navigate to the point of your desire using the 'center' property. Set the zoom level using the zoom property, like this:
map.easeTo({
center: [lng, lat],
zoom: 6
});
however, keep in mind that user's location might not be close to the original viewbox of the map, which will result in some changes in the UI.
Here is a snippet for using the map's load event:
const [map, setMap] = useState();
function mapLoadHandler(e) {
setMap(e.target);
}
<Map onLoad={mapLoadHandler} ...otherprops/>
Upvotes: 1