So I have a .geojson
file that contains a FeatureCollection
of multiple polygons representing a country. I am trying to determine if a specific point is inside one of these polygons. If so, I return the entire feature itself; if not, I return a simple message.
So far, I am able to load the data into a GeoDataFrame
using geopandas, but for some reasons, I can't successfully iterate through the geodataframe and successfully perform polygon.contains(point)
. It seems to me that the iteration stops after a certain point, or maybe my code does not work at all.
I have tried multiple suggestions from S/O and other tutorials on Google, but I couldn't successfully get what I wanted. Below is my code.
Geojson file
Code
%matplotlib inline
import json
import pandas as pd
import geopandas as gpd
import matplotlib.pyplot as plt
import shapely
from shapely.geometry import Point, Polygon
from descartes import PolygonPatch
import geocoder
import requests
import copy
session = requests.Session()
test_point = [14.1747157, 10.4952759]
f, ax = plt.subplots(1, figsize=(10, 10))
url = 'https://trello-attachments.s3.amazonaws.com/599b7f6ff18b8d629ac53168/5d03586a06add530095c325c/26f5d54bbfa9731ec16737641b59de9a/CMR_adm3-2.geojson'
df = gpd.read_file(url)
df['Area']= df['geometry'].area
df['centroid'] = df['geometry'].centroid
df.plot(ax=ax, column="Area", cmap='OrRd', alpha=0.5, edgecolor='k')
# ax.set_title(arr + " " + depart + " " + region, fontsize = font_size)
# print(df.head(3))
plt.show()
print("The length of the Dataframe is:", len(df))
def find_department(df, point):
for feature in df['geometry']:
polygon = Polygon(feature)
# print(type(polygon))
if polygon.contains(point):
# print(feature.to_json())
print ('Found containing polygon:', feature)
else:
print('Found nothing!')
p1 = Point(float(test_point[0]), float(test_point[1]))
dept = find_department(df, p1)
print("The department is:", dept)
This is the response I get when I run it on notebook:
This worked for me:
def find_department(df, point):
for index, row in df.iterrows():
if row.geometry.contains(point):
return row