Dylee
Dylee

Reputation: 125

Get all lat/lon points inside a bounding box area

I am able to generate a southwest-northeast bounding box from latitude, longitude and radius. How could I possibly get all the points within that bounding box area?

I have tried creating a shapely.geometry.polygon.Polygon object thinking I can extract the points with polygon.coords or polygon.interiors. I generated the polygon like this:

import shapely.geometry as sg

bbox = (55.74341900255196, 37.5950436686672, 55.79737829890708, 37.69096949784429)
polygon = sg.box(*bbox, ccw=True)

But nothing could possibly give all points inside the box.

Upvotes: 0

Views: 1606

Answers (1)

Alon Cohen
Alon Cohen

Reputation: 21

There are a couple of options:

The naive solution - pass your bbox to a function that returns True if a point's lat, lng values between the bbox values

Pro - Computationally cheap

Con - Not accurate (Doesn't take into account the curves of the earth)

def isin_box(lat, lng, bbox):
    
   x1, x2, x3, x4 = bbox
    
   within = False
    
   if x2 < lat < x4:
      if x1 < lng < x3:
         within = True
    
   return within

isin_box(55.77037811279297,37.64223791838213, bbox)
True

The accurate solution - use shapely within operation to check if a point object lies in the bbox polygon:

from shapely.geometry import Point

bbox = (55.74341900255196, 37.5950436686672, 55.79737829890708, 37.69096949784429)
polygon = sg.box(*bbox, ccw=True)
Point(55.77037811279297,37.64223791838213).within(polygon)
True

Pro - Accurate

Con - Computationally expensive

Upvotes: 2

Related Questions