WebMercatorViewport: Replacement in react-map-gl v7 ? #1849
-
I build a map, that has to calculate and adapt the center and zoom level, according to an array of points who should be visible. All examples I found on the web use onViewportChange and WebMercatorViewport. But both of those were removed in v7 of react-map-gl. So instead of onViewportChange I use onMove. But what would now be the officially recommended replacement for WebMercatorViewport? The documentation only mentions
At the moment, I still use it and import it from deck.gl. But is there something different now, that is recommended instead? import Map, { Marker } from "react-map-gl";
import { WebMercatorViewport } from "@deck.gl/core";
import { useWindowSize } from "@react-hook/window-size";
import { useState } from "react";
import "mapbox-gl/dist/mapbox-gl.css";
import { ImLocation2 } from "react-icons/im";
const testCoordinatesArray = [
{ longitude: 13.377722, latitude: 52.516272, name: "Berlin" },
{ longitude: -0.119722, latitude: 51.503333, name: "London" },
{ longitude: 2.352222, latitude: 48.856614, name: "Paris" },
{ longitude: -73.94, latitude: 40.7127, name: "New York" },
];
const applyToArray = (func, array) => func.apply(Math, array);
const getBoundsForPoints = (points) => {
// Calculate corner values of bounds
const pointsLong = points.map((point) => point.longitude);
const pointsLat = points.map((point) => point.latitude);
const cornersLongLat = [
[applyToArray(Math.min, pointsLong), applyToArray(Math.min, pointsLat)],
[applyToArray(Math.max, pointsLong), applyToArray(Math.max, pointsLat)],
];
const [width, height] = useWindowSize();
// Use WebMercatorViewport to get center longitude/latitude and zoom
const viewport = new WebMercatorViewport({
width: width || 800,
height: height || 600,
}).fitBounds(cornersLongLat, { padding: Math.round(width * 0.05) || 30 }); // Can also use option: offset: [0, -100]
const { longitude, latitude, zoom } = viewport;
return { longitude, latitude, zoom };
};
export default function MapTestCenter() {
const bounds = getBoundsForPoints(testCoordinatesArray);
const [viewport, setViewport] = useState({
width: "100%",
height: "100%",
...bounds,
});
return (
<div className="h-screen w-screen">
<Map
{...viewport}
onMove={(evt) => setViewport(evt.viewport)}
mapboxAccessToken={process.env.NEXT_PUBLIC_MAPBOX_API_KEY}
mapStyle="mapbox://styles/mapbox/streets-v9"
>
{testCoordinatesArray.map((result) => (
<div
key={result.longitude.toString().concat(result.latitude.toString())}
>
<Marker
longitude={result.longitude}
latitude={result.latitude}
anchor="bottom"
>
<p className="cursor-pointer text-2xl animate-bounce">
<ImLocation2 className="text-red-600" />
</p>
</Marker>
</div>
))}
</Map>
</div>
);
} |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
Call |
Beta Was this translation helpful? Give feedback.
Call
MapRef.fitBpunds
.https://docs.mapbox.com/mapbox-gl-js/api/map/#map#fitbounds