Search code examples
azurebing-mapsazure-maps

How can I zoom the Azure Maps bounding box on cluster click event?


A data source in Azure Maps can cluster point features (pins) within a certain radius. When a click event on such a cluster occurs I would like to reset my bounding box to the area represented by the cluster and zoom in to show individual pins within the cluster.

With Google Maps you can set the default behaviour of a cluster to auto zoom on click. This feature was also relatively easily accomplished in the old Bing Maps API. How can I add this functionality in Azure Maps without an unwieldy amount of JavaScript?


Solution

  • Indeed, it appears Azure Maps does not support it directly, the following approach could be considered:

    Once we layer is clicked event returns pixel position of target object along with another properties. Then min and max coordinates of cluster circle is determined via atlas.Map.pixelsToPositions function:

    const coordinates = e.map.pixelsToPositions([
              [e.pixel[0] + (clusterRadius*2), e.pixel[1] + (clusterRadius*2)],
              [e.pixel[0] - (clusterRadius*2), e.pixel[1] - (clusterRadius*2)],
            ]);            
    

    Then the bounds of area which might contain pins within a cluster bubble is determined via atlas.data.BoundingBox.fromPositions function:

    const bounds = atlas.data.BoundingBox.fromPositions(coordinates);
    

    And finally map viewport is set:

     map.setCamera({
              bounds: bounds,
              padding:0
            }); 
    

    Here is a demo for your reference