1

I am currently using react-map-gl package for creating my application. In the documentation this block of code focuses on the latitude: 37.7577, longitude: -122.4376 zoom: 8 in the center of my view. However, I want the focus of latitude: 37.7577, longitude: -122.4376 to be the bottom of my view. Any ideas how I can accomplish this?

function Map() {
  const [viewport, setViewport] = useState({
    width: 400,
    height: 400,
    latitude: 37.7577,
    longitude: -122.4376,
    zoom: 8
  });

  return (
    <ReactMapGL
      {...viewport}
      onViewportChange={nextViewport => setViewport(nextViewport)}
    />
  );
}
James Lee
  • 656
  • 1
  • 7
  • 22

1 Answers1

1

One option would be to determine north point of the bounds and re-center a map via Map.panTo function:

const bounds = map.getBounds();  //get map bounds
const newCenter = { lng: map.getCenter().lng, lat: bounds.getNorth() };
map.panTo(newCenter);

Example

function Map() {
  const [viewport, setViewport] = React.useState({
    latitude: 37.7577,
    longitude: -122.4376,
    zoom: 8,
  });

  function mapLoaded(e) {
    const map = e.target;
    const bounds = map.getBounds();  //get map bounds
    const newCenter = { lng: map.getCenter().lng, lat: bounds.getNorth() };
    map.panTo(newCenter);
  }

  return (
    <ReactMapGL
      onLoad={mapLoaded}
      mapboxApiAccessToken={MAPBOX_TOKEN}
      {...viewport}
      width="100vw"
      height="100vh"
      onViewportChange={(nextViewport) => setViewport(nextViewport)}
    />
  );
}
Vadim Gremyachev
  • 57,952
  • 20
  • 129
  • 193