Point in Polygon with geoJSON in Python

Benjamin Horowitz picture Benjamin Horowitz · Dec 25, 2013 · Viewed 21.9k times · Source

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.

Thanks!

Answer

Zebs picture Zebs · Dec 27, 2013

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.geometry import shape, Point
# depending on your version, use: from shapely.geometry import shape, Point

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

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

# 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