Search code examples
javascriptnode.jsh3

JS: How to divide a bounding box into two smaller bounding boxes


We are using H3Js library (https://github.com/uber/h3-js) to fetch the H3Cells based on boundingBox (First converting into polygon and using polygonToCells method).

For bigger screens (4k resolutions), this method polygonToCells is responding with wrong H3 Cells. So thats why I want to divide this bounding box into 2 or 4 pieces, so I can get the H3 cells for smaller pieces then can merge all of the H3 Cells into one.

Requested Bounding box:

15.203087,-109.629878,72.791223,110.448247 (Lat/lng format)

-109.629878,15.203087,110.448247,72.791223 (Lng/Lat format)

enter image description here


Solution

  • Seems like a pretty simple geometry question.

    You want to find the midpoints of a rectangle. enter image description here

    You just need an algorithm to find the midpoint of a given line segment.

    For example, the coordinates of Mab will be as follows:

    x = (x1 + x2)/2

    y = y1

    Generic way to find the midpoint of any line segment will be something like:

    const getMidpoint = (a, b) => [(a[0] + b[0])/2, (a[1] + b[1])/2]
    
    a = [2, 4], b = [8, 8]
    getMidpoint(a, b) //this will be [6, 6]
    getMidpoint([-10, 6], [10, -2]) //this will be [0, 2]
    

    Using this simple function, you can calculate the midpoints of the original rectangle really easily, and if you want to divide the rectangle by four, you just have to find the midpoint of the two opposing midpoints (Mab, Mcd or Mbc, Mad).

    Hope this clears things out.