Skip to content

Instantly share code, notes, and snippets.

@stnguyen90
Last active May 22, 2024 20:26
Show Gist options
  • Save stnguyen90/145bc06d4ae72c69295a46a05e2092d5 to your computer and use it in GitHub Desktop.
Save stnguyen90/145bc06d4ae72c69295a46a05e2092d5 to your computer and use it in GitHub Desktop.
Get Bounds From Center and Distance
import 'dart:math';
const earthRadius = 3958.8; // in miles
const earthCircumference = 2 * pi * earthRadius;
class Point {
final double lng;
final double lat;
Point({
required this.lng,
required this.lat,
});
@override
String toString() {
return '$lat,$lng';
}
}
class Bounds {
final Point north;
final Point south;
final Point east;
final Point west;
Bounds({
required this.north,
required this.south,
required this.east,
required this.west,
});
factory Bounds.fromCenter(Point center, double radius) {
final deltaLatitude = 360 * radius / earthCircumference;
final deltaLongitude = deltaLatitude / cos(center.lat * pi / 180);
return Bounds(
north: Point(lat: center.lat + deltaLatitude, lng: center.lng),
south: Point(lat: center.lat - deltaLatitude, lng: center.lng),
west: Point(lat: center.lat, lng: center.lng - deltaLongitude),
east: Point(lat: center.lat, lng: center.lng + deltaLongitude),
);
}
@override
String toString() {
return 'Bounds(north: $north, south: $south, east: $east, west: $west)';
}
}
void main() {
final center = Point(lat: 51.503231, lng: -0.119189);
final distance = 10.0;
final bounds = Bounds.fromCenter(center, distance);
print(center);
print(bounds.north);
print(bounds.south);
print(bounds.east);
print(bounds.west);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment