Last active
November 6, 2024 14:49
-
-
Save tomsoderlund/a2040d659aafe4064e4060f561aca6d1 to your computer and use it in GitHub Desktop.
Using fitBounds in ReactMapGL to center points on map
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { useState } from 'react' | |
import ReactMapGL, { Marker } from 'react-map-gl' | |
import { WebMercatorViewport } from '@deck.gl/core' | |
const getBoundsForPoints = (points, { width = 200, height = 500, padding = 0 } = {}) => { | |
// Calculate corner values of bounds | |
const pointsLong = points.map(point => point.coordinates._long) | |
const pointsLat = points.map(point => point.coordinates._lat) | |
const cornersLongLat = [ | |
[Math.min(...pointsLong), Math.min(...pointsLat)], | |
[Math.max(...pointsLong), Math.max(...pointsLat)] | |
] | |
// Use WebMercatorViewport to get center longitude/latitude and zoom | |
const viewport = new WebMercatorViewport({ width, height }) | |
.fitBounds(cornersLongLat, { padding }) // Can also use option: offset: [0, -100] | |
const { longitude, latitude, zoom } = viewport | |
return { longitude, latitude, zoom } | |
} | |
const Map = ({ points }) => { | |
const bounds = getBoundsForPoints(points) | |
const [viewport, setViewport] = useState({ | |
width: '100%', | |
height: '50vh', | |
...bounds | |
}) | |
return ( | |
<ReactMapGL | |
{...viewport} | |
onViewportChange={setViewport} | |
mapStyle='mapbox://styles/mapbox/streets-v9' | |
mapboxApiAccessToken={mapboxPublicToken} | |
> | |
{points.map((point, index) => ( | |
<Marker | |
key={index} | |
latitude={point.coordinates._lat} | |
longitude={point.coordinates._long} | |
offsetLeft={-20} | |
offsetTop={-10} | |
> | |
<div>{point.name}</div> | |
</Marker> | |
))} | |
</ReactMapGL> | |
) | |
} | |
export default Map |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Btw.
WebMercatorViewport
is not in 'react-map-gl' anymoreI used
viewport-mercator-project