Skip to content

Instantly share code, notes, and snippets.

@tomsoderlund
Last active November 6, 2024 14:49
Show Gist options
  • Save tomsoderlund/a2040d659aafe4064e4060f561aca6d1 to your computer and use it in GitHub Desktop.
Save tomsoderlund/a2040d659aafe4064e4060f561aca6d1 to your computer and use it in GitHub Desktop.
Using fitBounds in ReactMapGL to center points on map
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
@barmettlerl
Copy link

Btw. WebMercatorViewport is not in 'react-map-gl' anymore

I used viewport-mercator-project

@geoffraymond
Copy link

👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment