Skip to content

Commit 8114a16

Browse files
fix: allowed LatLngBounds.center to work across world boundary & added simpleCenter (#1860)
1 parent 58ff560 commit 8114a16

File tree

2 files changed

+54
-1
lines changed

2 files changed

+54
-1
lines changed

lib/src/geo/latlng_bounds.dart

+7-1
Original file line numberDiff line numberDiff line change
@@ -193,9 +193,15 @@ class LatLngBounds {
193193
final lambda3 = lambda1 + atan2(by, cos(phi1) + bx);
194194

195195
// phi3 and lambda3 are actually in radians and LatLng wants degrees
196-
return LatLng(phi3 * radians2Degrees, lambda3 * radians2Degrees);
196+
return LatLng(
197+
phi3 * radians2Degrees,
198+
(lambda3 * radians2Degrees + 540) % 360 - 180,
199+
);
197200
}
198201

202+
/// Obtain simple coordinates of the bounds center
203+
LatLng get simpleCenter => LatLng((south + north) / 2, (east + west) / 2);
204+
199205
/// Checks whether [point] is inside bounds
200206
bool contains(LatLng point) =>
201207
point.longitude >= west &&

test/geo/latlng_bounds_test.dart

+47
Original file line numberDiff line numberDiff line change
@@ -47,5 +47,52 @@ void main() {
4747
expect(bounds1.hashCode, bounds2.hashCode);
4848
});
4949
});
50+
51+
group('center', () {
52+
// cf. https://github.com/fleaflet/flutter_map/issues/1689
53+
test('should calculate center point #1', () async {
54+
final bounds = LatLngBounds(
55+
const LatLng(-77.45, -171.16),
56+
const LatLng(46.64, 25.88),
57+
);
58+
final center = bounds.center;
59+
expect(center.latitude, greaterThanOrEqualTo(-90));
60+
expect(center.latitude, lessThanOrEqualTo(90));
61+
expect(center.longitude, greaterThanOrEqualTo(-180));
62+
expect(center.longitude, lessThanOrEqualTo(180));
63+
});
64+
test('should calculate center point #2', () async {
65+
final bounds = LatLngBounds(
66+
const LatLng(-0.87, -179.86),
67+
const LatLng(84.92, 23.86),
68+
);
69+
final center = bounds.center;
70+
expect(center.latitude, greaterThanOrEqualTo(-90));
71+
expect(center.latitude, lessThanOrEqualTo(90));
72+
expect(center.longitude, greaterThanOrEqualTo(-180));
73+
expect(center.longitude, lessThanOrEqualTo(180));
74+
});
75+
});
76+
77+
group('simpleCenter', () {
78+
test('should calculate center point #1', () async {
79+
final bounds = LatLngBounds(
80+
const LatLng(-77.45, -171.16),
81+
const LatLng(46.64, 25.88),
82+
);
83+
final center = bounds.simpleCenter;
84+
expect(center.latitude, (-77.45 + 46.64) / 2);
85+
expect(center.longitude, (-171.16 + 25.88) / 2);
86+
});
87+
test('should calculate center point #2', () async {
88+
final bounds = LatLngBounds(
89+
const LatLng(-0.87, -179.86),
90+
const LatLng(84.92, 23.86),
91+
);
92+
final center = bounds.simpleCenter;
93+
expect(center.latitude, (-0.87 + 84.92) / 2);
94+
expect(center.longitude, (-179.86 + 23.86) / 2);
95+
});
96+
});
5097
});
5198
}

0 commit comments

Comments
 (0)