### Run Turf.js Helpers Examples Source: https://github.com/dartclub/turf_dart/blob/main/test/examples/helpers/README.md Execute the example code to see the output of the turf_dart helper functions. ```bash dart test/examples/helpers/helpers_example.dart ``` -------------------------------- ### Install Dependencies Source: https://github.com/dartclub/turf_dart/blob/main/CONTRIBUTING.md Navigate to the project's folder and install its dependencies using Dart Pub. ```bash dart pub get ``` -------------------------------- ### Install Turf Package Source: https://github.com/dartclub/turf_dart/blob/main/_autodocs/10-quick-start-guide.md Run this command in your terminal to install the turf package after adding it to pubspec.yaml. ```bash dart pub add turf ``` -------------------------------- ### Create a LineString Instance Source: https://github.com/dartclub/turf_dart/blob/main/_autodocs/09-types-and-data-structures.md Example of creating a LineString with multiple coordinate points. ```dart var line = LineString(coordinates: [ Position(0, 0), Position(5, 5), Position(10, 10), ]); ``` -------------------------------- ### Example Usage of Turf.dart Library Source: https://github.com/dartclub/turf_dart/blob/main/CONTRIBUTING.md Demonstrates how to import and use the Turf.dart library for geometric operations, specifically using segmentReduce with a Polygon. ```dart import 'package:turf/helpers.dart'; import 'package:turf/src/line_segment.dart'; Feature poly = Feature( geometry: Polygon(coordinates: [ [ Position(0, 0), Position(2, 2), Position(0, 1), Position(0, 0), ], [ Position(0, 0), Position(1, 1), Position(0, 1), Position(0, 0), ], ]), ); var total = segmentReduce(poly, (previousValue, currentSegment, initialValue, featureIndex, multiFeatureIndex, geometryIndex, segmentIndex) { if (previousValue != null) { previousValue++; } return previousValue; }, 0, combineNestedGeometries: false); // total.length == 6 ``` -------------------------------- ### Create a Simple Polygon Instance Source: https://github.com/dartclub/turf_dart/blob/main/_autodocs/09-types-and-data-structures.md Example of creating a Polygon with a single outer ring. ```dart // Simple polygon var poly = Polygon(coordinates: [ [ Position(0, 0), Position(10, 0), Position(10, 10), Position(0, 10), Position(0, 0) ] ]); ``` -------------------------------- ### Run Output Generator Source: https://github.com/dartclub/turf_dart/blob/main/test/examples/point_on_feature/README.md Run this command to regenerate the output GeoJSON files for the examples. ```bash dart test/examples/point_on_feature/generate_outputs.dart ``` -------------------------------- ### Create a Feature Instance Source: https://github.com/dartclub/turf_dart/blob/main/_autodocs/09-types-and-data-structures.md Example of creating a Feature with Point geometry, properties, ID, and bounding box. Access its components using dot notation. ```dart var feature = Feature( geometry: Point(coordinates: Position(10, 45)), properties: { 'name': 'My Location', 'population': 10000, 'elevation': 1000.5, }, id: 'loc-001', bbox: BBox.named(lng1: 10, lat1: 45, lng2: 10, lat2: 45), ); // Access print(feature.geometry?.coordinates); // Position(10, 45) print(feature.properties?['name']); // 'My Location' print(feature.id); // 'loc-001' ``` -------------------------------- ### Create a FeatureCollection Instance Source: https://github.com/dartclub/turf_dart/blob/main/_autodocs/09-types-and-data-structures.md Example of creating a FeatureCollection with two Point Features. It includes a bounding box encompassing all features. ```dart var collection = FeatureCollection( features: [ Feature( geometry: Point(coordinates: Position(0, 0)), properties: {'id': 1}, ), Feature( geometry: Point(coordinates: Position(1, 1)), properties: {'id': 2}, ), ], bbox: BBox.named(lng1: 0, lat1: 0, lng2: 1, lat2: 1), ); ``` -------------------------------- ### Polygon Segment Reduction Example Source: https://github.com/dartclub/turf_dart/blob/main/README.md Demonstrates how to use segmentReduce to process segments of a GeoJSON Polygon. Ensure the turf and geotypes libraries are imported. ```dart import 'package:turf/helpers.dart'; import 'package:turf/src/line_segment.dart'; Feature poly = Feature( geometry: Polygon(coordinates: [ [ Position(0, 0), Position(2, 2), Position(0, 1), Position(0, 0), ], [ Position(0, 0), Position(1, 1), Position(0, 1), Position(0, 0), ], ]), ); void main() { var total = segmentReduce( poly, (previousValue, currentSegment, initialValue, featureIndex, multiFeatureIndex, geometryIndex, segmentIndex) { if (previousValue != null) { previousValue++; } return previousValue; }, 0, combineNestedGeometries: false, ); print(total); // total == 6 } ``` -------------------------------- ### Create a Polygon Instance with a Hole Source: https://github.com/dartclub/turf_dart/blob/main/_autodocs/09-types-and-data-structures.md Example of creating a Polygon with an outer ring and an inner hole. ```dart // Polygon with hole var polyWithHole = Polygon(coordinates: [ [ // Outer ring Position(0, 0), Position(10, 0), Position(10, 10), Position(0, 10), Position(0, 0) ], [ // Hole Position(2, 2), Position(4, 2), Position(4, 4), Position(2, 4), Position(2, 2) ] ]); ``` -------------------------------- ### Create and Access BBox Instance Source: https://github.com/dartclub/turf_dart/blob/main/_autodocs/09-types-and-data-structures.md Example of creating a BBox using the named constructor and accessing its coordinates via array or named properties. The format is [minLng, minLat, maxLng, maxLat]. ```dart var bbox = BBox.named( lng1: -10.5, lat1: 45.2, lng2: 20.3, lat2: 55.8, ); // Array access var minLng = bbox[0]; // -10.5 var minLat = bbox[1]; // 45.2 var maxLng = bbox[2]; // 20.3 var maxLat = bbox[3]; // 55.8 // Named access var west = bbox.lng1; // -10.5 var south = bbox.lat1; // 45.2 ``` -------------------------------- ### Navigate to Destination Source: https://github.com/dartclub/turf_dart/blob/main/_autodocs/03-geometry-operations.md Calculates the destination point given a starting point, distance, bearing, and unit. ```dart var currentLocation = Point(coordinates: Position(-75.343, 39.984)); var distance = 100; var bearing = 45; // northeast var newLocation = destination(currentLocation, distance, bearing, Unit.kilometers); ``` -------------------------------- ### Turf.js Dart Installation in pubspec.yaml Source: https://github.com/dartclub/turf_dart/blob/main/_autodocs/00-index.md Specifies the Turf.js package dependency in your Dart project's pubspec.yaml file. Ensure you use a compatible version. ```yaml dependencies: turf: ^0.0.12 ``` -------------------------------- ### lineSliceAlong Source: https://github.com/dartclub/turf_dart/blob/main/_autodocs/06-line-operations.md Extracts a section of a line based on distance from the start. It takes a start distance and a stop distance along the line and returns the corresponding segment. The unit of distance can be specified. ```APIDOC ## lineSliceAlong ### Description Extracts a section of a line based on distance from the start. It takes a start distance and a stop distance along the line and returns the corresponding segment. The unit of distance can be specified. ### Parameters #### Path Parameters - **startDist** (num) - Required - Start distance along line - **stopDist** (num) - Required - Stop distance along line - **line** (Feature) - Required - LineString to slice #### Query Parameters - **unit** (Unit) - Optional - Unit of distance (default: kilometers) ### Returns `Feature` — Sliced line segment ### Example ```dart var line = Feature( geometry: LineString(coordinates: [ Position(0, 0), Position(5, 5), Position(10, 10), ]), ); // Extract 2-8 km of the line var sliced = lineSliceAlong(2, 8, line, unit: Unit.kilometers); ``` ``` -------------------------------- ### Navigate by Distance and Bearing Source: https://github.com/dartclub/turf_dart/blob/main/_autodocs/10-quick-start-guide.md Calculate a destination point given a starting point, distance, and bearing using the `destination` function. Specify the unit for distance. ```dart import 'package:turf/destination.dart'; var start = Point(coordinates: Position(0, 0)); var distance = 100; var bearing = 45; // Northeast var destination = destination(start, distance, bearing, Unit.kilometers); print(destination.coordinates); ``` -------------------------------- ### Handle Common Turf.js Errors Source: https://github.com/dartclub/turf_dart/blob/main/_autodocs/10-quick-start-guide.md Illustrates how to catch specific errors like invalid units, null/missing geometries, and invalid coordinate data. Provides examples for common exception scenarios. ```dart // Invalid unit try { radiansToLength(1.0, Unit.hectares); // Invalid unit } on Exception catch (e) { print('$e'); // Exception: Unit.hectares units is invalid } // Null/missing geometry try { var geom = getGeom(featureCollection); // FeatureCollection not allowed } on Exception catch (e) { print('$e'); // Cannot retrieve single Geometry from FeatureCollection } // Invalid coordinates try { var line = LineString(coordinates: [Position(0, 0)]); // Need ≥2 coords } on Exception catch (e) { print('$e'); } ``` -------------------------------- ### destination Source: https://github.com/dartclub/turf_dart/blob/main/_autodocs/03-geometry-operations.md Calculates a destination point given a starting point, distance, and bearing. Supports various units for distance. ```APIDOC ## destination ### Description Calculates a destination point given distance and bearing from an origin. ### Method ```dart Point destination( Point origin, num distance, num bearing, [Unit unit = Unit.kilometers] ) ``` ### Parameters #### Path Parameters - **origin** (Point) - Required - Starting point - **distance** (num) - Required - Distance to travel - **bearing** (num) - Required - Direction in degrees (0° = north, 90° = east) - **unit** (Unit) - Optional - Unit of distance (kilometers, miles, meters, etc.) ### Returns `Point` — Destination point ### Example ```dart var startPoint = Point(coordinates: Position(-75.343, 39.984)); var distance = 50; var bearing = 90; // due east var endPoint = destination(startPoint, distance, bearing, Unit.miles); // Result: Point ~50 miles east of starting point ``` ``` -------------------------------- ### Calculate Initial Bearing Between Points Source: https://github.com/dartclub/turf_dart/blob/main/_autodocs/02-distance-bearing.md Use the `bearing` function to determine the initial compass direction from a starting `Point` to an ending `Point`. The result is in degrees (0-360). ```dart var point1 = Point(coordinates: Position(-75.343, 39.984)); var point2 = Point(coordinates: Position(-75.543, 39.123)); var initialBearing = bearing(point1, point2); // ~215.5° (southwest) var finalBearing = bearing(point1, point2, calcFinal: true); // ~211.2° ``` -------------------------------- ### Calculate Destination Point Source: https://github.com/dartclub/turf_dart/blob/main/_autodocs/03-geometry-operations.md Calculates a destination point given a starting point, distance, and bearing. Supports various units for distance. ```dart var startPoint = Point(coordinates: Position(-75.343, 39.984)); var distance = 50; var bearing = 90; // due east var endPoint = destination(startPoint, distance, bearing, Unit.miles); // Result: Point ~50 miles east of starting point ``` -------------------------------- ### calculateFinalBearing Source: https://github.com/dartclub/turf_dart/blob/main/_autodocs/02-distance-bearing.md Calculates the final bearing (reverse direction) from one point to another. This is equivalent to calling `bearing(start, end, calcFinal: true)`. ```APIDOC ## calculateFinalBearing ### Description Calculates the final bearing (reverse direction) from one point to another. ### Method ```dart num calculateFinalBearing(Point start, Point end) ``` ### Parameters #### Path Parameters - **start** (Point) - Required - Starting point - **end** (Point) - Required - Destination point ### Returns `num` — Final bearing in degrees 0-360 ### Example ```dart var finalBearing = calculateFinalBearing( Point(coordinates: Position(-75.343, 39.984)), Point(coordinates: Position(-75.543, 39.123)) ); ``` ``` -------------------------------- ### along Source: https://github.com/dartclub/turf_dart/blob/main/_autodocs/06-line-operations.md Finds a point at a specific distance along a given line. This function is useful for determining a location on a path based on a measured distance from its start. The unit of distance can be specified. ```APIDOC ## along ### Description Finds a point at a specific distance along a given line. This function is useful for determining a location on a path based on a measured distance from its start. The unit of distance can be specified. ### Parameters #### Path Parameters - **line** (Feature) - Required - LineString to traverse - **distance** (num) - Required - Distance along line #### Query Parameters - **unit** (Unit) - Optional - Unit of distance (default: kilometers) ### Returns `Feature` — Point at specified distance ### Example ```dart var line = Feature( geometry: LineString(coordinates: [ Position(0, 0), Position(5, 5), Position(10, 10), ]), ); // Find point 2 km along the line var point = along(line, 2, unit: Unit.kilometers); ``` ``` -------------------------------- ### Measure Route Properties Source: https://github.com/dartclub/turf_dart/blob/main/_autodocs/08-utility-functions.md Calculates various properties of a route represented as a LineString, including its total length, bounding box, start point, and end point. ```dart var route = Feature(geometry: ...); var routeLength = length(route, unit: Unit.kilometers); var routeBounds = envelope(route); var startPoint = route.geometry?.coordinates.first; var endPoint = route.geometry?.coordinates.last; print('Route: ${routeLength.toStringAsFixed(2)} km'); ``` -------------------------------- ### Get Bounding Box of a Geometry Source: https://github.com/dartclub/turf_dart/blob/main/_autodocs/10-quick-start-guide.md Calculate the minimum bounding box (axis-aligned) for a given geometry using the `bbox` function. The result contains the coordinates of the bounding box. ```dart import 'package:turf/bbox.dart'; var polygon = Polygon(coordinates: [[...]]); var boundingBox = bbox(polygon); print('Bounds: ${boundingBox.lng1}, ${boundingBox.lat1}, ' '${boundingBox.lng2}, ${boundingBox.lat2}'); ``` -------------------------------- ### Run Benchmarks Source: https://github.com/dartclub/turf_dart/blob/main/CONTRIBUTING.md Execute all benchmarks for the Turf.dart project using the Dart benchmark runner. ```bash dart pub run benchmark ``` -------------------------------- ### Import All Turf Modules Source: https://github.com/dartclub/turf_dart/blob/main/_autodocs/10-quick-start-guide.md Import all available types and functions from the turf library at once. ```dart import 'package:turf/turf.dart'; ``` -------------------------------- ### Run Visualization Generator Source: https://github.com/dartclub/turf_dart/blob/main/test/examples/point_on_feature/README.md Run this command to generate the combined visualization GeoJSON file. ```bash dart test/examples/point_on_feature/generate_visualization.dart ``` -------------------------------- ### Turf.dart Module Structure Source: https://github.com/dartclub/turf_dart/blob/main/CONTRIBUTING.md Illustrates the directory structure for modules within the Turf.dart project, including public API, implementation, benchmarks, and tests. ```text TURF_DART/lib/.dart // public facing API, exports the implementation │ │ │ └───src/.dart // the implementation │ └───benchmark/_benchmark.dart │ └───test/components/_test.dart // all the related tests ``` -------------------------------- ### Clone Turf.dart Repository Source: https://github.com/dartclub/turf_dart/blob/main/CONTRIBUTING.md Clone the Turf.dart repository to your local machine using Git. ```bash git clone git@github.com:dartclub/turf_dart.git ``` -------------------------------- ### Rhumb Line Bearing Calculation Source: https://github.com/dartclub/turf_dart/blob/main/_autodocs/02-distance-bearing.md Calculates the bearing along a rhumb line between a start and end point. Can optionally calculate the final bearing. ```dart num rhumbBearing(Point start, Point end, {bool calcFinal = false}) ``` ```dart var bearing = rhumbBearing( Point(coordinates: Position(-75.343, 39.984)), Point(coordinates: Position(-75.543, 39.123)) ); ``` -------------------------------- ### Create and Access Position Instances Source: https://github.com/dartclub/turf_dart/blob/main/_autodocs/09-types-and-data-structures.md Demonstrates creating Position objects with and without altitude, and accessing their coordinates. ```dart var pos1 = Position(10.5, 45.2); var pos2 = Position.named(lng: 10.5, lat: 45.2); var pos3 = Position(10.5, 45.2, 1000); // With altitude print(pos1.lng); // 10.5 print(pos1.lat); // 45.2 print(pos1[0]); // 10.5 ``` -------------------------------- ### Create and Use Typed Features Source: https://github.com/dartclub/turf_dart/blob/main/_autodocs/09-types-and-data-structures.md Demonstrates how to create typed and untyped features, and how to safely access their geometries using null-aware checks. ```dart // Typed feature Feature pointFeature = Feature( geometry: Point(coordinates: Position(10, 45)), ); // Untyped feature Feature untypedFeature = Feature( geometry: Point(coordinates: Position(10, 45)), ); // Null-safe geometry var geom = pointFeature.geometry; // Point? if (geom is Point) { print(geom.coordinates); // Guaranteed Point } ``` -------------------------------- ### Bounding Box Operations Source: https://github.com/dartclub/turf_dart/blob/main/_autodocs/09-types-and-data-structures.md Shows how to create a BBox, check if a point is within it, and convert a BBox into a Polygon. ```dart var bbox = BBox.named(lng1: -10, lat1: 0, lng2: 10, lat2: 20); // Check if point is in bbox var point = Position(5, 10); bool inBbox = (bbox[0]! <= point[0]! && bbox[1]! <= point[1]! && bbox[2]! >= point[0]! && bbox[3]! >= point[1]!) ; // Create polygon from bbox var polygon = Polygon(coordinates: [[ Position(bbox[0]!, bbox[1]!), Position(bbox[2]!, bbox[1]!), Position(bbox[2]!, bbox[3]!), Position(bbox[0]!, bbox[3]!), Position(bbox[0]!, bbox[1]!), ]]); ``` -------------------------------- ### Importing Turf.js Modules in Dart Source: https://github.com/dartclub/turf_dart/blob/main/_autodocs/00-index.md Demonstrates how to import specific modules or all of Turf.js for use in your Dart project. This allows for selective importing to reduce bundle size or importing all functions at once for convenience. ```dart import 'package:turf/helpers.dart'; // Units, conversions import 'package:turf/distance.dart'; // distance(), bearing() import 'package:turf/area.dart'; // area() import 'package:turf/bbox.dart'; // bbox() import 'package:turf/circle.dart'; // circle() import 'package:turf/centroid.dart'; // centroid() import 'package:turf/boolean.dart'; // All boolean operations import 'package:turf/meta.dart'; // coordEach, featureEach, etc. import 'package:turf/line_segment.dart'; // segmentEach, lineSegment() import 'package:turf/simplify.dart'; // simplify() import 'package:turf/line_slice.dart'; // lineSlice() import 'package:turf/nearest_point_on_line.dart';// nearestPointOnLine() import 'package:turf/line_intersect.dart'; // lineIntersect() import 'package:turf/polyline.dart'; // encode/decode polylines import 'package:turf/flatten.dart'; // flatten() import 'package:turf/explode.dart'; // explode() import 'package:turf/flip.dart'; // flip() // Or import all at once: import 'package:turf/turf.dart'; ``` -------------------------------- ### Slice a Line Between Two Points Source: https://github.com/dartclub/turf_dart/blob/main/_autodocs/10-quick-start-guide.md Extracts a segment of a LineString that falls between two specified points. Creates a new LineString from the start to end points. ```dart import 'package:turf/line_slice.dart'; var line = Feature( geometry: LineString(coordinates: [ Position(0, 0), Position(5, 5), Position(10, 10), Position(15, 15), ]), ); var sliced = lineSlice( Position(2, 2), Position(12, 12), line, ); ``` -------------------------------- ### Import Specific Turf Modules Source: https://github.com/dartclub/turf_dart/blob/main/_autodocs/10-quick-start-guide.md Import only the specific spatial analysis functions and types you need from the turf library. ```dart // All types and helpers import 'package:turf/helpers.dart'; // Spatial analysis functions (choose what you need) import 'package:turf/distance.dart'; // distance, bearing import 'package:turf/area.dart'; // area calculation import 'package:turf/bbox.dart'; // bounding box import 'package:turf/destination.dart'; // navigate by bearing import 'package:turf/circle.dart'; // buffer zones import 'package:turf/boolean.dart'; // point-in-polygon, overlaps, etc. import 'package:turf/meta.dart'; // iterate coordinates/features import 'package:turf/line_slice.dart'; // slice lines import 'package:turf/simplify.dart'; // simplify geometry ``` -------------------------------- ### Handle Exceptions with Try-Catch Source: https://github.com/dartclub/turf_dart/blob/main/_autodocs/10-quick-start-guide.md Demonstrates the use of try-catch blocks to gracefully handle potential exceptions during geospatial operations. Catches and prints any exceptions that occur. ```dart try { var result = distance(point1, point2); } on Exception catch (e) { print('Error: $e'); } ``` -------------------------------- ### Create a Buffer Zone (Circle) Source: https://github.com/dartclub/turf_dart/blob/main/_autodocs/10-quick-start-guide.md Generate a circular buffer zone around a center point using the `circle` function. Specify the radius and unit. This can be used with `booleanPointInPolygon` to check containment. ```dart import 'package:turf/circle.dart'; var center = Point(coordinates: Position(10, 45)); var bufferZone = circle(center, 5, unit: Unit.kilometers); // Creates 5 km circular buffer // Check if point is in buffer if (booleanPointInPolygon(testPoint, bufferZone.geometry!)) { print('Within buffer zone!'); } ``` -------------------------------- ### Create Geometries (Point, LineString, Polygon) Source: https://github.com/dartclub/turf_dart/blob/main/_autodocs/10-quick-start-guide.md Instantiate basic geospatial geometries like Point, LineString, and Polygon. Polygons can include holes. ```dart // Point var point = Point(coordinates: Position(10, 45)); // LineString var line = LineString(coordinates: [ Position(0, 0), Position(5, 5), Position(10, 10), ]); // Polygon (with hole) var polygon = Polygon(coordinates: [ [ // Outer ring (counterclockwise) Position(0, 0), Position(10, 0), Position(10, 10), Position(0, 10), Position(0, 0) ], [ // Hole (clockwise) Position(2, 2), Position(4, 2), Position(4, 4), Position(2, 4), Position(2, 2) ] ]); ``` -------------------------------- ### Slice a LineString by distance Source: https://github.com/dartclub/turf_dart/blob/main/_autodocs/06-line-operations.md Extracts a section of a line based on start and stop distances along its length. Supports different units for distance measurement. The function returns the sliced line segment. ```dart var line = Feature( geometry: LineString(coordinates: [ Position(0, 0), Position(5, 5), Position(10, 10), ]), ); // Extract 2-8 km of the line var sliced = lineSliceAlong(2, 8, line, unit: Unit.kilometers); ``` -------------------------------- ### Find Features Matching Area Criteria Source: https://github.com/dartclub/turf_dart/blob/main/_autodocs/05-iteration-reduction.md Filters a `FeatureCollection` to find features that meet a specific area criterion. This example iterates through features using `featureEach` and adds matching features to a new list. ```dart var matchingFeatures = []; featureEach(featureCollection, (feature, _) { if (feature.properties?['area'] as num? ?? 0 > 1000) { matchingFeatures.add(feature); } }); ``` -------------------------------- ### Spatial Index Search with Turf.js Dart Source: https://github.com/dartclub/turf_dart/blob/main/_autodocs/10-quick-start-guide.md Demonstrates how to create a grid over a region of interest and query features within each grid cell using spatial intersection checks. This is useful for optimizing searches in large geospatial datasets. ```dart var roi = BBox.named(lng1: 0, lat1: 0, lng2: 100, lat2: 100); var grid = squareGrid(roi, 10, unit: Unit.kilometers); grid.features.forEach((cell) { var cellBounds = bbox(cell); var featuresInCell = features.where((f) { var fBounds = bbox(f); // Check if bounds overlap return booleanIntersects(cell, f); }).toList(); print('Cell has ${featuresInCell.length} features'); }); ``` -------------------------------- ### Convert Closed LineString to Polygon Source: https://github.com/dartclub/turf_dart/blob/main/_autodocs/07-coordinate-manipulation.md Converts a closed LineString feature into a Polygon feature. The linestring must start and end at the same coordinate to form a valid ring. Properties can be optionally passed to the resulting polygon feature. ```dart var ring = Feature( geometry: LineString(coordinates: [ Position(0, 0), Position(5, 0), Position(5, 5), Position(0, 5), Position(0, 0) ]), ); var polygon = lineToPolygon(ring, properties: {'area': 'test'}); // Polygon with single outer ring ``` -------------------------------- ### Get a Point on a Feature Source: https://github.com/dartclub/turf_dart/blob/main/_autodocs/08-utility-functions.md This function finds a point that is guaranteed to be inside a given GeoJSON geometry or feature. It's useful for tasks like labeling or testing point containment within polygons, lines, or points. ```dart import 'package:turf/helpers.dart'; import 'package:turf/point_on_feature.dart'; var polygon = Polygon(coordinates: [[ Position(0, 0), Position(10, 0), Position(10, 10), Position(0, 10), Position(0, 0) ]]); var insidePoint = pointOnFeature(polygon); // Feature with coordinates inside the polygon // Guaranteed that booleanPointInPolygon(insidePoint.geometry?.coordinates, polygon) == true ``` -------------------------------- ### Calculate Distance Between Two Points Source: https://github.com/dartclub/turf_dart/blob/main/_autodocs/00-index.md Demonstrates how to calculate the distance between two points using the `distance` function. Ensure the `turf/helpers.dart` library is imported. ```dart import 'package:turf/helpers.dart'; void main() { var berlin = Point(coordinates: Position(13.4, 52.52)); var paris = Point(coordinates: Position(2.35, 48.85)); var dist = distance(berlin, paris, Unit.kilometers); print('Distance: $dist km'); // ~877 km } ``` -------------------------------- ### lineSlice Source: https://github.com/dartclub/turf_dart/blob/main/_autodocs/06-line-operations.md Extracts a section of a line between two specified points. The function finds the closest points on the line to the provided start and stop points and returns the segment between them. It preserves the original feature properties and returns an empty line if the slice is invalid. ```APIDOC ## lineSlice ### Description Extracts a section of a line between two points. The function finds the closest points on the line to the provided start and stop points and returns the segment between them. It preserves the original feature properties and returns an empty line if the slice is invalid. ### Parameters #### Path Parameters - **start** (Position) - Required - Starting point [longitude, latitude] - **stop** (Position) - Required - Ending point [longitude, latitude] - **line** (Feature) - Required - LineString to slice ### Returns `Feature` — Sliced line segment ### Example ```dart var line = Feature( geometry: LineString(coordinates: [ Position(0, 0), Position(5, 5), Position(10, 10), ]), ); var sliced = lineSlice( Position(1, 1), Position(9, 9), line, ); // Returns line from ~(1,1) to ~(9,9) ``` ``` -------------------------------- ### simplify Source: https://github.com/dartclub/turf_dart/blob/main/_autodocs/06-line-operations.md Simplifies a LineString using the Ramer-Douglas-Peucker algorithm. It reduces the number of vertices in a line while preserving its general shape, based on a specified tolerance. An option to use only RDP for highest quality is available. ```APIDOC ## simplify ### Description Simplifies a LineString using the Ramer-Douglas-Peucker algorithm. It reduces the number of vertices in a line while preserving its general shape, based on a specified tolerance. An option to use only RDP for highest quality is available. ### Parameters #### Path Parameters - **points** (Feature) - Required - LineString to simplify #### Query Parameters - **tolerance** (double) - Optional - Simplification tolerance (higher = more simplified) (default: 1) - **highestQuality** (bool) - Optional - If true, uses only RDP; if false, combines radial distance and RDP (default: false) ### Returns `Feature` — Simplified line ### Example ```dart var complexLine = Feature( geometry: LineString(coordinates: [ Position(0, 0), Position(0.1, 0.1), Position(0.2, 0.2), Position(5, 5), Position(5.1, 5.1), Position(5.2, 5.2), Position(10, 10), ]), ); var simplified = simplify(complexLine, tolerance: 0.5); // Removes near-duplicate vertices, keeps key turning points ``` ``` -------------------------------- ### Create Features (Geometry + Properties) Source: https://github.com/dartclub/turf_dart/blob/main/_autodocs/10-quick-start-guide.md Create a Feature object by combining a geometry with arbitrary properties and an optional ID. Access geometry and properties using dot or bracket notation. ```dart var feature = Feature( geometry: Point(coordinates: Position(10, 45)), properties: { 'name': 'Berlin', 'population': 3645000, 'country': 'Germany', }, id: 'berlin-01', ); // Access print(feature.geometry?.coordinates); print(feature.properties?['name']); ``` -------------------------------- ### Slice a LineString between two points Source: https://github.com/dartclub/turf_dart/blob/main/_autodocs/06-line-operations.md Extracts a section of a line between two specified points. The function uses the closest points on the line to the provided start and stop points. It preserves original feature properties and returns an empty line if the slice is invalid. ```dart var line = Feature( geometry: LineString(coordinates: [ Position(0, 0), Position(5, 5), Position(10, 10), ]), ); var sliced = lineSlice( Position(1, 1), Position(9, 9), line, ); // Returns line from ~(1,1) to ~(9,9) ``` -------------------------------- ### Create Labels for Polygons Source: https://github.com/dartclub/turf_dart/blob/main/_autodocs/08-utility-functions.md Finds a guaranteed interior point for a given polygon, which is suitable for placing labels. This ensures the label point is within the polygon's boundaries. ```dart var polygon = Feature( geometry: Polygon(coordinates: [ [Position(0, 0), Position(10, 0), Position(10, 10), Position(0, 10), Position(0, 0)] ]), properties: {'name': 'Region A'} ); // Find guaranteed interior point for label placement var labelPoint = pointOnFeature(polygon); ``` -------------------------------- ### Generate Point Grid Source: https://github.com/dartclub/turf_dart/blob/main/_autodocs/08-utility-functions.md Creates a grid of points within a specified bounding box. Use this to sample locations or define points for further spatial processing. The cellSize determines the spacing between points. ```dart FeatureCollection pointGrid( BBox bbox, num cellSize, {Unit unit = Unit.kilometers} ) ``` ```dart var bbox = BBox.named(lng1: -10, lat1: 0, lng2: 10, lat2: 20); var grid = pointGrid(bbox, 5, unit: Unit.kilometers); // Creates grid of points 5 km apart within bbox ``` -------------------------------- ### Run Component Tests Source: https://github.com/dartclub/turf_dart/blob/main/CONTRIBUTING.md Execute tests for a specific component within the Turf.dart project using the Dart test runner. ```bash dart test test/components/XXX.dart ``` -------------------------------- ### Create Buffer Zone Source: https://github.com/dartclub/turf_dart/blob/main/_autodocs/03-geometry-operations.md Creates a circular buffer zone around a given point with a specified radius and unit. ```dart var point = Point(coordinates: Position(10, 45)); var bufferZone = circle(point, 5, unit: Unit.kilometers); // Creates 5 km buffer around point ``` -------------------------------- ### Reuse Bounding Box (BBox) Source: https://github.com/dartclub/turf_dart/blob/main/_autodocs/10-quick-start-guide.md Optimizes performance by reusing a cached bounding box instead of recomputing it. Use `recompute: false` when the bbox is already known. ```dart // Don't recompute bbox if already cached var box = bbox(geometry, recompute: false); ``` -------------------------------- ### pointGrid Source: https://github.com/dartclub/turf_dart/blob/main/_autodocs/08-utility-functions.md Generates a grid of points within a bounding box. This function is useful for creating sample points for spatial analysis or data distribution visualization. ```APIDOC ## pointGrid ### Description Generates a grid of points within a bounding box. ### Method ```dart FeatureCollection pointGrid(BBox bbox, num cellSize, {Unit unit = Unit.kilometers}) ``` ### Parameters #### Path Parameters - **bbox** (BBox) - Required - Bounding box [minLng, minLat, maxLng, maxLat] - **cellSize** (num) - Required - Distance between points - **unit** (Unit) - Optional - Unit of cellSize (defaults to kilometers) ### Returns `FeatureCollection` — Grid of points ### Example ```dart var bbox = BBox.named(lng1: -10, lat1: 0, lng2: 10, lat2: 20); var grid = pointGrid(bbox, 5, unit: Unit.kilometers); // Creates grid of points 5 km apart within bbox ``` ``` -------------------------------- ### triangleGrid Source: https://github.com/dartclub/turf_dart/blob/main/_autodocs/08-utility-functions.md Generates a grid of triangular polygons within a bounding box. Suitable for creating triangular tessellations. ```APIDOC ## triangleGrid ### Description Generates a grid of triangular polygons within a bounding box. ### Method Dart Function ### Signature FeatureCollection triangleGrid(BBox bbox, num cellSize, {Unit unit = Unit.kilometers}) ### Parameters #### Path Parameters - **bbox** (BBox) - Required - Bounding box - **cellSize** (num) - Required - Size of triangles - **unit** (Unit) - Optional - Unit of cellSize (default: kilometers) ### Returns `FeatureCollection` — Grid of triangular polygons ``` -------------------------------- ### Create Positions (Coordinates) Source: https://github.com/dartclub/turf_dart/blob/main/_autodocs/10-quick-start-guide.md Create Position objects representing geographic coordinates using positional or named constructors. Supports longitude, latitude, and altitude. ```dart // Indexed: [longitude, latitude] var pos = Position(10.5, 45.2); // Named constructor var pos = Position.named(lng: 10.5, lat: 45.2); // With altitude var pos3d = Position(10.5, 45.2, 1000); // Access print(pos.lng); // 10.5 print(pos.lat); // 45.2 print(pos[0]); // 10.5 print(pos[1]); // 45.2 ``` -------------------------------- ### bearing Source: https://github.com/dartclub/turf_dart/blob/main/_autodocs/02-distance-bearing.md Calculates the initial bearing (forward azimuth) from one point to another. Can also calculate the final bearing if specified. ```APIDOC ## bearing ### Description Calculates the initial bearing (forward azimuth) from one point to another. ### Method ```dart num bearing(Point start, Point end, {bool calcFinal = false}) ``` ### Parameters #### Path Parameters - **start** (Point) - Required - Starting point - **end** (Point) - Required - Destination point - **calcFinal** (bool) - Optional - If true, returns final bearing (reverse bearing); if false, returns initial bearing ### Returns `num` — Bearing in degrees 0-360 ### Example ```dart var point1 = Point(coordinates: Position(-75.343, 39.984)); var point2 = Point(coordinates: Position(-75.543, 39.123)); var initialBearing = bearing(point1, point2); var finalBearing = bearing(point1, point2, calcFinal: true); ``` ``` -------------------------------- ### Use Raw Functions for Bulk Operations Source: https://github.com/dartclub/turf_dart/blob/main/_autodocs/10-quick-start-guide.md Improves performance for processing many coordinates by using raw functions that avoid Point wrapping. Suitable for high-volume coordinate calculations. ```dart // Faster for many coordinates for (var coord in coords) { var dist = distanceRaw(start, coord); // Avoid Point wrapping } ``` -------------------------------- ### hexGrid Source: https://github.com/dartclub/turf_dart/blob/main/_autodocs/08-utility-functions.md Generates a grid of hexagonal polygons within a bounding box. Useful for spatial analysis and creating honeycomb patterns. ```APIDOC ## hexGrid ### Description Generates a grid of hexagonal polygons within a bounding box. ### Method Dart Function ### Signature FeatureCollection hexGrid(BBox bbox, num cellSize, {Unit unit = Unit.kilometers}) ### Parameters #### Path Parameters - **bbox** (BBox) - Required - Bounding box - **cellSize** (num) - Required - Size of hexagons - **unit** (Unit) - Optional - Unit of cellSize (default: kilometers) ### Returns `FeatureCollection` — Grid of hexagonal polygons ### Example ```dart var bbox = BBox.named(lng1: 0, lat1: 0, lng2: 10, lat2: 10); var hexes = hexGrid(bbox, 1, unit: Unit.kilometers); // Creates honeycomb pattern of hexagons ``` ``` -------------------------------- ### Generate Square Grid Source: https://github.com/dartclub/turf_dart/blob/main/_autodocs/08-utility-functions.md Generates a grid of square polygons within a given bounding box. This is useful for creating tessellations or dividing an area into regular square cells for analysis. ```dart FeatureCollection squareGrid( BBox bbox, num cellSize, {Unit unit = Unit.kilometers} ) ``` ```dart var bbox = BBox.named(lng1: 0, lat1: 0, lng2: 10, lat2: 10); var grid = squareGrid(bbox, 1, unit: Unit.kilometers); // Creates grid of 1km x 1km squares ``` -------------------------------- ### Feature Collections with Mixed Types Source: https://github.com/dartclub/turf_dart/blob/main/_autodocs/09-types-and-data-structures.md Illustrates creating a FeatureCollection with diverse geometry types and filtering it to extract specific feature types, such as only Point features. ```dart var mixed = FeatureCollection( features: [ Feature(geometry: Point(coordinates: Position(0, 0))), Feature(geometry: LineString(coordinates: [ Position(1, 1), Position(2, 2) ])), Feature(geometry: Polygon(coordinates: [[ Position(3, 3), Position(4, 3), Position(4, 4), Position(3, 3) ]])), ], ); // Filter by type var pointFeatures = mixed.features .whereType>() .toList(); ``` -------------------------------- ### Calculate Round-Trip Distance Source: https://github.com/dartclub/turf_dart/blob/main/_autodocs/02-distance-bearing.md Demonstrates calculating the total distance for a round trip by summing the distances in both directions between two points. ```javascript var pointA = Point(coordinates: Position(-75.343, 39.984)); var pointB = Point(coordinates: Position(-75.543, 39.123)); var distAtoB = distance(pointA, pointB, Unit.kilometers); var distBtoA = distance(pointB, pointA, Unit.kilometers); var totalDistance = distAtoB + distBtoA; ``` -------------------------------- ### simplify Source: https://github.com/dartclub/turf_dart/blob/main/_autodocs/06-line-operations.md Simplifies a LineString feature by reducing the number of vertices while preserving its general shape. ```APIDOC ## simplify ### Description Reduces points while maintaining shape. ### Method ```dart var simplified = simplify(gpsTrack, tolerance: 0.1); ``` ### Parameters #### Path Parameters - **line** (Feature) - Required - The line to simplify. - **tolerance** (double) - Required - The tolerance for simplification. Smaller values result in more vertices. - **highQuality** (bool?) - Optional - Whether to use a high-quality simplification algorithm. ### Response #### Success Response - **Feature** — The simplified line. ``` -------------------------------- ### Create Circular Polygon Source: https://github.com/dartclub/turf_dart/blob/main/_autodocs/03-geometry-operations.md Creates a circular polygon from a center point and radius. The number of steps determines the smoothness of the circle. ```dart var centerPoint = Point(coordinates: Position(-75.343, 39.984)); var circleFeature = circle( centerPoint, 10, steps: 32, unit: Unit.kilometers, properties: {'name': 'buffer-zone'}, ); // Creates 32-vertex circular polygon with 10 km radius ``` -------------------------------- ### Define a Position with Longitude, Latitude, and Optional Altitude Source: https://github.com/dartclub/turf_dart/blob/main/_autodocs/09-types-and-data-structures.md Represents a single coordinate point. Use the constructor or named constructor for initialization. Access coordinates by index or named properties. ```dart class Position { final List _coordinates; Position(num lng, num lat, [num? altitude]); Position.named({ required num lng, required num lat, num? altitude, }); } ``` -------------------------------- ### Generate Triangular Grid Source: https://github.com/dartclub/turf_dart/blob/main/_autodocs/08-utility-functions.md Generates a grid of triangular polygons within a specified bounding box. Suitable for applications requiring triangular tessellations. ```dart FeatureCollection triangleGrid( BBox bbox, num cellSize, {Unit unit = Unit.kilometers} ) ``` -------------------------------- ### Create Square Polygon Source: https://github.com/dartclub/turf_dart/blob/main/_autodocs/08-utility-functions.md Generates a square polygon centered at a given point with a specified side length. Use this to create square areas for spatial analysis or visualization. ```dart Feature square( Feature center, num size, {Unit? unit} ) ``` ```dart var center = Feature( geometry: Point(coordinates: Position(10, 45)) ); var squareFeature = square(center, 10, unit: Unit.kilometers); // Creates 10km x 10km square centered at (10, 45) ``` -------------------------------- ### CoordinateSystem Enumeration Source: https://github.com/dartclub/turf_dart/blob/main/_autodocs/09-types-and-data-structures.md Defines supported coordinate systems, primarily WGS84 (geographic lon/lat) and Web Mercator (EPSG:3857). ```dart enum CoordinateSystem { wgs84, // WGS84 geographic (lon/lat) mercator, // Web Mercator (EPSG:3857) } ``` -------------------------------- ### squareGrid Source: https://github.com/dartclub/turf_dart/blob/main/_autodocs/08-utility-functions.md Generates a grid of square polygons within a bounding box. This function is useful for creating regular spatial grids for analysis or mapping. ```APIDOC ## squareGrid ### Description Generates a grid of square polygons within a bounding box. ### Method ```dart FeatureCollection squareGrid(BBox bbox, num cellSize, {Unit unit = Unit.kilometers}) ``` ### Parameters #### Path Parameters - **bbox** (BBox) - Required - Bounding box - **cellSize** (num) - Required - Side length of squares - **unit** (Unit) - Optional - Unit of cellSize (defaults to kilometers) ### Returns `FeatureCollection` — Grid of square polygons ### Example ```dart var bbox = BBox.named(lng1: 0, lat1: 0, lng2: 10, lat2: 10); var grid = squareGrid(bbox, 1, unit: Unit.kilometers); // Creates grid of 1km x 1km squares ``` ``` -------------------------------- ### Convert Coordinate Systems (WGS84 and Web Mercator) Source: https://github.com/dartclub/turf_dart/blob/main/_autodocs/10-quick-start-guide.md Converts coordinates between the WGS84 (latitude/longitude) and Web Mercator projection systems. Useful for map rendering and analysis. ```dart import 'package:turf/helpers.dart'; // WGS84 to Web Mercator var wgs84 = Position(10.0, 45.0); // [lon, lat] var mercator = toMercator(wgs84); // ~[1111949, 5621521] // Web Mercator to WGS84 var backToWgs84 = toWGS84(mercator); // ~[10, 45] ``` -------------------------------- ### Common Unit and Coordinate Conversions in Turf.js Dart Source: https://github.com/dartclub/turf_dart/blob/main/_autodocs/10-quick-start-guide.md Provides a collection of utility functions for converting between different units of measurement (degrees, radians, distance, area) and coordinate systems (WGS84, Mercator). ```dart // Degrees ↔ Radians var rad = degreesToRadians(45); // 0.7854 var deg = radiansToDegrees(pi / 4); // 45 // Bearing ↔ Azimuth var az = bearingToAzimuth(-45); // 315 // Distance conversions convertLength(100, Unit.kilometers, Unit.miles); // 62.137 convertLength(100, Unit.miles, Unit.kilometers); // 160.934 convertLength(100, Unit.meters, Unit.feet); // 328.084 // Area conversions convertArea(1000000, Unit.meters, Unit.kilometers); // 1.0 convertArea(1, Unit.miles, Unit.kilometers); // 2.59 convertArea(2000, Unit.meters, Unit.acres); // 0.494 // Coordinate systems toMercator(Position(10, 45)); // Web Mercator projection toWGS84(Position(1111949, 5621521)); // Back to lat/lon ```