Shapely Point not inside Multipolygon when it should be inside
I'm trying to check if a point is inside a shapely Multipolygon. The data is obtained from the GISCO and the link to it can be found here, the form data is: NUTS 2021, GeoJSON, Polygons (RG), 60M and EPSG:4326.
As you can see in this picture the point I'm trying to know if it's inside the polygon is clearly inside (ignore the other points only the one with Madrid is relevant). I'm linking the image as I'm not allowed to attach images: https://i.imgur.com/aLk6hDR.png
The code I ran to check if the point is inside is the following:
import json
import geopandas as gpd
from shapely.geometry import Point
with open('../datos/poblacion/eurostat_geoson/NUTS_RG_60M_2021_4326.geojson', 'r', encoding='utf8') as f_read:
geodata = json.load(f_read)
gdf = gpd.GeoDataFrame.from_features(geodata['features'])
gdf = gdf[(gdf['LEVL_CODE'] == 0) & (gdf['FID'] == 'ES')]
spain_mp = gdf.loc[1955, 'geometry']
print(f'{spain_mp.contains(Point(40.4381311, -3.8196194))}')
The code returns False
. What could I be doing wrong?
I'm aware the are already similar questions like this but I hope this isn't considered as a duplicate question.
Edit: it seems that the point arguments aren't right. You shouldn't pass latitude then longitude it should be longitude then latitude
Example: Point(-3.8196194, 40.4381311)
Solution 1:
The coordinates in spain_mp
are stored longitude, latitude but you've entered them latitude, longitude in your query.
# examine spain_mp coordinates
print(spain_mp[0].exterior.coords.xy)
(array('d', [4.391037526273436, 4.190661611365112, 3.9067635199467445, 4.158595089473282, 4.391037526273436]),
array('d', [39.861727174825646, 39.79806899465741, 39.99861969152096, 40.107076555880866, 39.861727174825646]))
Switching your query around gives us:
print(f'{spain_mp.contains(Point(-3.8196194, 40.4381311))}')
True