Function to get Polyline Map Bounds Easily for fitBounds

Last Updated:
Carbon code generated image of solution

I have been recently working on a project using user generated poly-lines on maps. I am using Mapbox to render the maps and lines, it is brilliant! However, I needed a simple way of zooming the map to the polyline and the Mapbox example wasn’t working for me.

Enter my solution!

export default function getPolylineBounds(bounds) {
  return bounds.reduce((processArray, bound) => {
    const topLeftLat = Array.isArray(processArray[0])
      ? processArray[0][0]
      : processArray[0];
    const topLeftLng = Array.isArray(processArray[0])
      ? processArray[0][1]
      : processArray[1];
    const bottomRightLat = Array.isArray(processArray[1])
      ? processArray[1][0]
      : processArray[0];
    const bottomRightLng = Array.isArray(processArray[1])
      ? processArray[1][1]
      : processArray[1];

    const topLeft = [
      topLeftLat < bound[0] ? topLeftLat : bound[0],
      topLeftLng < bound[1] ? topLeftLng : bound[1] ]; const bottomRight = [ bottomRightLat > bound[0] ? bottomRightLat : bound[0],
      bottomRightLng > bound[1] ? bottomRightLng : bound[1]
    ];

    return [topLeft, bottomRight];
  });
}

It takes the array, spins through and reduces it down into its furthest points.

Drop the longitude & latitude array into the function and it will return the most top left, and bottom right co-ordinates which can then be used with the fitBounds function.

Like this:


    const routePolyline = [
      [-0.18235092163085938, 51.538250335096376],
      [-0.1674163818359375, 51.54433860667918],
      [-0.15591506958007812, 51.53974577545329],
      [-0.15831832885742188, 51.53429786349477],
      [-0.17531280517578122, 51.53429786349477],
      [-0.18200759887695312, 51.537823057404094]
    ];

    const routeBounds = getPolylineBounds(routePolyline);

 

Very nice!

Related Posts

Helpful Bits Straight Into Your Inbox

Subscribe to the newsletter for insights and helpful pieces on React, Gatsby, Next JS, Headless WordPress, and Jest testing.