### Interactive midpoint example with ipyleaflet Source: https://turfpy.readthedocs.io/en/latest/measurements/midpoint.html Creates an interactive map showing the start and end points as GeoJSON layers and the midpoint as a red CircleMarker. Requires ipyleaflet and a Jupyter environment to display the map. ```python from turfpy.measurement import midpoint from geojson import Point, Feature from ipyleaflet import Map, GeoJSON, LayersControl, CircleMarker point1 = Feature(geometry=Point([144.834823, -37.771257])) point2 = Feature(geometry=Point([145.14244, -37.830937])) m = Map(center=[-37.80415546165204, 145.0286749005318], zoom=11) start_geo_json = GeoJSON(name="Start Point", data=point1) end_geo_json = GeoJSON(name="End Point", data=point2) m.add_layer(start_geo_json) m.add_layer(end_geo_json) midpoint_coord = midpoint(point1, point2)["geometry"]["coordinates"] circle_marker = CircleMarker(name="Midpoint") circle_marker.location = (midpoint_coord[1], midpoint_coord[0]) circle_marker.radius = 10 circle_marker.color = "red" m.add_layer(circle_marker) control = LayersControl(position="topright") m.add_control(control) m ``` -------------------------------- ### Install Turfpy with pip Source: https://turfpy.readthedocs.io/en/latest/install.html Installs the Turfpy library using the pip package manager. Run this command in your terminal or command prompt. ```bash pip install turfpy ``` -------------------------------- ### voronoi example Source: https://turfpy.readthedocs.io/en/latest/turfpy.transformation.html Creates a list of point coordinates and a bounding box, then calls voronoi to generate Voronoi polygons. The example shows the expected input format for points and bbox. ```python >>> from turfpy.transformation import voronoi >>> points = [ ... [-66.9703, 40.3183], ... [-63.7763, 40.4500], ... [-65.4196, 42.13985310302137], ... [-69.5813, 43.95405461286195], ... [-65.66337553550034, 55.97088945355232], ... [-60.280418548905, 56.240669185466146], ... [-68.5129561347689, 50.12984589640148], ... [-64.2393519226657, 59.66235385923687], ... ] >>> bbox = [-70, 40, -60, 60] >>> voronoi(points, bbox) ``` -------------------------------- ### Output of bezier_spline example Source: https://turfpy.readthedocs.io/en/latest/transformations/bezier_spline.html The JSON output produced by the example, showing the curved line's coordinates after applying the Bezier spline algorithm. ```json { "geometry": { "coordinates": [ [ -76.091308, 18.427501 ], [ -76.091346, 18.427508 ], [ -76.091459, 18.427529 ], [ -76.091647, 18.427565 ], [ -76.091908, 18.427614 ], [ -76.092243, 18.427678 ], [ -76.09265, 18.427756 ], [ -76.093129, 18.427849 ], [ -76.093679, 18.427955 ], [ -76.0943, 18.428076 ], [ -76.10558, 18.430352 ], [ -76.106992, 18.430645 ], [ -76.108466, 18.430953 ], [ -76.110001, 18.431275 ], [ -76.111596, 18.431612 ], [ -76.11325, 18.431963 ], [ -76.114963, 18.432328 ], [ -76.116735, 18.432709 ], [ -76.118563, 18.433103 ], [ -76.120449, 18.433513 ], [ -76.144737, 18.43898 ], [ -76.147249, 18.439565 ], [ -76.14981, 18.440164 ], [ -76.152418, 18.440779 ], [ -76.155072, 18.441408 ], [ -76.157771, 18.442052 ], [ -76.160516, 18.442711 ], [ -76.163306, 18.443385 ], [ -76.166139, 18.444074 ], [ -76.169015, 18.444777 ], [ -76.203294, 18.453497 ], [ -76.206632, 18.45438 ], [ -76.210005, 18.455277 ], [ -76.213411, 18.45619 ], [ -76.21685, 18.457117 ], [ -76.220321, 18.45806 ], [ -76.223823, 18.459018 ], [ -76.227356, 18.45999 ], [ -76.230919, 18.460978 ], [ -76.234512, 18.461981 ], [ -76.275764, 18.474017 ], [ -76.279654, 18.475203 ], [ -76.283565, 18.476403 ], [ -76.287496, 18.47762 ], [ -76.291445, 18.478851 ], [ -76.295413, 18.480098 ], [ -76.299398, 18.48136 ], [ -76.303401, 18.482638 ], [ -76.307419, 18.483931 ], [ -76.311453, 18.485239 ], [ -76.356662, 18.500652 ], [ -76.36083, 18.502146 ], [ -76.365004, 18.503656 ], [ -76.369185, 18.505182 ], [ -76.37337, 18.506723 ], [ -76.377561, 18.508279 ], [ -76.381755, 18.509852 ], [ -76.385952, 18.51144 ], [ -76.390152, 18.513043 ], [ -76.394354, 18.514663 ], [ -76.440502, 18.533515 ], [ -76.444673, 18.535324 ], [ -76.448836, 18.537148 ], [ -76.452992, 18.538988 ], [ -76.45714, 18.540845 ], [ -76.461278, 18.542717 ], [ -76.465407, 18.544605 ], [ -76.469525, 18.546509 ], [ -76.473632, 18.548429 ], [ -76.477728, 18.550365 ], [ -76.521797, 18.572719 ], [ -76.525697, 18.574847 ], [ -76.529575, 18.576992 ], [ -76.533433, 18.579153 ], [ -76.537268, 18.58133 ], [ -76.54108, 18.583523 ], [ -76.544869, 18.585733 ], [ -76.548634, 18.587959 ], [ -76.552374, 18.590201 ] ] } } ``` -------------------------------- ### Interactive sector example with ipyleaflet Source: https://turfpy.readthedocs.io/en/latest/misc/sector.html Interactive example that creates a sector and displays it on an ipyleaflet map. It uses `Map`, `GeoJSON`, and `LayersControl` from `ipyleaflet`, and adds the sector and center as a GeoJSON layer. ```python from ipyleaflet import Map, GeoJSON, LayersControl from turfpy.misc import sector from geojson import Feature, Point, LineString, FeatureCollection center = Feature(geometry=Point((-75, 40))) radius = 5; bearing1 = 25; bearing2 = 45; m = Map(center=[40.011313056309056, -74.97720068362348], zoom=12) feature = sector(center, radius, bearing1, bearing2, options={"properties":{"length":3}}) fc = FeatureCollection([feature, center]) layer = GeoJSON(name="Line_Arc", data=fc, style={'color':'red'}) m.add_layer(layer) m ``` -------------------------------- ### Example: Using line_segment from turfpy.misc Source: https://turfpy.readthedocs.io/en/latest/_modules/turfpy/misc.html Shows how to import and use the line_segment function with a Polygon feature. The example defines a polygon and calls line_segment(poly) to generate line segments. ```python >>> from turfpy.misc import line_segment >>> >>> poly = { ... "type": "Feature", ... "properties": {}, ... "geometry": { ... "type": "Polygon", ... "coordinates": [ ... [ ... [ ... 51.17431640625, ... 47.025206001585396 ... ], ... [ ... 45.17578125, ... 43.13306116240612 ... ], ... [ ... 54.5361328125, ... 41.85319643776675 ... ], ... [ ... 51.17431640625, ... 47.025206001585396 ... ] ... ] ... ] ... } ... } ... >>> line_segment(poly) ``` -------------------------------- ### Install Turfpy with conda Source: https://turfpy.readthedocs.io/en/latest/install.html Installs the Turfpy library using the conda package manager from the conda-forge channel. Requires conda to be installed. ```bash conda install -c conda-forge turfpy ``` -------------------------------- ### Output of transform_translate example Source: https://turfpy.readthedocs.io/en/latest/transformations/transform_translate.html The JSON output of the transform_translate example, showing the translated polygon coordinates. ```json { "geometry": { "coordinates": [ [ [ 0.591903, 29.73668 ], [ 4.091903, 29.73668 ], [ 3.110728, 32.73668 ], [ 0.591903, 29.73668 ] ] ], "type": "Polygon" }, "properties": {}, "type": "Feature" } ``` -------------------------------- ### Output of line_offset example Source: https://turfpy.readthedocs.io/en/latest/transformations/line_offset.html The GeoJSON output produced by the basic line_offset example, showing the offset MultiLineString coordinates. ```json { "geometry": { "coordinates": [ [ [ 3.748342, 9.278899 ], [ -130.951658, 1.548899 ] ], [ [ 23.172299, -34.231543 ], [ -1.320442, -4.640314 ], [ 3.478898, 77.948321 ] ] ], "type": "MultiLineString" }, "properties": {}, "type": "Feature" } ``` -------------------------------- ### Interactive boolean_point_in_polygon example with ipyleaflet Source: https://turfpy.readthedocs.io/en/latest/measurements/point_in_polygon.html Builds on the basic example by adding ipyleaflet map layers to visualize the polygon and point. Creates a Map, adds GeoJSON layers for the polygon and point, and adds a LayersControl. The final map object is displayed. ```python from turfpy.measurement import boolean_point_in_polygon from geojson import Point, MultiPolygon, Feature from ipyleaflet import Map, GeoJSON, LayersControl point = Feature(geometry=Point([-77, 44])) polygon = Feature( geometry=MultiPolygon( [ ([(-81, 41), (-81, 47), (-72, 47), (-72, 41), (-81, 41)],), ([(3.78, 9.28), (-130.91, 1.52), (35.12, 72.234), (3.78, 9.28)],), ] ) ) boolean_point_in_polygon(point, polygon) m = Map(center=[46.57868671298067, -40.91583251953126], zoom=2) geo_json = GeoJSON(name="MultiPolygon Feature", data=polygon) m.add_layer(geo_json) point_geojson = GeoJSON(name="Point in Polygon", data=point) m.add_layer(point_geojson) control = LayersControl(position="topright") m.add_control(control) m ``` -------------------------------- ### square example Source: https://turfpy.readthedocs.io/en/latest/turfpy.measurement.html Takes a bounding box and calculates the minimum square bounding box that would contain the input. ```python >>> from turfpy.measurement import square >>> bbox = [-20, -20, -15, 0] >>> square(bbox) ``` -------------------------------- ### boolean_point_in_polygon definition and example Source: https://turfpy.readthedocs.io/en/latest/_modules/turfpy/measurement.html Defines the boolean_point_in_polygon function with a docstring containing an example invocation. The code so far validates required arguments, extracts coordinates, and prepares polygon coordinates, including a bbox early-exit. The example shows how to import and call it with a Point and MultiPolygon feature. ```python [docs]def boolean_point_in_polygon(point, polygon, ignore_boundary=False): """ Takes a Point or a Point Feature and Polygon or Polygon Feature as input and returns True if Point is in given Feature. :param point: Point or Point Feature. :param polygon: Polygon or Polygon Feature. :param ignore_boundary: [Optional] default value is False, specify whether to exclude boundary of the given polygon or not. :return: True if the given Point is in Polygons else False Example: >>> from turfpy.measurement import boolean_point_in_polygon >>> from geojson import Point, MultiPolygon, Feature >>> point = Feature(geometry=Point((-77, 44))) >>> polygon = Feature(geometry=MultiPolygon([([(-81, 41), (-81, 47), (-72, 47), (-72, 41), (-81, 41)],), >>> ([(3.78, 9.28), (-130.91, 1.52), (35.12, 72.234), (3.78, 9.28)],)])) >>> boolean_point_in_polygon(point, polygon) """ if not point: raise Exception("point is required") if not polygon: raise Exception("polygon is required") pt = get_coord(point) geom = get_geom(polygon) geo_type = geom["type"] bbox = polygon.get("bbox", None) polys = geom["coordinates"] if bbox and not in_bbox(pt, bbox): return False if geo_type == "Polygon": polys = [polys] inside_poly = False ``` -------------------------------- ### tesselate example Source: https://turfpy.readthedocs.io/en/latest/turfpy.transformation.html Tesselates a GeoJSON polygon feature into a FeatureCollection of triangles using turfpy.transformation.tesselate. The example creates a polygon feature and calls tesselate(polygon). ```python >>> from geojson import Feature >>> from turfpy.transformation import tesselate >>> polygon = Feature(geometry={"coordinates": [[[11, 0], [22, 4], [31, 0], [31, 11], ... [21, 15], [11, 11], [11, 0]]], "type": "Polygon"}) >>> tesselate(polygon) ``` -------------------------------- ### Interactive example of points_within_polygon with ipyleaflet Source: https://turfpy.readthedocs.io/en/latest/measurements/points_within_polygon.html This example creates a set of points and a polygon, visualizes them on an ipyleaflet map, and then uses points_within_polygon to filter points within the polygon. The result is displayed on a second map. Requires geojson, turfpy, and ipyleaflet. ```python from geojson import Feature, FeatureCollection, Point, Polygon from turfpy.measurement import points_within_polygon from ipyleaflet import Map, GeoJSON p1 = Feature(geometry=Point((-46.6318, -23.5523))) p2 = Feature(geometry=Point((-46.6246, -23.5325))) p3 = Feature(geometry=Point((-46.6062, -23.5513))) p4 = Feature(geometry=Point((-46.663, -23.554))) p5 = Feature(geometry=Point((-46.643, -23.557))) points = FeatureCollection([p1, p2, p3, p4, p5]) poly = Polygon( [ [ (-46.653, -23.543), (-46.634, -23.5346), (-46.613, -23.543), (-46.614, -23.559), (-46.631, -23.567), (-46.653, -23.560), (-46.653, -23.543), ] ] ) m = Map(center=(-23.5523, -46.6318), zoom=13) fc = FeatureCollection([p1, p2, p3, p4, p5, poly]) geo_json = GeoJSON( data=fc, style={"opacity": 1, "dashArray": "9", "fillOpacity": 0.3, "weight": 1}, hover_style={"color": "green", "dashArray": "0", "fillOpacity": 0.5}, ) m.add_layer(geo_json) result = points_within_polygon(points, poly) data = result.copy() data["features"].append(Feature(geometry=poly)) m = Map(center=(-23.5523, -46.6318), zoom=13) geo_json2 = GeoJSON( data=data, style={"opacity": 1, "dashArray": "9", "fillOpacity": 0.3, "weight": 1}, hover_style={"color": "green", "dashArray": "0", "fillOpacity": 0.5}, ) m.add_layer(geo_json2) m ``` -------------------------------- ### bbox function with example Source: https://turfpy.readthedocs.io/en/latest/_modules/turfpy/measurement.html Defines the bbox function that computes the bounding box of a GeoJSON object. The docstring includes a usage example with a Polygon. ```python def bbox(geojson): """ This function is used to generate bounding box coordinates for given geojson. :param geojson: Geojson object for which bounding box is to be found. :return: bounding box for the given Geojson object. Example : >>> from turfpy.measurement import bbox >>> from geojson import Polygon >>> p = Polygon([(2.38, 57.322), (23.194, -20.28), (-120.43, 19.15),(2.38, 57.322)]) >>> bb = bbox(p) """ result = [float("inf"), float("inf"), float("-inf"), float("-inf")] def _callback_coord_each( coord, coord_index, feature_index, multi_feature_index, geometry_index ): nonlocal result if result[0] > coord[0]: result[0] = coord[0] if result[1] > coord[1]: result[1] = coord[1] if result[2] < coord[0]: result[2] = coord[0] if result[3] < coord[1]: result[3] = coord[1] coord_each(geojson, _callback_coord_each) return result ``` -------------------------------- ### envelope function with example Source: https://turfpy.readthedocs.io/en/latest/_modules/turfpy/measurement.html Defines the envelope function that returns a rectangular Polygon encompassing all vertices. The docstring includes a usage example with a FeatureCollection. ```python def envelope(geojson) -> Feature: """ Takes any number of features and returns a rectangular Polygon that encompasses all vertices. :param geojson: geojson input features for which envelope to be generated. :return: returns envelope i.e bounding box polygon. Example : >>> from turfpy.measurement import envelope >>> from geojson import Feature, FeatureCollection, Point >>> f1 = Feature(geometry=Point((-97.522259, 35.4691))) >>> f2 = Feature(geometry=Point((-97.502754, 35.463455))) >>> f3 = Feature(geometry=Point((-97.508269, 35.463245))) >>> feature_collection = FeatureCollection([f1, f2, f3]) >>> feature = envelope(feature_collection) """ return bbox_polygon(bbox(geojson)) ``` -------------------------------- ### along - Find point at distance along a LineString Source: https://turfpy.readthedocs.io/en/latest/turfpy.measurement.html Example for the along function, which identifies a Point at a specified distance along a LineString. The example creates a LineString Feature and calls along with distance 200 and unit 'mi'. ```python >>> from turfpy.measurement import along >>> from geojson import LineString, Feature >>> ls = Feature(geometry=LineString([(-83, 30), (-84, 36), (-78, 41)])) >>> along(ls,200,'mi') ``` -------------------------------- ### center - Calculate center of a FeatureCollection Source: https://turfpy.readthedocs.io/en/latest/turfpy.measurement.html Example for the center function, which takes a FeatureCollection of Point features and returns the center point. The example creates three Point features, combines them into a FeatureCollection, and calls center. ```python >>> f1 = Feature(geometry=Point((-97.522259, 35.4691))) >>> f2 = Feature(geometry=Point((-97.502754, 35.463455))) >>> f3 = Feature(geometry=Point((-97.508269, 35.463245))) >>> feature_collection = FeatureCollection([f1, f2, f3]) >>> feature = center(feature_collection) ``` -------------------------------- ### polygon_tangents function definition with docstring example Source: https://turfpy.readthedocs.io/en/latest/_modules/turfpy/measurement.html Finds tangents of a (Multi)Polygon from a Point. The docstring includes a usage example with imports and sample data. ```python [docs]def polygon_tangents(point, polygon): """ Finds the tangents of a (Multi)Polygon from a Point. :param point: Point or Point Feature. :param polygon: (Multi)Polygon or (Multi)Polygon Feature. :return: FeatureCollection of two tangent Point Feature. Example: >>> from turfpy.measurement import polygon_tangents >>> from geojson import Polygon, Point, Feature >>> point = Feature(geometry=Point((61, 5))) >>> polygon = Feature(geometry=Polygon([(11, 0), (22, 4), (31, 0), (31, 11), ... (21, 15), (11, 11), (11, 0)])) >>> polygon_tangents(point, polygon) """ point_coords = get_coords(point) poly_coords = get_coords(polygon) enext = 0 bbox_points = bbox(polygon) nearest_pt_index = 0 nearest = None if ( bbox_points[0] < point_coords[0] < bbox_points[2] and bbox_points[1] < point_coords[1] < bbox_points[3] ): nearest = nearest_point(point, explode(polygon)) nearest_pt_index = nearest.properties.featureIndex geo_type = get_type(polygon) if geo_type == "Polygon": rtan = poly_coords[0][nearest_pt_index] ltan = poly_coords[0][0] if nearest: if nearest["geometry"]["coordinates"][1] < point_coords[1]: ltan = poly_coords[0][nearest_pt_index] ``` -------------------------------- ### bbox_polygon function with example Source: https://turfpy.readthedocs.io/en/latest/_modules/turfpy/measurement.html Defines the bbox_polygon function that creates a Polygon Feature from a bounding box. The docstring includes a usage example with a Polygon and bbox. ```python def bbox_polygon(bbox: list, properties: dict = {}) -> Feature: """ To generate a Polygon Feature for the bounding box generated using bbox. :param bbox: bounding box generated for a geojson. :param properties: properties to be added to the returned feature. :return: polygon for the given bounding box coordinates. Example : >>> from turfpy.measurement import bbox_polygon, bbox >>> from geojson import Polygon >>> p = Polygon([((2.38, 57.322), (23.194, -20.28), (-120.43, 19.15), ... (2.38, 57.322))]) >>> bb = bbox(p) >>> feature = bbox_polygon(bb) """ west = float(bbox[0]) south = float(bbox[1]) east = float(bbox[2]) north = float(bbox[3]) if len(bbox) == 6: raise Exception("bbox-polygon does not support BBox with 6 positions") low_left = (west, south) top_left = (west, north) top_right = (east, north) low_right = (east, south) bbox_polygon = Polygon([(low_left, low_right, top_right, top_left, low_left)]) feature_bbox = Feature(geometry=bbox_polygon) if "properties" in properties: feature_bbox.properties = properties["properties"] elif "properties" not in properties: feature_bbox.properties = {} if "id" in properties: feature_bbox.id = properties["id"] if "bbox" in properties: feature_bbox.bbox = properties["bbox"] return feature_bbox ``` -------------------------------- ### center function with example Source: https://turfpy.readthedocs.io/en/latest/_modules/turfpy/measurement.html Defines the center function that calculates the absolute center point of a GeoJSON object. The docstring includes a usage example with a FeatureCollection. ```python def center(geojson, properties: Optional[dict] = None) -> Feature: """ Takes a Feature or FeatureCollection and returns the absolute center point of all features. :param geojson: GeoJSON for which centered to be calculated. :param properties: Optional parameters to be set to the generated feature. :return: Point feature for the center. Example : >>> from turfpy.measurement import center >>> from geojson import Feature, FeatureCollection, Point >>> f1 = Feature(geometry=Point((-97.522259, 35.4691))) >>> f2 = Feature(geometry=Point((-97.502754, 35.463455))) >>> f3 = Feature(geometry=Point((-97.508269, 35.463245))) >>> feature_collection = FeatureCollection([f1, f2, f3]) >>> feature = center(feature_collection) """ bounding_box = bbox(geojson) x = (bounding_box[0] + bounding_box[2]) / 2 y = (bounding_box[1] + bounding_box[3]) / 2 point = Point((x, y)) center_feature = Feature(geometry=point) if properties is None: properties = dict() if "properties" in properties: center_feature.properties = properties["properties"] elif "properties" not in properties: center_feature.properties = {} if "id" in properties: center_feature.id = properties["id"] if "bbox" in properties: center_feature.bbox = properties["bbox"] return center_feature ``` -------------------------------- ### along function with docstring and docstring example Source: https://turfpy.readthedocs.io/en/latest/_modules/turfpy/measurement.html Defines the `along` function that identifies a point at a specified distance along a LineString. The docstring includes an example usage in the doctest format. ```python [docs]def along(line: Feature, dist, unit: str = "km") -> Feature: """ This function is used identify a Point at a specified distance along a LineString. :param line: LineString on which the point to be identified :param dist: Distance from the start of the LineString :param unit: unit of distance :return: Feature : Point at the distance on the LineString passed Example : >>> from turfpy.measurement import along >>> from geojson import LineString, Feature >>> ls = Feature(geometry=LineString([(-83, 30), (-84, 36), (-78, 41)])) >>> along(ls,200,'mi') """ if line["type"] == "Feature": geom = line["geometry"] else: geom = line ``` -------------------------------- ### destination function with docstring and docstring example Source: https://turfpy.readthedocs.io/en/latest/_modules/turfpy/measurement.html Defines the `destination` function that calculates the destination point given an origin, distance, and bearing. The docstring includes an example usage in the doctest format. ```python [docs]def destination( origin: Union[Feature, Point], distance, bearing, options: dict = {} ) -> Feature: """ Takes a Point and calculates the location of a destination point given a distance in degrees, radians, miles, or kilometers and bearing in degrees. :param origin: Start point. :param distance: distance upto which the destination is from origin. :param bearing: Direction in which is the destination is from origin. :param options: Option like units of distance and properties to be passed to destination point feature, value for units are 'mi', 'km', 'deg' and 'rad'. :return: Feature: destination point in at the given distance and given direction. Example: >>> from turfpy.measurement import destination >>> from geojson import Point, Feature >>> origin = Feature(geometry=Point([-75.343, 39.984])) >>> distance = 50 >>> bearing = 90 >>> options = {'units': 'mi'} >>> destination(origin,distance,bearing,options) """ coordinates1 = get_coord(origin) longitude1 = radians(float(coordinates1[0])) latitude1 = radians(float(coordinates1[1])) bearingRad = radians(float(bearing)) if "units" in options: radian = length_to_radians(distance, options["units"]) else: radian = length_to_radians(distance) latitude2 = asin( (sin(latitude1) * cos(radian)) + (cos(latitude1) * sin(radian) * cos(bearingRad)) ) longitude2 = longitude1 + atan2( sin(bearingRad) * sin(radian) * cos(latitude1), cos(radian) - sin(latitude1) * sin(latitude2), ) lng = degrees(longitude2) lat = degrees(latitude2) point = Point((lng, lat)) return Feature( geometry=point, properties=options["properties"] if "properties" in options else {}, ) ``` -------------------------------- ### length function with docstring and docstring example Source: https://turfpy.readthedocs.io/en/latest/_modules/turfpy/measurement.html Defines the `length` function that measures the length of a GeoJSON object in specified units. The docstring includes an example usage in the doctest format. ```python [docs]def length(geojson, units: str = "km"): """ Takes a geojson and measures its length in the specified units. :param geojson: geojson for which the length is to be determined. :param units: units in which length is to be returned. :return: length of the geojson in specified units. Example: >>> from turfpy.measurement import length >>> from geojson import LineString >>> ls = LineString([(115, -32), (131, -22), (143, -25), (150, -34)]) >>> length(ls) """ def _callback_segment_reduce(previous_value, segment): coords = segment["geometry"]["coordinates"] return previous_value + distance( Feature(geometry=Point(coords[0])), Feature(geometry=Point(coords[1])), units ) return segment_reduce(geojson, _callback_segment_reduce, 0) ``` -------------------------------- ### Basic bbox_clip example Source: https://turfpy.readthedocs.io/en/latest/transformations/bbox_clip.html Clips a polygon Feature to a bounding box and prints the resulting GeoJSON. The output shows the clipped polygon coordinates. ```python import json from turfpy.transformation import bbox_clip from geojson import Feature f = Feature(geometry={"coordinates": [[[2, 2], [8, 4], [12, 8], [3, 7], [2, 2]]], "type": "Polygon"}) bbox = [0, 0, 10, 10] bc = bbox_clip(f, bbox) print(json.dumps(bc, indent=2, sort_keys=True)) ``` ```json { "geometry": { "coordinates": [ [ [ 10.0, 7.777778 ], [ 10.0, 6.0 ], [ 8.0, 4.0 ], [ 2.0, 2.0 ], [ 3.0, 7.0 ], [ 10.0, 7.777778 ] ] ], "type": "Polygon" }, "properties": {}, "type": "Feature" } ``` -------------------------------- ### centroid function with docstring and docstring example Source: https://turfpy.readthedocs.io/en/latest/_modules/turfpy/measurement.html Defines the `centroid` function that calculates the centroid of input features using the mean of all vertices. The docstring includes an example usage in the doctest format. ```python [docs]def centroid(geojson, properties: dict = None) -> Feature: """ Takes one or more features and calculates the centroid using the mean of all vertices. :param geojson: Input features :param properties: Properties to be set to the output Feature point :return: Feature: Point feature which is the centroid of the given features Example: >>> from turfpy.measurement import centroid >>> from geojson import Polygon >>> polygon = Polygon([((-81, 41), (-88, 36), (-84, 31), (-80, 33), (-77, 39), (-81, 41))]) >>> centroid(polygon) """ x_sum = 0 y_sum = 0 length = 0 def _callback_coord_each( coord, coord_index, feature_index, multi_feature_index, geometry_index ): nonlocal x_sum, y_sum, length x_sum += coord[0] y_sum += coord[1] length += 1 coord_each(geojson, _callback_coord_each) point = Point((x_sum / length, y_sum / length)) return Feature(geometry=point, properties=properties if properties else {}) ``` -------------------------------- ### Basic boolean_point_in_polygon example Source: https://turfpy.readthedocs.io/en/latest/measurements/point_in_polygon.html Imports boolean_point_in_polygon from turfpy.measurement and creates a Point and MultiPolygon Feature. Calls the function with these features and prints the result, which is True. ```python from turfpy.measurement import boolean_point_in_polygon from geojson import Point, MultiPolygon, Feature point = Feature(geometry=Point([-77, 44])) polygon = Feature(geometry=MultiPolygon([([(-81, 41), (-81, 47), (-72, 47), (-72, 41), (-81, 41)],), ([(3.78, 9.28), (-130.91, 1.52), (35.12, 72.234), (3.78, 9.28)],)])) boolean_point_in_polygon(point, polygon) ``` ```python True ``` -------------------------------- ### destination(origin, distance, bearing, options) Source: https://turfpy.readthedocs.io/en/latest/_modules/turfpy/measurement.html Function to calculate the destination point from a starting point given distance and bearing. ```APIDOC ## destination(origin, distance, bearing, options) ### Description Takes a Point and calculates the location of a destination point given a distance in degrees, radians, miles, or kilometers and bearing in degrees. ### Parameters - **origin** (Feature|Point) - Required - Start point. - **distance** (number) - Required - distance upto which the destination is from origin. - **bearing** (number) - Required - Direction in which is the destination is from origin. - **options** (dict) - Optional - Option like units of distance and properties to be passed to destination point feature, value for units are 'mi', 'km', 'deg' and 'rad'. ### Returns - **Feature** - destination point in at the given distance and given direction. ### Example ```python >>> from turfpy.measurement import destination >>> from geojson import Point, Feature >>> origin = Feature(geometry=Point([-75.343, 39.984])) >>> distance = 50 >>> bearing = 90 >>> options = {'units': 'mi'} >>> destination(origin,distance,bearing,options) ``` ``` -------------------------------- ### Calculate distance between two points Source: https://turfpy.readthedocs.io/en/latest/_modules/turfpy/measurement.html Example usage of the distance function. It creates two Point features and calls measurement.distance to calculate the distance between them in kilometers by default. ```python from turfpy import measurement >>> from geojson import Point, Feature >>> start = Feature(geometry=Point((-75.343, 39.984))) >>> end = Feature(geometry=Point((-75.534, 39.123))) >>> measurement.distance(start,end) ``` -------------------------------- ### bearing(start, end, final=False) Source: https://turfpy.readthedocs.io/en/latest/_modules/turfpy/measurement.html Calculates the geographic bearing between two Point features. Optionally calculates the final bearing if the final parameter is set to True. ```APIDOC ## bearing(start, end, final=False) ### Description Takes two Point features and finds the geographic bearing between them. The bearing is the angle from north, measured clockwise, between the start and end points. ### Parameters - **start** (Feature) - Required - A Feature object representing the start point. - **end** (Feature) - Required - A Feature object representing the end point. - **final** (bool) - Optional - If True, calculates the final bearing instead of the initial bearing. ### Returns - **float** - The calculated bearing in degrees. ### Example ```python from geojson import Point, Feature from turfpy import measurement start = Feature(geometry=Point((-75.343, 39.984))) end = Feature(geometry=Point((-75.534, 39.123))) measurement.bearing(start, end) ``` ``` -------------------------------- ### point_on_feature function Source: https://turfpy.readthedocs.io/en/latest/_modules/turfpy/measurement.html This is the source code for the `point_on_feature` function in the `turfpy.measurement` module. It takes a Feature or FeatureCollection and returns a Point guaranteed to be on the surface of the feature. It normalizes the input using `_normalize` and then computes the centroid using the `centroid` function. The docstring includes an example usage with `from turfpy.measurement import point_on_feature` and `from geojson import Polygon, Feature`. ```python [docs]def point_on_feature(geojson) -> Feature: """ Takes a Feature or FeatureCollection and returns a Point guaranteed to be on the surface of the feature. :param geojson: Feature or FeatureCollection on which the Point is to be found. :return: Feature point which on the provided feature. Example: >>> from turfpy.measurement import point_on_feature >>> from geojson import Polygon, Feature >>> point = Polygon([((116, -36), (131, -32), (146, -43), (155, -25), (133, -9), (111, -22), (116, -36))]) >>> feature = Feature(geometry=point) >>> point_on_feature(feature) """ fc = _normalize(geojson) cent = centroid(fc) ``` -------------------------------- ### midpoint function Source: https://turfpy.readthedocs.io/en/latest/_modules/turfpy/measurement.html This is the source code for the `midpoint` function in the `turfpy.measurement` module. It calculates the midpoint between two given points by computing the distance and bearing between them, then using the `destination` function to find the point at half the distance. The docstring includes an example usage with `from turfpy.measurement import midpoint` and `from geojson import Point, Feature`. ```python [docs]def midpoint(point1: Feature, point2: Feature) -> Feature: """ This function is used to get midpoint between any the two points. :param point1: First point. :param point2: Second point. :return: Feature: Point which is the midpoint of the two points given as input. Example: >>> from turfpy.measurement import midpoint >>> from geojson import Point, Feature >>> point1 = Feature(geometry=Point((144.834823, -37.771257))) >>> point2 = Feature(geometry=Point((145.14244, -37.830937))) >>> midpoint(point1, point2) """ dist = distance(point1, point2) heading = bearing(point1, point2) midpoint = destination(point1, dist / 2, heading) return midpoint ``` -------------------------------- ### Basic line_intersect example Source: https://turfpy.readthedocs.io/en/latest/misc/line_intersect.html Shows how to use line_intersect with two LineString features. The function returns a FeatureCollection containing the intersection point. Requires Rtree or pygeos to be installed. ```python from geojson import LineString, Feature from turfpy.misc import line_intersect l1 = Feature(geometry=LineString([[126, -11], [129, -21]])) l2 = Feature(geometry=LineString([[123, -18], [131, -14]])) line_intersect(l1, l2) ``` ```json {"features": [{"geometry": {"coordinates": [127.434783, -15.782609], "type": "Point"}, "properties": {}, "type": "Feature"}], "type": "FeatureCollection"} ``` -------------------------------- ### Get point on feature surface with point_on_feature Source: https://turfpy.readthedocs.io/en/latest/turfpy.measurement.html Returns a Point Feature guaranteed to be on the surface of the provided Feature or FeatureCollection. The example creates a Polygon Feature and calls point_on_feature on it. ```python >>> from turfpy.measurement import point_on_feature >>> from geojson import Polygon, Feature >>> point = Polygon([((116, -36), (131, -32), (146, -43), (155, -25), (133, -9), (111, -22), (116, -36))]) >>> feature = Feature(geometry=point) >>> point_on_feature(feature) ``` -------------------------------- ### Interactive example with ipyleaflet Source: https://turfpy.readthedocs.io/en/latest/transformations/transform_translate.html Creates an interactive map using ipyleaflet to visualize the original and translated features. The translated feature is styled in red and a layers control is added. ```python from ipyleaflet import Map, GeoJSON, LayersControl original = GeoJSON(name='Original', data=f) rotated = GeoJSON(name='Translated', data=transform_translate(f, 100, 35, mutate=True), style={'color': 'red'}) m = Map(center=[30.18519925274955, 2.939529418945313], zoom=5) m.add_layer(original) m.add_layer(rotated) control = LayersControl(position='topright') m.add_control(control) m ``` -------------------------------- ### Calculate rhumb destination with turfpy.rhumb_destination Source: https://turfpy.readthedocs.io/en/latest/measurements/rhumb_destination.html Computes the destination point along a rhumb line from a start point, given distance and bearing. The example uses a distance of 50 miles and a bearing of 90 degrees, and prints the resulting GeoJSON Feature. The output shows the destination coordinates and preserves the marker-color property. ```python import json from turfpy.measurement import rhumb_destination from geojson import Point, Feature start = Feature(geometry=Point([-75.343, 39.984]), properties={"marker-color": "F00"}) distance = 50 bearing = 90 rd = rhumb_destination(start, distance, bearing, {'units':'mi', 'properties': {"marker-color": "F00"}}) print(json.dumps(rd, indent=2, sort_keys=True)) ``` ```json { "geometry": { "coordinates": [ -74.398553, 39.984 ], "type": "Point" }, "properties": { "marker-color": "F00" }, "type": "Feature" } ```