#!/usr/bin/env python # coding: utf-8 # # Computing intersections with polygons # # # # [![Binder](https://mybinder.org/badge_logo.svg)](https://mybinder.org/v2/gh/movingpandas/movingpandas-examples/main?filepath=1-tutorials/5-intersecting-with-polygons.ipynb) # [![IPYNB](https://img.shields.io/badge/view-ipynb-hotpink)](https://github.com/movingpandas/movingpandas-examples/blob/main/1-tutorials/5-intersecting-with-polygons.ipynb) # [![HTML](https://img.shields.io/badge/view-html-green)](https://movingpandas.github.io/movingpandas-website/1-tutorials/5-intersecting-with-polygons.html) # # Clipping and intersection functions can be used to extract trajectory segments that are located within an area of interest polygon. # In[ ]: import pandas as pd import geopandas as gpd import movingpandas as mpd import shapely as shp import hvplot.pandas from geopandas import GeoDataFrame, read_file from shapely.geometry import Point, LineString, Polygon from datetime import datetime, timedelta from holoviews import opts import warnings warnings.filterwarnings('ignore') opts.defaults(opts.Overlay(active_tools=['wheel_zoom'], frame_width=500, frame_height=400)) mpd.show_versions() # In[ ]: gdf = read_file('../data/geolife_small.gpkg') tc = mpd.TrajectoryCollection(gdf, 'trajectory_id', t='t') # ## Clipping a Trajectory # In[ ]: xmin, xmax, ymin, ymax = 116.365035,116.3702945,39.904675,39.907728 polygon = Polygon([(xmin,ymin), (xmin,ymax), (xmax,ymax), (xmax,ymin), (xmin,ymin)]) my_traj = tc.trajectories[2] intersections = my_traj.clip(polygon) print("Found {} intersections".format(len(intersections))) # In[ ]: ax = my_traj.plot() gpd.GeoSeries(polygon).plot(ax=ax, color='lightgray') intersections.plot(ax=ax, color='red', linewidth=5) # ## Clipping a TrajectoryCollection # Alternatively, using **TrajectoryCollection**: # In[ ]: clipped = tc.clip(polygon) clipped # In[ ]: clipped.plot() # ## Computing intersections # In[ ]: polygon_feature = { "geometry": polygon, "properties": {'field1': 'abc'} } # In[ ]: my_traj = tc.trajectories[2] intersections = my_traj.intersection(polygon_feature) intersections # In[ ]: intersections.to_point_gdf() # In[ ]: