I have a map.geojson
file that contains the regional boundaries of a various cities.
How can I calculate the region of a point given by (latitude, longitude)?
I have a map.geojson
file that contains the regional boundaries of a various cities.
How can I calculate the region of a point given by (latitude, longitude)?
you can parse the geojson and extract the points / coordinates
import json
data = json.loads(datastring)
data['features'][0]['geometry'] #Your first point
( How can I parse GeoJSON with Python )
When you load a GeoJSON file using the json library, you get a dict that contains an entry features, which contains the list of features. Each feature in turn consists of a dict, which, among other things, contains an entry geometry. The geometry is a dict containing the entries type and coordinates. So you can traverse your GeoJSON file like this:
import json
with open('test.json') as f:
data = json.load(f)
for feature in data['features']:
print feature['geometry']['type']
print feature['geometry']['coordinates']
( https://gis.stackexchange.com/questions/73768/how-to-convert-geojson-to-python-objects )
now that you have the coordinates / points create a polygon in shapely with it to get a geometric representation of the city boundaries : How to create a Polygon given its Point vertices?
Point-in-Polygon
Now that you have a polygon, determining whether a point is inside it is very easy. There’s 2 ways to do it.
`point.within(polygon)` `polygon.contains(point)`
point should be an instance of the Point class, and poly is of course an instance of Polygon. within and contains are the converse of each other, so whichever method you use is entirely up to you.
https://streamhacker.com/2010/03/23/python-point-in-polygon-shapely/
in shapely is a specific class to handle points and only points that are represented in this class will work in the point.within(polygon)
and polygon.contains(point)
functions.
The point type is implemented by a Point class; curve by the LineString and LinearRing classes; and surface by a Polygon class. Shapely implements no smooth (i.e. having continuous tangents) curves. All curves must be approximated by linear splines. All rounded patches must be approximated by regions bounded by linear splines.
( https://toblerity.org/shapely/manual.html )
so you have to take your decimal lat
, lon
values and insert them in the shapely point class :
from shapely.geometry import Point
point = Point(0.0, 0.0)
q = Point((0.0, 0.0))
( https://toblerity.org/shapely/manual.html#points )
with this point.within(polygon)
and polygon.contains(point)
functions will work ...