Skip to content
This repository has been archived by the owner on Dec 3, 2019. It is now read-only.

fitBounds not working as expected compared to Mapbox #103

Open
julians opened this issue Sep 26, 2019 · 1 comment
Open

fitBounds not working as expected compared to Mapbox #103

julians opened this issue Sep 26, 2019 · 1 comment

Comments

@julians
Copy link

julians commented Sep 26, 2019

Hello!

I am trying using this library to calculate the initial zoom/center for a map before it’s being drawn. I have a bounding box and the dimensions for the map container. I also have some padding and an offset.

Sadly, all I get is a failed assertion, whereas Mapbox’s fitBounds and flyTo work as expected with the same parameters.

The problem seems to be with the following code. padding is being subtracted from the dimensions, as well as the offset * 2. This results in height being less than zero, throwing the assertion.

var targetSize = [width - padding.left - padding.right - Math.abs(offset[0]) * 2, height - padding.top - padding.bottom - Math.abs(offset[1]) * 2];
Object(_assert__WEBPACK_IMPORTED_MODULE_2__["default"])(targetSize[0] > 0 && targetSize[1] > 0);

Code to reproduce the issue:

const tempViewport = new WebMercatorViewport({
  width: 825,
  height: 978,
  longitude: 0,
  latitude: 0,
  zoom: 11,
  pitch: 0,
  bearing: 0,
});
const bounds = [[13.2928, 52.5067], [13.4761, 52.4746]];
const newViewport = tempViewport.fitBounds(bounds, {
  padding: {top: 303, bottom: 303, left: 14, right: 14},
  offset: [0, -226],
});
// -> Uncaught Error: viewport-mercator-project: assertion failed.
@RobJacobson
Copy link

I had a similar issue in React when using react-map-gl with viewport-mercator-project. My goal was set my map initially to a fixed bounding box. My problem was that the viewport width and height weren't set in the initial state (and can't be set in the initial state for some reason).

I solved this by creating a method setInitialBounds() and using window.innerWidth and window.innerHeight to force a 100%-sized bounding box. I then call this function in componentDidMount(). Sample code:

  setInitialBounds() {
    const viewport = new WebMercatorViewport({
      width: window.innerWidth,
      height: window.innerHeight,
    });
    const {longitude, latitude, zoom} = viewport.fitBounds(BOUNDS, {
      padding: 20
    });
    this.setState({
      viewport: {
        ...this.state.viewport,
        longitude,
        latitude,
        zoom
      }
    });
  }

This feels like a hack, but it works. If there's a more idiomatic way to set the initial bounding box, I'd love to know it.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants