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
2 changes: 1 addition & 1 deletion docs/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |

Expand Down
8 changes: 8 additions & 0 deletions docs/upgrading.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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(
Expand Down
Original file line number Diff line number Diff line change
@@ -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<Double>): 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<LatLng>): 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),
)
}
Original file line number Diff line number Diff line change
@@ -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)
}
}
28 changes: 16 additions & 12 deletions package/ios/AppleMapProviderAdapter.swift
Original file line number Diff line number Diff line change
Expand Up @@ -332,21 +332,25 @@ final class AppleMapProviderAdapter: MapProviderAdapter {
animated: Bool?
) throws -> Promise<Void> {
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)
Expand Down
6 changes: 6 additions & 0 deletions package/ios/Geometry/ClusterZoomSpan.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}
49 changes: 49 additions & 0 deletions package/ios/Geometry/LongitudeArc.swift
Original file line number Diff line number Diff line change
@@ -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
}
}
9 changes: 7 additions & 2 deletions package/ios/GoogleMapProviderAdapter.swift
Original file line number Diff line number Diff line change
Expand Up @@ -57,13 +57,13 @@
if let googleMapId = _googleMapId?.trimmingCharacters(in: .whitespacesAndNewlines),
!googleMapId.isEmpty
{
mapView = GMSMapView(

Check warning on line 60 in package/ios/GoogleMapProviderAdapter.swift

View workflow job for this annotation

GitHub Actions / native / iOS (google)

'init(frame:mapID:camera:)' is deprecated: Use -init or -initWithOptions: instead.

Check warning on line 60 in package/ios/GoogleMapProviderAdapter.swift

View workflow job for this annotation

GitHub Actions / native / iOS (google)

'init(frame:mapID:camera:)' is deprecated: Use -init or -initWithOptions: instead.
frame: .zero,
mapID: GMSMapID(identifier: googleMapId),
camera: initialCamera
)
} else {
mapView = GMSMapView(frame: .zero, camera: initialCamera)

Check warning on line 66 in package/ios/GoogleMapProviderAdapter.swift

View workflow job for this annotation

GitHub Actions / native / iOS (google)

'init(frame:camera:)' is deprecated: Use -init or -initWithOptions: instead.

Check warning on line 66 in package/ios/GoogleMapProviderAdapter.swift

View workflow job for this annotation

GitHub Actions / native / iOS (google)

'init(frame:camera:)' is deprecated: Use -init or -initWithOptions: instead.
}

mapView.delegate = self
Expand Down Expand Up @@ -321,12 +321,17 @@
animated: Bool?
) throws -> Promise<Void> {
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
Expand Down
19 changes: 5 additions & 14 deletions package/ios/MarkerClusterEngine.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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
)
))
}
Expand Down Expand Up @@ -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,
Expand All @@ -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),
Expand Down
16 changes: 5 additions & 11 deletions package/ios/Region+GMSCoordinateBounds.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
Expand All @@ -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 {
Expand Down
Loading
Loading