diff --git a/docs/api.md b/docs/api.md index b5045cc5..17047bdb 100644 --- a/docs/api.md +++ b/docs/api.md @@ -141,7 +141,7 @@ provider supports. | `animateCamera(camera, duration?)` | — | Animates the camera over `duration` ms (default `250`); `0`, a negative or a non-finite duration moves without animating. Rejects for an invalid camera | | `animateToRegion(region, duration?)` | — | Animates to frame `region` as the `region` prop does: all of it in view, north up and flat. Same `duration` rules. Rejects for an invalid region | | `getVisibleRegion()` | `VisibleRegion` | The four corners of the visible area | -| `fitToCoordinates(coordinates, padding?, animated?)` | — | Fits the camera to the coordinates; `padding` is added to `mapPadding`. Animates unless `animated` is `false`. An empty list is a no-op; invalid coordinates are dropped with a development warning | +| `fitToCoordinates(coordinates, padding?, animated?)` | — | Fits the camera to the coordinates, the short way round the world: across the antimeridian when that is shorter; `padding` is added to `mapPadding`. Animates unless `animated` is `false`. An empty list is a no-op; invalid coordinates are dropped with a development warning | | `pointForCoordinate(coordinate)` | `Point` | Where the map draws the coordinate, in dp from the map view's top-left corner; off screen gives a point outside the view. Rejects for a coordinate outside the world | | `coordinateForPoint(point)` | `Coordinate` | The coordinate under a point. Rejects for a non-finite `x` or `y`, and when the map has no ground under the point | diff --git a/docs/upgrading.md b/docs/upgrading.md index 14ce66d1..8e51f100 100644 --- a/docs/upgrading.md +++ b/docs/upgrading.md @@ -32,6 +32,14 @@ item against your app. Items without a migration step need no change. moves the map either. **Migration:** to move back to the same region, call `animateToRegion` or `fitToCoordinates` on the ref. ([#67](https://github.com/gmi-software/react-native-better-maps/pull/67)) +- **`fitToCoordinates` takes the short way round the world on Apple Maps.** + Points on both sides of the antimeridian, such as 179.9° and -179.9°, used + to frame the 359.8° between them; they now frame the 0.2° strip across it, + as Google Maps already did. Points that are closer the other way round, such + as New York and Tokyo, are framed across the Pacific. Google Maps used to + grow the bounds one point at a time, so a few orderings of three or more + widely spread points came out wider than needed; they no longer do. + ([#237](https://github.com/gmi-software/react-native-better-maps/pull/237)) ## Region events diff --git a/package/android/src/main/java/com/margelo/nitro/nitromaps/GoogleMapProviderAdapter.kt b/package/android/src/main/java/com/margelo/nitro/nitromaps/GoogleMapProviderAdapter.kt index 1f9b823c..bfbdfc7e 100644 --- a/package/android/src/main/java/com/margelo/nitro/nitromaps/GoogleMapProviderAdapter.kt +++ b/package/android/src/main/java/com/margelo/nitro/nitromaps/GoogleMapProviderAdapter.kt @@ -14,7 +14,6 @@ import com.google.android.gms.maps.GoogleMapOptions import com.google.android.gms.maps.MapView import com.google.android.gms.maps.model.CameraPosition import com.google.android.gms.maps.model.LatLng -import com.google.android.gms.maps.model.LatLngBounds import com.google.android.gms.maps.model.MapStyleOptions import com.margelo.nitro.core.Promise @@ -418,19 +417,13 @@ class GoogleMapProviderAdapter( if (skipped > 0) { Log.w(NITRO_MAPS_LOG_TAG, "fitToCoordinates skipped $skipped coordinate(s) outside the world.") } - if (validCoordinates.isEmpty()) { - return Promise.resolved(Unit) - } + val bounds = + smallestBounds(validCoordinates.map { LatLng(it.latitude, it.longitude) }) + ?: return Promise.resolved(Unit) // `newLatLngBounds` throws on a map that has no size yet, so the camera update // waits for the first layout pass -- and so does the promise. return promiseMoveWhenLaidOut { map, onEnd -> - val builder = LatLngBounds.Builder() - for (coordinate in validCoordinates) { - builder.include(LatLng(coordinate.latitude, coordinate.longitude)) - } - val bounds = builder.build() - // Converting the insets needs the size the map was laid out with. val target = bounds.expandedForEdgePadding( diff --git a/package/android/src/main/java/com/margelo/nitro/nitromaps/LongitudeArc.kt b/package/android/src/main/java/com/margelo/nitro/nitromaps/LongitudeArc.kt new file mode 100644 index 00000000..2af1d738 --- /dev/null +++ b/package/android/src/main/java/com/margelo/nitro/nitromaps/LongitudeArc.kt @@ -0,0 +1,54 @@ +package com.margelo.nitro.nitromaps + +import com.google.android.gms.maps.model.LatLng +import com.google.android.gms.maps.model.LatLngBounds + +/** A stretch of longitude, read eastward from [west] for [span] degrees. */ +internal data class LongitudeArc( + val west: Double, + val span: Double, +) + +/** The same meridian in [-180, 180). */ +private fun wrapLongitude(longitude: Double): Double { + if (longitude >= -180.0 && longitude < 180.0) { + return longitude + } + val shifted = (longitude + 180.0) % 360.0 + return (if (shifted < 0.0) shifted + 360.0 else shifted) - 180.0 +} + +/** + * The shortest stretch of longitude that holds all of [longitudes]: the whole circle less the + * widest gap between neighbours. It crosses the antimeridian when that is the short way. When + * the gap across the antimeridian ties for the widest, the plain bounds win. The JS cluster + * press and iOS `fitToCoordinates` use the same rule (`LongitudeArc.swift`). + */ +internal fun smallestLongitudeArc(longitudes: List): LongitudeArc? { + val sorted = longitudes.map(::wrapLongitude).sorted() + val first = sorted.firstOrNull() ?: return null + val last = sorted.last() + var widestGap = first + 360.0 - last + var arc = LongitudeArc(west = first, span = last - first) + for (index in 1 until sorted.size) { + val gap = sorted[index] - sorted[index - 1] + if (gap > widestGap) { + widestGap = gap + arc = LongitudeArc(west = sorted[index], span = 360.0 - gap) + } + } + return arc +} + +/** + * The smallest bounds that hold all of [points]. `LatLngBounds.Builder` picks a side per point + * as they come, so its bounds depend on the order and can come out wider. + */ +internal fun smallestBounds(points: List): LatLngBounds? { + val arc = smallestLongitudeArc(points.map { it.longitude }) ?: return null + // `LatLng` wraps an east edge past 180 back into range. + return LatLngBounds( + LatLng(points.minOf { it.latitude }, arc.west), + LatLng(points.maxOf { it.latitude }, arc.west + arc.span), + ) +} diff --git a/package/android/src/test/java/com/margelo/nitro/nitromaps/LongitudeArcTest.kt b/package/android/src/test/java/com/margelo/nitro/nitromaps/LongitudeArcTest.kt new file mode 100644 index 00000000..5a66bcb1 --- /dev/null +++ b/package/android/src/test/java/com/margelo/nitro/nitromaps/LongitudeArcTest.kt @@ -0,0 +1,65 @@ +package com.margelo.nitro.nitromaps + +import com.google.android.gms.maps.model.LatLng +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Test + +private const val TOLERANCE = 1e-9 + +class LongitudeArcTest { + @Test + fun crossesTheAntimeridianWhenThatIsTheShortWay() { + val arc = smallestLongitudeArc(listOf(179.9, -179.9))!! + + assertEquals(179.9, arc.west, TOLERANCE) + assertEquals(0.2, arc.span, TOLERANCE) + } + + @Test + fun keepsPlainBoundsWhenTheyAreTheShortWay() { + val arc = smallestLongitudeArc(listOf(21.2, 21.0, 20.9))!! + + assertEquals(20.9, arc.west, 0.0) + assertEquals(0.3, arc.span, TOLERANCE) + } + + @Test + fun leavesOutTheWidestGapWhateverTheOrder() { + // `LatLngBounds.Builder` takes these in order and spans 260 degrees from 0 eastward. + assertEquals(LongitudeArc(west = 170.0, span = 190.0), smallestLongitudeArc(listOf(0.0, 170.0, -100.0))) + } + + @Test + fun keepsPlainBoundsWhenTheGapAcrossTheAntimeridianTies() { + assertEquals(LongitudeArc(west = -90.0, span = 180.0), smallestLongitudeArc(listOf(-90.0, 90.0))) + } + + @Test + fun reads180AndMinus180AsOneMeridian() { + assertEquals(LongitudeArc(west = -180.0, span = 0.0), smallestLongitudeArc(listOf(180.0, -180.0))) + } + + @Test + fun noPointsGiveNoArc() { + assertNull(smallestLongitudeArc(emptyList())) + } + + @Test + fun boundsAcrossTheAntimeridianKeepTheirWestEdgeEastOfTheirEastEdge() { + val bounds = smallestBounds(listOf(LatLng(-17.0, 179.9), LatLng(-17.1, -179.9)))!! + + assertEquals(-17.1, bounds.southwest.latitude, TOLERANCE) + assertEquals(-17.0, bounds.northeast.latitude, TOLERANCE) + assertEquals(179.9, bounds.southwest.longitude, TOLERANCE) + assertEquals(-179.9, bounds.northeast.longitude, TOLERANCE) + } + + @Test + fun boundsOfOnePointAreThatPoint() { + val bounds = smallestBounds(listOf(LatLng(52.0, 21.0)))!! + + assertEquals(LatLng(52.0, 21.0), bounds.southwest) + assertEquals(LatLng(52.0, 21.0), bounds.northeast) + } +} diff --git a/package/ios/AppleMapProviderAdapter.swift b/package/ios/AppleMapProviderAdapter.swift index 59a83253..a676d4ff 100644 --- a/package/ios/AppleMapProviderAdapter.swift +++ b/package/ios/AppleMapProviderAdapter.swift @@ -332,21 +332,25 @@ final class AppleMapProviderAdapter: MapProviderAdapter { animated: Bool? ) throws -> Promise { let validCoordinates = coordinates.filter { $0.isValid } - guard !validCoordinates.isEmpty else { + guard + let arc = LongitudeArc.smallest(containing: validCoordinates.map(\.longitude)), + let south = validCoordinates.map(\.latitude).min(), + let north = validCoordinates.map(\.latitude).max() + else { return Promise.resolved() } - var mapRect = MKMapRect.null - for coordinate in validCoordinates { - let mapPoint = MKMapPoint( - CLLocationCoordinate2D( - latitude: coordinate.latitude, - longitude: coordinate.longitude - ) - ) - let pointRect = MKMapRect(x: mapPoint.x, y: mapPoint.y, width: 0, height: 0) - mapRect = mapRect.union(pointRect) - } + // Built from the arc rather than as a union of map points, which cannot wrap: + // across the antimeridian the rect runs past the world's east edge, and MapKit + // centres it on the far side. + let southWest = MKMapPoint(CLLocationCoordinate2D(latitude: south, longitude: arc.west)) + let northWest = MKMapPoint(CLLocationCoordinate2D(latitude: north, longitude: arc.west)) + let mapRect = MKMapRect( + x: southWest.x, + y: northWest.y, + width: arc.span / 360 * MKMapSize.world.width, + height: southWest.y - northWest.y + ) let edgePadding = padding?.toUIEdgeInsets() ?? .zero view.setVisibleMapRect(mapRect, edgePadding: edgePadding, animated: animated ?? true) diff --git a/package/ios/Geometry/ClusterZoomSpan.swift b/package/ios/Geometry/ClusterZoomSpan.swift index 10989a03..27d7e635 100644 --- a/package/ios/Geometry/ClusterZoomSpan.swift +++ b/package/ios/Geometry/ClusterZoomSpan.swift @@ -14,4 +14,10 @@ enum ClusterZoomSpan { static func delta(min: Double, max: Double) -> Double { Swift.max((max - min) * paddingFactor, minimumDelta) } + + /// The centre between longitudes measured without wrapping, so `max` may lie + /// past 180 for a cluster across the antimeridian. + static func centerLongitude(min: Double, max: Double) -> Double { + LongitudeArc.wrapped((min + max) / 2) + } } diff --git a/package/ios/Geometry/LongitudeArc.swift b/package/ios/Geometry/LongitudeArc.swift new file mode 100644 index 00000000..6a85b37b --- /dev/null +++ b/package/ios/Geometry/LongitudeArc.swift @@ -0,0 +1,49 @@ +import Foundation + +/// A stretch of longitude, read eastward from `west` for `span` degrees. +struct LongitudeArc: Equatable { + let west: Double + let span: Double + + /// The same meridian in [-180, 180). + static func wrapped(_ longitude: Double) -> Double { + if longitude >= -180 && longitude < 180 { + return longitude + } + let shifted = (longitude + 180).truncatingRemainder(dividingBy: 360) + return (shifted < 0 ? shifted + 360 : shifted) - 180 + } + + /// The same meridian in [-180, 180], leaving the edges as they are. + static func normalized(_ longitude: Double) -> Double { + Swift.abs(longitude) > 180 ? wrapped(longitude) : longitude + } + + /// The shortest stretch of longitude that holds all of `longitudes`: the whole + /// circle less the widest gap between neighbours. It crosses the antimeridian + /// when that is the short way. When the gap across the antimeridian ties for the + /// widest, the plain bounds win. The JS cluster press and Android's + /// `fitToCoordinates` use the same rule. + static func smallest(containing longitudes: [Double]) -> LongitudeArc? { + let sorted = longitudes.map(wrapped).sorted() + guard let first = sorted.first, let last = sorted.last else { + return nil + } + var widestGap = first + 360 - last + var arc = LongitudeArc(west: first, span: last - first) + for index in sorted.indices.dropFirst() { + let gap = sorted[index] - sorted[index - 1] + if gap > widestGap { + widestGap = gap + arc = LongitudeArc(west: sorted[index], span: 360 - gap) + } + } + return arc + } + + /// How far east of `west` the meridian of `longitude` lies, in [0, 360). + func offset(of longitude: Double) -> Double { + let offset = Self.wrapped(longitude) - west + return offset < 0 ? offset + 360 : offset + } +} diff --git a/package/ios/GoogleMapProviderAdapter.swift b/package/ios/GoogleMapProviderAdapter.swift index 88ec1a54..8df7b324 100644 --- a/package/ios/GoogleMapProviderAdapter.swift +++ b/package/ios/GoogleMapProviderAdapter.swift @@ -321,12 +321,17 @@ final class GoogleMapProviderAdapter: NSObject, MapProviderAdapter { animated: Bool? ) throws -> Promise { let validCoordinates = coordinates.filter { $0.isValid } - guard !validCoordinates.isEmpty else { + guard let arc = LongitudeArc.smallest(containing: validCoordinates.map(\.longitude)) else { return Promise.resolved() } + // `includingCoordinate` grows the bounds the shorter way round, one point at a + // time, so taken from west to east the points end up spanning exactly `arc`. + // In any other order the bounds can come out wider. var bounds = GMSCoordinateBounds() - for coordinate in validCoordinates { + for coordinate in validCoordinates.sorted(by: { + arc.offset(of: $0.longitude) < arc.offset(of: $1.longitude) + }) { bounds = bounds.includingCoordinate(coordinate.toCLLocationCoordinate2D()) } let edgePadding = padding?.toUIEdgeInsets() ?? .zero diff --git a/package/ios/MarkerClusterEngine.swift b/package/ios/MarkerClusterEngine.swift index cb762fb0..3f1064ce 100644 --- a/package/ios/MarkerClusterEngine.swift +++ b/package/ios/MarkerClusterEngine.swift @@ -98,17 +98,6 @@ enum MarkerClusterEngine { return normalized } - private static func wrapTo180(_ lon: Double) -> Double { - var wrapped = lon - while wrapped > 180 { - wrapped -= 360 - } - while wrapped < -180 { - wrapped += 360 - } - return wrapped - } - /// Approximate badge radius (points) per count — mirrors the annotation views /// so the overlap test matches what is actually drawn. private static func badgeRadius(for count: Int) -> Double { @@ -280,8 +269,8 @@ enum MarkerClusterEngine { region: expandedRegion( minLat: bucket.minLat, maxLat: bucket.maxLat, - minLon: wrapTo180(bucket.minLon), - maxLon: wrapTo180(bucket.maxLon) + minLon: bucket.minLon, + maxLon: bucket.maxLon ) )) } @@ -370,6 +359,8 @@ enum MarkerClusterEngine { /// Region that snugly contains a cluster's members, padded so a tap-to-zoom /// reveals them with breathing room (and never zooms in absurdly far). + /// Longitudes come unwrapped, so a cluster across the antimeridian keeps its + /// width. private static func expandedRegion( minLat: Double, maxLat: Double, @@ -378,7 +369,7 @@ enum MarkerClusterEngine { ) -> MKCoordinateRegion { let center = CLLocationCoordinate2D( latitude: (minLat + maxLat) / 2, - longitude: (minLon + maxLon) / 2 + longitude: ClusterZoomSpan.centerLongitude(min: minLon, max: maxLon) ) let span = MKCoordinateSpan( latitudeDelta: ClusterZoomSpan.delta(min: minLat, max: maxLat), diff --git a/package/ios/Region+GMSCoordinateBounds.swift b/package/ios/Region+GMSCoordinateBounds.swift index 4c4e41fb..adcbfba7 100644 --- a/package/ios/Region+GMSCoordinateBounds.swift +++ b/package/ios/Region+GMSCoordinateBounds.swift @@ -6,14 +6,15 @@ extension Region { func toGMSCoordinateBounds() -> GMSCoordinateBounds { // Latitude is clamped rather than wrapped: a span wide enough to run past a // pole has no representable edge there, and Google Maps is handed the - // closest one that does exist. + // closest one that does exist. Longitude is wrapped: an edge past ±180 + // collapses the bounds to a point. let southWest = CLLocationCoordinate2D( latitude: max(-90, latitude - latitudeDelta / 2), - longitude: longitude - longitudeDelta / 2 + longitude: LongitudeArc.normalized(longitude - longitudeDelta / 2) ) let northEast = CLLocationCoordinate2D( latitude: min(90, latitude + latitudeDelta / 2), - longitude: longitude + longitudeDelta / 2 + longitude: LongitudeArc.normalized(longitude + longitudeDelta / 2) ) return GMSCoordinateBounds(coordinate: southWest, coordinate: northEast) } @@ -27,18 +28,11 @@ extension GMSCoordinateBounds { return Region( latitude: southWest.latitude + latitudeDelta / 2, - longitude: normalizedLongitude(southWest.longitude + longitudeDelta / 2), + longitude: LongitudeArc.normalized(southWest.longitude + longitudeDelta / 2), latitudeDelta: latitudeDelta, longitudeDelta: longitudeDelta ) } - - private func normalizedLongitude(_ longitude: Double) -> Double { - var value = longitude - while value > 180 { value -= 360 } - while value < -180 { value += 360 } - return value - } } extension MKCoordinateRegion { diff --git a/package/ios/Tests/Geometry/ClusterZoomSpanTests.swift b/package/ios/Tests/Geometry/ClusterZoomSpanTests.swift index 62c36093..f2d495b8 100644 --- a/package/ios/Tests/Geometry/ClusterZoomSpanTests.swift +++ b/package/ios/Tests/Geometry/ClusterZoomSpanTests.swift @@ -21,3 +21,19 @@ struct ClusterZoomSpanTests { #expect(abs(ClusterZoomSpan.delta(min: 0, max: 0.01) - 0.016) < 1e-12) } } + +@Suite +struct ClusterZoomCenterTests { + @Test + func centresAClusterAcrossTheAntimeridianOnIt() { + // The engine measures a cluster that wraps eastward past 180 degrees. + let center = ClusterZoomSpan.centerLongitude(min: 179.9, max: 180.1) + #expect(Swift.abs(Swift.abs(center) - 180) < 1e-9) + #expect(Swift.abs(ClusterZoomSpan.delta(min: 179.9, max: 180.1) - 0.32) < 1e-9) + } + + @Test + func keepsTheCentreOfAPlainCluster() { + #expect(ClusterZoomSpan.centerLongitude(min: 21, max: 21.2) == 21.1) + } +} diff --git a/package/ios/Tests/Geometry/LongitudeArcTests.swift b/package/ios/Tests/Geometry/LongitudeArcTests.swift new file mode 100644 index 00000000..fe45e7ba --- /dev/null +++ b/package/ios/Tests/Geometry/LongitudeArcTests.swift @@ -0,0 +1,76 @@ +import Testing + +@testable import NitroMapsGeometry + +@Suite +struct LongitudeArcTests { + @Test + func wrapsALongitudePastTheAntimeridianBackIntoTheWorld() { + #expect(Swift.abs(LongitudeArc.wrapped(180.1) + 179.9) < 1e-9) + #expect(Swift.abs(LongitudeArc.wrapped(-180.1) - 179.9) < 1e-9) + #expect(LongitudeArc.wrapped(540) == -180) + #expect(LongitudeArc.wrapped(21) == 21) + } + + @Test + func crossesTheAntimeridianWhenThatIsTheShortWay() throws { + let arc = try #require(LongitudeArc.smallest(containing: [179.9, -179.9])) + #expect(Swift.abs(arc.west - 179.9) < 1e-9) + #expect(Swift.abs(arc.span - 0.2) < 1e-9) + } + + @Test + func keepsPlainBoundsWhenTheyAreTheShortWay() throws { + let arc = try #require(LongitudeArc.smallest(containing: [21.2, 21, 20.9])) + #expect(arc.west == 20.9) + #expect(Swift.abs(arc.span - 0.3) < 1e-9) + } + + @Test + func leavesOutTheWidestGapWhateverTheOrder() { + #expect(LongitudeArc.smallest(containing: [0, 170, -100]) == LongitudeArc(west: 170, span: 190)) + } + + @Test + func keepsPlainBoundsWhenTheGapAcrossTheAntimeridianTies() { + #expect(LongitudeArc.smallest(containing: [-90, 90]) == LongitudeArc(west: -90, span: 180)) + } + + @Test + func reads180AndMinus180AsOneMeridian() { + #expect(LongitudeArc.smallest(containing: [180, -180]) == LongitudeArc(west: -180, span: 0)) + } + + @Test + func measuresHowFarEastOfTheWestEdgeAPointLies() { + let arc = LongitudeArc(west: 179.9, span: 0.2) + #expect(Swift.abs(arc.offset(of: -179.9) - 0.2) < 1e-9) + #expect(arc.offset(of: 179.9) == 0) + } + + @Test + func noPointsGiveNoArc() { + #expect(LongitudeArc.smallest(containing: []) == nil) + } +} + +@Suite +struct LongitudeNormalizationTests { + @Test + func leavesTheWorldsEdgesAsTheyAre() { + #expect(LongitudeArc.normalized(180) == 180) + #expect(LongitudeArc.normalized(-180) == -180) + #expect(LongitudeArc.normalized(21) == 21) + } + + @Test + func bringsALongitudePastAnEdgeBack() { + #expect(Swift.abs(LongitudeArc.normalized(180.16) + 179.84) < 1e-9) + #expect(Swift.abs(LongitudeArc.normalized(-180.16) - 179.84) < 1e-9) + } + + @Test + func returnsForAHugeLongitude() { + #expect(LongitudeArc.normalized(-5e29).isFinite) + } +} diff --git a/package/src/components/MapView.tsx b/package/src/components/MapView.tsx index 791a4d24..6ebb9b3c 100644 --- a/package/src/components/MapView.tsx +++ b/package/src/components/MapView.tsx @@ -41,7 +41,7 @@ import { import { OverlayType, overlayCallbackKey } from '../overlays/overlayType'; import { clusterMemberCoordinates, - clusterZoomCorners, + clusterZoomCoordinates, markerViewRenderStatesEqual, } from '../overlays/markerViewRenderState'; import { normalizeClusterStyle } from '../overlays/normalizeClusterStyle'; @@ -301,10 +301,10 @@ export function MapView({ if (clusterPressBehavior === 'none') { return Promise.resolve(); } - const corners = clusterZoomCorners( + const points = clusterZoomCoordinates( clusterMemberCoordinates(cluster.markerIds, markers), ); - if (corners == null) { + if (points == null) { return Promise.resolve(); } const padding = @@ -312,7 +312,7 @@ export function MapView({ ? CLUSTER_FIT_PADDING.google : CLUSTER_FIT_PADDING.apple; return commands.run((hybrid) => - hybrid.fitToCoordinates(corners, padding, true), + hybrid.fitToCoordinates(points, padding, true), ); }, [ diff --git a/package/src/overlays/__tests__/markerViewRenderState.test.ts b/package/src/overlays/__tests__/markerViewRenderState.test.ts index aed3921a..f040cada 100644 --- a/package/src/overlays/__tests__/markerViewRenderState.test.ts +++ b/package/src/overlays/__tests__/markerViewRenderState.test.ts @@ -1,8 +1,10 @@ import { describe, expect, test } from 'bun:test'; import type { NativeMarkerViewRenderState } from '../../native/specs/MapView.nitro'; +import { smallestLongitudeArc, wrapLongitude } from '../../region/longitudeArc'; +import type { Coordinate } from '../../types/coordinate'; import { clusterMemberCoordinates, - clusterZoomCorners, + clusterZoomCoordinates, markerViewRenderStatesEqual, } from '../markerViewRenderState'; @@ -70,38 +72,96 @@ describe('clusterMemberCoordinates', () => { }); }); -describe('clusterZoomCorners', () => { +describe('clusterZoomCoordinates', () => { + const longitudes = (coordinates: Coordinate[] | null) => + (coordinates ?? []).map(({ longitude }) => longitude); + test("pads the members' spread by 1.6 on each axis around their centre", () => { - const corners = clusterZoomCorners([ + const fit = clusterZoomCoordinates([ { latitude: 52, longitude: 21 }, { latitude: 52.1, longitude: 21.2 }, ]); - expect(corners?.[0].latitude).toBeCloseTo(51.97, 10); - expect(corners?.[1].latitude).toBeCloseTo(52.13, 10); - expect(corners?.[0].longitude).toBeCloseTo(20.94, 10); - expect(corners?.[1].longitude).toBeCloseTo(21.26, 10); + expect(fit).toHaveLength(2); + expect(fit?.[0]?.latitude).toBeCloseTo(51.97, 10); + expect(fit?.[1]?.latitude).toBeCloseTo(52.13, 10); + expect(fit?.[0]?.longitude).toBeCloseTo(20.94, 10); + expect(fit?.[1]?.longitude).toBeCloseTo(21.26, 10); }); test('members stacked on one coordinate still frame about a kilometre', () => { - const corners = clusterZoomCorners([ + const fit = clusterZoomCoordinates([ { latitude: 52, longitude: 21 }, { latitude: 52, longitude: 21 }, ]); - expect(corners?.[0].latitude).toBeCloseTo(51.995, 10); - expect(corners?.[1].latitude).toBeCloseTo(52.005, 10); - expect(corners?.[0].longitude).toBeCloseTo(20.995, 10); - expect(corners?.[1].longitude).toBeCloseTo(21.005, 10); + expect(fit?.[0]?.latitude).toBeCloseTo(51.995, 10); + expect(fit?.[1]?.latitude).toBeCloseTo(52.005, 10); + expect(fit?.[0]?.longitude).toBeCloseTo(20.995, 10); + expect(fit?.[1]?.longitude).toBeCloseTo(21.005, 10); + }); + + test('frames the 0.3 degrees around members on both sides of the antimeridian', () => { + const fit = clusterZoomCoordinates([ + { latitude: -17, longitude: 179.9 }, + { latitude: -17.1, longitude: -179.9 }, + ]); + const arc = smallestLongitudeArc(longitudes(fit)); + expect(arc?.west).toBeCloseTo(179.84, 10); + expect(arc?.span).toBeCloseTo(0.32, 10); }); test('stays inside the world, which fitToCoordinates requires', () => { - const corners = clusterZoomCorners([ + const fit = clusterZoomCoordinates([ { latitude: 89.99, longitude: 179.99 }, { latitude: 89.999, longitude: 179.999 }, ]); - expect(corners?.[1]).toEqual({ latitude: 90, longitude: 180 }); + for (const { latitude, longitude } of fit ?? []) { + expect(Math.abs(latitude)).toBeLessThanOrEqual(90); + expect(Math.abs(longitude)).toBeLessThanOrEqual(180); + } + expect(fit?.at(-1)?.latitude).toBe(90); + }); + + // The native fit reads its points by the smallest arc through them, so the + // points have to sit close enough together to leave the padded arc the + // smallest one. + test.each([ + ['0.2 degrees', [0, 0.2], 0.32], + ['120 degrees', [-60, 60], 192], + ['120 degrees across the antimeridian', [120, -120], 192], + ['200 degrees', [-100, 0, 100], 320], + [ + '340 degrees', + Array.from({ length: 18 }, (_, index) => -170 + 20 * index), + 340, + ], + ])('fits members spread over %s as one arc', (_, members, span) => { + const fit = clusterZoomCoordinates( + members.map((longitude) => ({ latitude: 0, longitude })), + ); + const membersArc = smallestLongitudeArc(members); + const arc = smallestLongitudeArc(longitudes(fit)); + expect(arc?.span).toBeCloseTo(span, 10); + const centre = (arc: { west: number; span: number }) => + wrapLongitude(arc.west + arc.span / 2); + expect(centre(arc!)).toBeCloseTo(centre(membersArc!), 10); + }); + + test('keeps a padded arc that rounds to just under 180 degrees on its side', () => { + const members = [123.75, -123.75000000000003]; + const arc = smallestLongitudeArc( + longitudes( + clusterZoomCoordinates( + members.map((longitude) => ({ latitude: 0, longitude })), + ), + ), + ); + for (const longitude of members) { + const offset = (((longitude - arc!.west) % 360) + 360) % 360; + expect(offset).toBeLessThanOrEqual(arc!.span); + } }); test('a cluster whose members are gone fits nothing', () => { - expect(clusterZoomCorners([])).toBeNull(); + expect(clusterZoomCoordinates([])).toBeNull(); }); }); diff --git a/package/src/overlays/markerViewRenderState.ts b/package/src/overlays/markerViewRenderState.ts index 8f413b91..5141223e 100644 --- a/package/src/overlays/markerViewRenderState.ts +++ b/package/src/overlays/markerViewRenderState.ts @@ -2,6 +2,7 @@ import type { NativeMarkerViewCluster, NativeMarkerViewRenderState, } from '../native/specs/MapView.nitro'; +import { smallestLongitudeArc, wrapLongitude } from '../region/longitudeArc'; import type { Coordinate } from '../types/coordinate'; function stringListsEqual(left: string[], right: string[]): boolean { @@ -88,44 +89,73 @@ function clusterZoomDelta(spread: number): number { ); } -function clamp(value: number, limit: number): number { - return Math.min(Math.max(value, -limit), limit); +/** + * Past this many degrees of longitude a fit shows the whole world on any + * screen, so padding stops there. It also keeps the points that describe the + * arc down to a handful. + */ +const CLUSTER_ZOOM_MAXIMUM_PADDED_LONGITUDE_DELTA = 320; + +const STEP_MARGIN = 1e-9; + +function clampLatitude(latitude: number): number { + return Math.min(Math.max(latitude, -90), 90); } /** - * The two corners of the area a cluster press fits: the members' bounds around - * the same centre, each axis scaled by 1.6 and at least 0.01 degrees wide. A - * press on a default cluster badge frames the cluster the same way natively + * The points a cluster press fits: the members' bounds around the same + * centre, each axis scaled by 1.6 and at least 0.01 degrees wide. A press on a + * default cluster badge frames the cluster the same way natively * (`ClusterZoomSpan` on iOS, `LatLngBounds+ClusterZoom.kt` on Android). + * + * Longitudes are read by the smallest arc through them, here and in the + * native `fitToCoordinates`, so a cluster on both sides of the antimeridian + * frames the strip around it. Two corners can only describe an arc under 180 + * degrees that way, so a wider one gets points along it, each step shorter + * than the gap the arc leaves. */ -export function clusterZoomCorners( +export function clusterZoomCoordinates( coordinates: readonly Coordinate[], -): [Coordinate, Coordinate] | null { - if (coordinates.length === 0) { +): Coordinate[] | null { + const members = smallestLongitudeArc( + coordinates.map(({ longitude }) => longitude), + ); + if (members == null) { return null; } let minLatitude = Infinity; let maxLatitude = -Infinity; - let minLongitude = Infinity; - let maxLongitude = -Infinity; - for (const { latitude, longitude } of coordinates) { + for (const { latitude } of coordinates) { minLatitude = Math.min(minLatitude, latitude); maxLatitude = Math.max(maxLatitude, latitude); - minLongitude = Math.min(minLongitude, longitude); - maxLongitude = Math.max(maxLongitude, longitude); } const centerLatitude = (minLatitude + maxLatitude) / 2; - const centerLongitude = (minLongitude + maxLongitude) / 2; const halfLatitude = clusterZoomDelta(maxLatitude - minLatitude) / 2; - const halfLongitude = clusterZoomDelta(maxLongitude - minLongitude) / 2; - return [ - { - latitude: clamp(centerLatitude - halfLatitude, 90), - longitude: clamp(centerLongitude - halfLongitude, 180), - }, - { - latitude: clamp(centerLatitude + halfLatitude, 90), - longitude: clamp(centerLongitude + halfLongitude, 180), - }, - ]; + const longitudeDelta = Math.max( + members.span, + Math.min( + clusterZoomDelta(members.span), + CLUSTER_ZOOM_MAXIMUM_PADDED_LONGITUDE_DELTA, + ), + ); + const west = members.west + members.span / 2 - longitudeDelta / 2; + // The margin keeps a step clearly shorter than the gap: at a step equal to + // it within rounding, the two read as a tie and the fit takes the other side. + const steps = + Math.floor(longitudeDelta / (360 - longitudeDelta) + STEP_MARGIN) + 1; + + const points: Coordinate[] = []; + for (let step = 0; step <= steps; step += 1) { + const latitude = + step === 0 + ? centerLatitude - halfLatitude + : step === steps + ? centerLatitude + halfLatitude + : centerLatitude; + points.push({ + latitude: clampLatitude(latitude), + longitude: wrapLongitude(west + (longitudeDelta * step) / steps), + }); + } + return points; } diff --git a/package/src/region/__tests__/longitudeArc.test.ts b/package/src/region/__tests__/longitudeArc.test.ts new file mode 100644 index 00000000..be252832 --- /dev/null +++ b/package/src/region/__tests__/longitudeArc.test.ts @@ -0,0 +1,47 @@ +import { describe, expect, test } from 'bun:test'; +import { smallestLongitudeArc, wrapLongitude } from '../longitudeArc'; + +describe('wrapLongitude', () => { + test('brings a longitude past the antimeridian back into the world', () => { + expect(wrapLongitude(180.1)).toBeCloseTo(-179.9, 10); + expect(wrapLongitude(-180.1)).toBeCloseTo(179.9, 10); + expect(wrapLongitude(540)).toBe(-180); + expect(wrapLongitude(21)).toBe(21); + }); +}); + +describe('smallestLongitudeArc', () => { + test('crosses the antimeridian when that is the short way', () => { + const arc = smallestLongitudeArc([179.9, -179.9]); + expect(arc?.west).toBeCloseTo(179.9, 10); + expect(arc?.span).toBeCloseTo(0.2, 10); + }); + + test('keeps plain bounds when they are the short way', () => { + const arc = smallestLongitudeArc([21.2, 21, 20.9]); + expect(arc?.west).toBe(20.9); + expect(arc?.span).toBeCloseTo(0.3, 10); + }); + + test('leaves out the widest gap, whatever order the points come in', () => { + // A greedy union in this order would cover 260 degrees from 0 eastward. + const arc = smallestLongitudeArc([0, 170, -100]); + expect(arc).toEqual({ west: 170, span: 190 }); + }); + + test('keeps plain bounds when the gap across the antimeridian ties', () => { + expect(smallestLongitudeArc([-90, 90])).toEqual({ west: -90, span: 180 }); + }); + + test('reads 180 and -180 as one meridian', () => { + expect(smallestLongitudeArc([180, -180])).toEqual({ west: -180, span: 0 }); + }); + + test('a single point spans nothing', () => { + expect(smallestLongitudeArc([21])).toEqual({ west: 21, span: 0 }); + }); + + test('no points give no arc', () => { + expect(smallestLongitudeArc([])).toBeNull(); + }); +}); diff --git a/package/src/region/longitudeArc.ts b/package/src/region/longitudeArc.ts new file mode 100644 index 00000000..e18f637b --- /dev/null +++ b/package/src/region/longitudeArc.ts @@ -0,0 +1,43 @@ +/** A stretch of longitude, read eastward from `west` for `span` degrees. */ +export interface LongitudeArc { + west: number; + span: number; +} + +/** The same meridian in [-180, 180). */ +export function wrapLongitude(longitude: number): number { + if (longitude >= -180 && longitude < 180) { + return longitude; + } + return ((((longitude + 180) % 360) + 360) % 360) - 180; +} + +/** + * The shortest stretch of longitude that holds all of {@linkcode longitudes}: + * the whole circle less the widest gap between neighbours. It crosses the + * antimeridian when that is the short way. When the gap across the + * antimeridian ties for the widest, the plain bounds win. + * + * The native fits use the same rule (`LongitudeArc.swift`, + * `LongitudeArc.kt`). + */ +export function smallestLongitudeArc( + longitudes: readonly number[], +): LongitudeArc | null { + if (longitudes.length === 0) { + return null; + } + const sorted = longitudes.map(wrapLongitude).sort((a, b) => a - b); + const first = sorted[0]!; + const last = sorted[sorted.length - 1]!; + let widestGap = first + 360 - last; + let arc: LongitudeArc = { west: first, span: last - first }; + for (let index = 1; index < sorted.length; index += 1) { + const gap = sorted[index]! - sorted[index - 1]!; + if (gap > widestGap) { + widestGap = gap; + arc = { west: sorted[index]!, span: 360 - gap }; + } + } + return arc; +} diff --git a/package/src/types/ref.ts b/package/src/types/ref.ts index ddc73334..e2a97905 100644 --- a/package/src/types/ref.ts +++ b/package/src/types/ref.ts @@ -84,6 +84,9 @@ export interface MapViewRef { * Resolves once the camera has arrived, which for an un-animated fit is * right away. An empty {@linkcode coordinates} list is a no-op. * + * Longitudes are framed the short way round the world: points at 179.9 and + * -179.9 frame the 0.2 degrees across the antimeridian. + * * {@linkcode padding} is added on top of {@linkcode MapViewProps.mapPadding}. * * @param animated Defaults to `true`; `false` moves the camera without