Search code examples
javascripthere-api

Here Maps API JavaScript zoom into bounds with margin


I have several markers in a group and I want to zoom in, so they're all visible.

With version 3.0 of mapsjs I could do this:

var cameraData = map.getCameraDataForBounds(group.getBounds());
map.setZoom(cameraData.zoom - 0.5, true);
map.setCenter(cameraData.position, true);

With version 3.1 getCameraDataForBounds was removed and the documentation tells me to do it this way:

map.getViewModel().setLookAtData({
  bounds: group.getBoundingBox()
}, true);

My problem is, that with the new way, the markers are very close to the edge. With the 3.0 way, I could add some margin by simply adjusting the zoom level. That doesn't seem possible with 3.1 since I can't seem to find a replacement for getCameraDataForBounds.

Zooming in and then back out, seems hacky and kills my animation. I tried widening the bounding box, but couldn't find a reliable way to do it.

Any advice on how to archive this would be greatly appreciated.


Solution

  • For this case you can simply use padding option when creating new Map instance:

    // assuming htmlElement and baseLayer exist
    var map = new H.Map(htmlElement, baseLayer, {
      ...
      padding: {top: 50, left: 50, bottom: 50, right: 50}
    });
    

    or setting the padding on the fly:

    map.getViewPort().setPadding(50, 50, 50, 50)
    

    Here is updated jsfiddle example.

    See Map#Options or ViewPort#setPadding documentation for more details.