diff --git a/lib/random_position.dart b/lib/random_position.dart new file mode 100644 index 00000000..707f4c69 --- /dev/null +++ b/lib/random_position.dart @@ -0,0 +1,4 @@ +library turf_random_position; + +export 'src/random_position.dart'; +export 'package:geotypes/geotypes.dart'; diff --git a/lib/src/random_position.dart b/lib/src/random_position.dart new file mode 100644 index 00000000..0e1b1497 --- /dev/null +++ b/lib/src/random_position.dart @@ -0,0 +1,35 @@ +import 'dart:math'; + +import 'package:turf/turf.dart'; + +// Returns a random Position within a Bbox +// Dart Random function module is obtained from dart:math + +Position randomPosition(BBox? bbox) { + checkBBox(bbox); + return randomPositionUnchecked(bbox); +} + +// Returns a Random Position without checking if it is valid +Position randomPositionUnchecked(BBox? bbox) { + return coordInBBox(bbox); +} + +// Performs checks on bbox ensuring a bbox is provided, and contains 4 values. +void checkBBox(BBox? bbox) { + if (bbox == null) { + throw ArgumentError("Bbox cannot be null."); + } + if (bbox.length != 4) { + throw ArgumentError("Bbox must contain exactly 4 values."); + } +} + +// Returns a random Position within bbox +Position coordInBBox(BBox? bbox) { + if (bbox == null) { + throw ArgumentError("Bbox cannot be null."); + } + return Position(bbox[0]! + Random().nextDouble() * (bbox[2]! - bbox[0]!), + bbox[1]! + Random().nextDouble() * (bbox[3]! - bbox[1]!)); +} diff --git a/test/components/random_position_test.dart b/test/components/random_position_test.dart new file mode 100644 index 00000000..c46e8d82 --- /dev/null +++ b/test/components/random_position_test.dart @@ -0,0 +1,25 @@ +import 'package:turf/random_position.dart'; +import 'package:test/test.dart'; + +void main() { + group('Random Position tests', () { + test('Generating a random position within a bounding box', () { + BBox bbox = BBox(100.0, -24.0, 110.0, -23.0); + Position randomPos = randomPosition(bbox); + + expect(randomPos.lng, greaterThanOrEqualTo(bbox[0]!)); + expect(randomPos.lng, lessThanOrEqualTo(bbox[2]!)); + expect(randomPos.lat, greaterThanOrEqualTo(bbox[1]!)); + expect(randomPos.lat, lessThanOrEqualTo(bbox[3]!)); + }); + + test('Check coordInBox returns point within bbox', () { + BBox bbox = BBox(100.0, -24.0, 110.0, -23.0); + Position coord = coordInBBox(bbox); + expect(coord.lng, greaterThanOrEqualTo(bbox[0]!)); + expect(coord.lng, lessThanOrEqualTo(bbox[2]!)); + expect(coord.lat, greaterThanOrEqualTo(bbox[1]!)); + expect(coord.lat, lessThanOrEqualTo(bbox[3]!)); + }); + }); +}