Search code examples
javascriptreactjsmapbox-gl-jsreact-map-gl

How to constrain React-mapbox-gl to its container?


I have a map with a maxBounds property setup, the map works fine but we are using a tile set from a third party that only gives the entire map for the UK, so I wonder if it is at all possible to constrain the map to its container div so the blank spaces that don't render remain hidden from the user?

Here is my setup:

const [viewport, setViewport] = useState({
  latitude: 53.55,
  longitude: -2.39,
  width: '100%',
  height: '450px',
  zoom: zoom,
  maxBounds: [
    [-10.76418, 49.528423],
    [1.9134116, 61.331151],
  ],
});

return (
  <ReactMapGL
    {...viewport}
    onViewportChange={(newViewport) => {
      setViewport({ ...newViewport })
    }}
    fitBounds={bounds}
    center={centre}
    mapStyle={style}
    ref={mapRef}
  >

    {* My Markers logic... *}

  </ReactMapGL>
  );

The image below shows the map as its been dragged to the top left corner, since there are not more tiles available to render you see an empty space, so I would like to constrain the map to the container div marked with the red line. enter image description here


Solution

  • You can use the maxBounds property of a map - docs here

    To integrate with react-map-gl, it looks like you have to include this as part of the mapOptions object property, not as part of the viewport. As react-map-gl docs explain, the mapOptions prop of an InteractiveMap inherits from the StaticMap mapOptions prop. You might try this:

    return (
      <ReactMapGL
        {...props}
        mapOptions={{
          maxBounds={[
            [-10.76418, 49.528423],
            [1.9134116, 61.331151],
          ]}
        }}
      />
    );