Benjamin Horowitz Benjamin Horowitz - 11 months ago 368
JSON Question

Point in Polygon with geoJSON in Python

So I have a geoJSON database with lots of polygons (census tracts specifically) and I have lots of long,lat points.

I am hoping that there would exist an efficient python code to identify which census tract a given coordinate is in, however so far my googling hasn't revealed anything.



I found an interesting article describing how to do exactly what you are looking to do.

TL;DR: Use Shapely

You will find this code at the end of the article:

import json
from shapely import shape, Point
# depending on your version, use: from shapely.geometry import shape, Point

# load GeoJSON file containing sectors
with ('sectors.json', 'r') as f:
    js = json.load(f)

# construct point based on lat/long returned by geocoder
point = Point(45.4519896, -122.7924463)

# check each polygon to see if it contains the point
for feature in js['features']:
    polygon = shape(feature['geometry'])
    if polygon.contains(point):
        print 'Found containing polygon:', feature