Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions lib/random_position.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
library turf_random_position;

export 'src/random_position.dart';
export 'package:geotypes/geotypes.dart';
35 changes: 35 additions & 0 deletions lib/src/random_position.dart
Original file line number Diff line number Diff line change
@@ -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]!));
}
25 changes: 25 additions & 0 deletions test/components/random_position_test.dart
Original file line number Diff line number Diff line change
@@ -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]!));
});
});
}