diff --git a/README.md b/README.md
index ce833bfe..7a4cea27 100644
--- a/README.md
+++ b/README.md
@@ -632,8 +632,8 @@ user's Local Network permission on iOS.
A rejected URL logs `Rejected remote marker image URI` — under the `NitroMaps` logcat tag on
Android, and under the `NitroMaps` category of the `com.nitromaps` subsystem in the unified log
-on iOS. The marker itself falls back to the default pin on both Google providers. On Apple Maps
-it draws with no image at all, the same as any marker image that fails to load.
+on iOS. The marker itself stays invisible on every provider, the same as any marker image that
+fails to load.
`require()`d assets are exempt, including the packager URL Metro resolves them to in a
development build.
@@ -656,10 +656,14 @@ Additional props:
Platform notes:
- Recommended icon size: up to **128×128 dp**; larger bitmaps are downscaled when `width`/`height` are provided.
-- Retina assets: pass `require()` and let Metro resolve `@2x`/`@3x`; optional explicit `width`/`height`/`scale` on `MarkerImage`.
+- Display size: an explicit `width` and `height` (in dp) win. Without them, `scale` maps the bitmap's pixels to dp, so a 50×82 px remote image with `scale: 2` draws at 25×41 dp on every device. Without either, a remote image keeps its pixel size.
+- Retina assets: pass `require()` and let Metro resolve `@2x`/`@3x`; it fills in `width`/`height` for you.
+- Until its image is ready, or after the load failed, a marker with `image` is invisible rather than the default pin. Changing `image` keeps the current image until the new one is ready, and a cached image is swapped in place. Failed loads log one warning per image (tag/category `NitroMaps`).
- Remote URLs use a basic in-memory cache only (no disk persistence).
- Custom React Native marker views (``) are not supported.
+> **Behavior change after 1.2.1:** `MarkerImage.scale` used to be ignored, so an image with `scale` but no `width`/`height` drew at its pixel size on iOS and at a density-dependent size on Android. It now draws at pixels ÷ `scale` dp on both. If you passed `scale` and sized your bitmaps around the old result, drop `scale` or set `width`/`height`.
+
### react-native-maps migration (markers)
| react-native-maps | react-native-better-maps |
diff --git a/example/App.tsx b/example/App.tsx
index 074f7562..588885e0 100644
--- a/example/App.tsx
+++ b/example/App.tsx
@@ -760,6 +760,9 @@ export default function App() {
const [dockExpanded, setDockExpanded] = useState(false);
const [customMarkerRotation, setCustomMarkerRotation] = useState(45);
const [customMarkerFlat, setCustomMarkerFlat] = useState(true);
+ const [selectedCustomMarkerId, setSelectedCustomMarkerId] = useState<
+ string | null
+ >(null);
const [applePoiDetailPresentation, setApplePoiDetailPresentation] =
useState(
APPLE_POI_DETAILS_DEFAULT_PRESENTATION,
@@ -772,6 +775,7 @@ export default function App() {
return createCustomMarkerImagesScenario({
rotation: customMarkerRotation,
flat: customMarkerFlat,
+ selectedMarkerId: selectedCustomMarkerId,
});
case APPLE_POI_DETAILS_SCENARIO_ID:
return createApplePoiDetailsScenario(applePoiDetailPresentation);
@@ -782,6 +786,7 @@ export default function App() {
baseScenario,
customMarkerRotation,
customMarkerFlat,
+ selectedCustomMarkerId,
applePoiDetailPresentation,
]);
const provider = SUPPORTED_MAP_PROVIDERS[providerIndex] ?? 'google';
@@ -896,6 +901,7 @@ export default function App() {
const handleMarkerPress = useCallback((id: string) => {
setStatus(`Marker · ${id}`);
+ setSelectedCustomMarkerId((current) => (current === id ? null : id));
}, []);
const handleMarkerDragEnd = useCallback(
diff --git a/example/examples/customMarkerImages.ts b/example/examples/customMarkerImages.ts
index 02dcdcb4..f75ad7ca 100644
--- a/example/examples/customMarkerImages.ts
+++ b/example/examples/customMarkerImages.ts
@@ -25,8 +25,12 @@ const PIN_ANCHOR = { x: 0.5, y: 1 } as const;
export interface CustomMarkerImagesOptions {
rotation: number;
flat: boolean;
+ /** The last pressed marker; the selectable pin grows while it is selected. */
+ selectedMarkerId: string | null;
}
+const SELECTABLE_MARKER_ID = 'selectable-pin';
+
const BASE = {
latitude: 52.2297,
longitude: 21.0122,
@@ -81,10 +85,10 @@ export function createCustomMarkerImagesScenario(
longitude: longitude + lngStep * 1.5,
},
title: 'Remote URL',
- subtitle: 'Leaflet gold pin · async fetch',
+ subtitle: 'Leaflet gold pin · scale 2 only · 25×41 dp',
image: {
uri: `${LEAFLET_BASE}/marker-icon-2x-gold.png`,
- ...LEAFLET_MARKER,
+ scale: LEAFLET_MARKER.scale,
},
anchor: PIN_ANCHOR,
},
@@ -207,6 +211,24 @@ export function createCustomMarkerImagesScenario(
},
anchor: PIN_ANCHOR,
},
+ {
+ id: SELECTABLE_MARKER_ID,
+ coordinate: {
+ latitude: latitude - latStep * 3.9,
+ longitude,
+ },
+ title: 'Image swap',
+ subtitle: 'Press to toggle 25×41 / 37×61 dp · swaps in place',
+ // A remote URL: a `require()`d asset cannot set its own size, and its `uri` passed as a
+ // plain object counts as user-supplied, so Android rejects the Metro host in development.
+ image: {
+ uri: `${LEAFLET_BASE}/marker-icon-2x-violet.png`,
+ width: options.selectedMarkerId === SELECTABLE_MARKER_ID ? 37 : 25,
+ height: options.selectedMarkerId === SELECTABLE_MARKER_ID ? 61 : 41,
+ scale: LEAFLET_MARKER.scale,
+ },
+ anchor: PIN_ANCHOR,
+ },
],
};
}
@@ -214,6 +236,7 @@ export function createCustomMarkerImagesScenario(
export const customMarkerImagesScenario = createCustomMarkerImagesScenario({
rotation: 45,
flat: true,
+ selectedMarkerId: null,
});
export const CUSTOM_MARKER_IMAGES_SCENARIO_ID = customMarkerImagesScenario.id;
diff --git a/package/android/src/main/java/com/margelo/nitro/nitromaps/MarkerDescriptor+MarkerOptions.kt b/package/android/src/main/java/com/margelo/nitro/nitromaps/MarkerDescriptor+MarkerOptions.kt
index eaea21ba..15e35dd7 100644
--- a/package/android/src/main/java/com/margelo/nitro/nitromaps/MarkerDescriptor+MarkerOptions.kt
+++ b/package/android/src/main/java/com/margelo/nitro/nitromaps/MarkerDescriptor+MarkerOptions.kt
@@ -9,6 +9,12 @@ fun MarkerDescriptor.toMarkerOptions(): MarkerOptions =
.title(title)
.snippet(subtitle)
.draggable(draggable == true)
+ .apply {
+ // Without an icon the marker is the default pin until `MarkerIconFactory` sets its image.
+ if (image != null) {
+ icon(placeholderMarkerIcon)
+ }
+ }
internal fun MarkerDescriptor.effectiveGoogleMapsAnchor(
widthPx: Float,
diff --git a/package/android/src/main/java/com/margelo/nitro/nitromaps/MarkerIconFactory.kt b/package/android/src/main/java/com/margelo/nitro/nitromaps/MarkerIconFactory.kt
index e6a7e25c..b6fab632 100644
--- a/package/android/src/main/java/com/margelo/nitro/nitromaps/MarkerIconFactory.kt
+++ b/package/android/src/main/java/com/margelo/nitro/nitromaps/MarkerIconFactory.kt
@@ -11,7 +11,9 @@ import android.util.LruCache
import com.google.android.gms.maps.model.BitmapDescriptor
import com.google.android.gms.maps.model.BitmapDescriptorFactory
import com.google.android.gms.maps.model.Marker
+import java.net.URI
import java.util.WeakHashMap
+import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors
@@ -24,9 +26,10 @@ internal class MarkerIconFactory(
private val cache = object : LruCache(iconCacheBytes()) {
override fun sizeOf(key: String, value: CachedIcon): Int = value.byteCount
}
- private val sizeCache = object : LruCache>(64) {}
private val mainHandler = Handler(Looper.getMainLooper())
private val appliedIconKeys = WeakHashMap()
+ // Size of the image icon each marker shows, kept with the marker so cache eviction cannot lose it.
+ private val appliedImageSizes = WeakHashMap>()
private val pendingIconLoads = WeakHashMap()
private val iconLoadGeneration = WeakHashMap()
@@ -35,7 +38,11 @@ internal class MarkerIconFactory(
var onIconApplied: () -> Unit,
)
- private class CachedIcon(val descriptor: BitmapDescriptor, val byteCount: Int)
+ private class CachedIcon(
+ val descriptor: BitmapDescriptor,
+ val byteCount: Int,
+ val sizePx: Pair,
+ )
fun applyVisualProps(
descriptor: MarkerDescriptor,
@@ -62,10 +69,11 @@ internal class MarkerIconFactory(
marker: Marker,
) {
val size =
- if (descriptor.image != null) {
- displaySizePx(descriptor.image) ?: (0f to 0f)
- } else {
- defaultMarkerDisplaySizePx()
+ when {
+ // While a replacement loads the old image stays on the map, so the anchor is sized for it.
+ descriptor.image != null && showsImage(marker) -> appliedImageSizes[marker] ?: (0f to 0f)
+ descriptor.image != null -> explicitDisplaySizePx(descriptor.image) ?: (0f to 0f)
+ else -> defaultMarkerDisplaySizePx()
}
val (anchorX, anchorY) = descriptor.effectiveGoogleMapsAnchor(size.first, size.second, density)
marker.setAnchor(anchorX, anchorY)
@@ -104,6 +112,8 @@ internal class MarkerIconFactory(
val iconKey = cacheKey(image)
if (isIconApplied(marker, iconKey)) {
+ // Back to the shown image: a load still running for another one must not replace it.
+ invalidatePendingLoad(marker)
return
}
@@ -117,10 +127,15 @@ internal class MarkerIconFactory(
cache.get(iconKey)?.let { cached ->
marker.setIcon(cached.descriptor)
setApplied(marker, iconKey)
+ appliedImageSizes[marker] = cached.sizePx
onIconApplied()
return
}
+ // A marker that already shows an image keeps it until the new one is ready, like a cache hit.
+ if (!showsImage(marker)) {
+ showPlaceholder(marker)
+ }
val generation = beginPendingLoad(marker, iconKey, onIconApplied)
loadIconAsync(image) { loaded ->
if (iconLoadGeneration[marker] != generation) {
@@ -133,28 +148,32 @@ internal class MarkerIconFactory(
}
if (loaded == null) {
+ // The load logged why. The placeholder key makes the next apply retry the load.
+ showPlaceholder(marker)
return@loadIconAsync
}
- marker.setIcon(loaded)
+ marker.setIcon(loaded.descriptor)
setApplied(marker, iconKey)
+ appliedImageSizes[marker] = loaded.sizePx
callback?.invoke()
}
}
- private fun displaySizePx(image: MarkerImage): Pair? {
- val key = cacheKey(image)
- sizeCache.get(key)?.let { return it }
-
- val widthDp = image.width
- val heightDp = image.height
- if (widthDp != null && heightDp != null) {
- val size = (widthDp * density).toFloat() to (heightDp * density).toFloat()
- sizeCache.put(key, size)
- return size
- }
+ private fun showsImage(marker: Marker): Boolean {
+ val key = appliedIconKeys[marker] ?: return false
+ return key != PLACEHOLDER_ICON_KEY && !key.startsWith(DEFAULT_ICON_KEY)
+ }
- return null
+ private fun showPlaceholder(marker: Marker) {
+ marker.setIcon(placeholderMarkerIcon)
+ appliedIconKeys[marker] = PLACEHOLDER_ICON_KEY
+ }
+
+ private fun explicitDisplaySizePx(image: MarkerImage): Pair? {
+ val widthDp = image.width ?: return null
+ val heightDp = image.height ?: return null
+ return (widthDp * density).toFloat() to (heightDp * density).toFloat()
}
private fun defaultMarkerDisplaySizePx(): Pair = (DEFAULT_MARKER_WIDTH_DP * density) to (DEFAULT_MARKER_HEIGHT_DP * density)
@@ -168,18 +187,22 @@ internal class MarkerIconFactory(
private fun loadLocalIcon(
image: MarkerImage,
key: String,
- ): BitmapDescriptor? {
- val bitmap = loadLocalBitmap(image) ?: return null
+ ): CachedIcon? {
+ val bitmap = loadLocalBitmap(image)
+ if (bitmap == null) {
+ logLoadFailure(image, key, "not found or not decodable")
+ return null
+ }
return cacheBitmap(key, bitmap)
}
private fun loadIconAsync(
image: MarkerImage,
- onLoaded: (BitmapDescriptor?) -> Unit,
+ onLoaded: (CachedIcon?) -> Unit,
) {
val key = cacheKey(image)
cache.get(key)?.let { cached ->
- deliverOnMainThread { onLoaded(cached.descriptor) }
+ deliverOnMainThread { onLoaded(cached) }
return
}
@@ -192,13 +215,13 @@ internal class MarkerIconFactory(
}
loadExecutor.execute {
- val descriptor =
+ val icon =
if (RemoteMarkerUriPolicy.isRemoteUri(image.uri)) {
loadRemoteIcon(image, key)
} else {
loadLocalIcon(image, key)
}
- deliverOnMainThread { onLoaded(descriptor) }
+ deliverOnMainThread { onLoaded(icon) }
}
}
@@ -242,13 +265,18 @@ internal class MarkerIconFactory(
private fun loadRemoteIcon(
image: MarkerImage,
key: String,
- ): BitmapDescriptor? {
+ ): CachedIcon? {
return try {
val bytes = remoteImageFetcher.fetch(image, ::logRejectedRemoteMarkerUri) ?: return null
- val bitmap = decodeByteArray(bytes, image) ?: return null
- cacheBitmap(key, resizeBitmap(bitmap, image))
+ val bitmap = decodeByteArray(bytes, image)
+ if (bitmap == null) {
+ logLoadFailure(image, key, "not decodable")
+ return null
+ }
+ cacheBitmap(key, bitmap)
} catch (error: Exception) {
- Log.w(NITRO_MAPS_LOG_TAG, "Failed to load marker image: ${image.uri}", error)
+ // Not the exception itself: its message can carry the full URL.
+ logLoadFailure(image, key, "request failed: ${error.javaClass.simpleName}")
null
}
}
@@ -276,9 +304,7 @@ internal class MarkerIconFactory(
}
return try {
- context.assets.open(uri).use { stream ->
- decodeByteArray(stream.readBytes(), image)?.let { resizeBitmap(it, image) }
- }
+ context.assets.open(uri).use { stream -> decodeByteArray(stream.readBytes(), image) }
} catch (_: Exception) {
null
}
@@ -287,24 +313,12 @@ internal class MarkerIconFactory(
private fun decodeFile(
path: String,
image: MarkerImage,
- ): Bitmap? {
- val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }
- BitmapFactory.decodeFile(path, bounds)
- val options = buildDecodeOptions(bounds.outWidth, bounds.outHeight, image) ?: return null
- val decoded = BitmapFactory.decodeFile(path, options) ?: return null
- return resizeBitmap(decoded, image)
- }
+ ): Bitmap? = decodeSized(image) { options -> BitmapFactory.decodeFile(path, options) }
private fun decodeResource(
resourceId: Int,
image: MarkerImage,
- ): Bitmap? {
- val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }
- BitmapFactory.decodeResource(context.resources, resourceId, bounds)
- val options = buildDecodeOptions(bounds.outWidth, bounds.outHeight, image) ?: return null
- val decoded = BitmapFactory.decodeResource(context.resources, resourceId, options) ?: return null
- return resizeBitmap(decoded, image)
- }
+ ): Bitmap? = decodeSized(image) { options -> BitmapFactory.decodeResource(context.resources, resourceId, options) }
private fun decodeByteArray(
bytes: ByteArray,
@@ -313,38 +327,45 @@ internal class MarkerIconFactory(
if (bytes.isEmpty()) {
return null
}
- val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }
- BitmapFactory.decodeByteArray(bytes, 0, bytes.size, bounds)
- val options = buildDecodeOptions(bounds.outWidth, bounds.outHeight, image) ?: return null
- return BitmapFactory.decodeByteArray(bytes, 0, bytes.size, options)
- }
-
- private fun targetDecodeSizePx(image: MarkerImage): Pair? {
- val widthDp = image.width ?: return null
- val heightDp = image.height ?: return null
- return (widthDp * density).toInt().coerceAtLeast(1) to (heightDp * density).toInt().coerceAtLeast(1)
+ return decodeSized(image) { options -> BitmapFactory.decodeByteArray(bytes, 0, bytes.size, options) }
}
- private fun buildDecodeOptions(
- sourceWidth: Int,
- sourceHeight: Int,
+ /**
+ * Decodes through [decode] at the size [image] is drawn at. The size comes from the source's
+ * bounds, not the decoded bitmap, which `inSampleSize` may have shrunk.
+ */
+ private inline fun decodeSized(
image: MarkerImage,
- ): BitmapFactory.Options? {
+ decode: (BitmapFactory.Options) -> Bitmap?,
+ ): Bitmap? {
+ val bounds =
+ BitmapFactory.Options().apply {
+ inJustDecodeBounds = true
+ inScaled = false
+ }
+ decode(bounds)
+ val sourceWidth = bounds.outWidth
+ val sourceHeight = bounds.outHeight
if (sourceWidth <= 0 || sourceHeight <= 0) {
return null
}
- val target = targetDecodeSizePx(image)
- val sampleSize =
- computeInSampleSize(
- sourceWidth = sourceWidth,
- sourceHeight = sourceHeight,
- reqWidth = target?.first,
- reqHeight = target?.second,
- )
- return BitmapFactory.Options().apply {
- inSampleSize = sampleSize
- inScaled = false
- }
+ val target =
+ image
+ .displaySizePx(sourceWidth, sourceHeight, density)
+ ?.boundedTo(MAX_DECODE_DIMENSION, MAX_DECODE_PIXELS)
+ val options =
+ BitmapFactory.Options().apply {
+ inSampleSize =
+ computeInSampleSize(
+ sourceWidth = sourceWidth,
+ sourceHeight = sourceHeight,
+ reqWidth = target?.first,
+ reqHeight = target?.second,
+ )
+ inScaled = false
+ }
+ val decoded = decode(options) ?: return null
+ return resizeBitmap(decoded, target)
}
private fun computeInSampleSize(
@@ -387,28 +408,44 @@ internal class MarkerIconFactory(
private fun cacheBitmap(
key: String,
bitmap: Bitmap,
- ): BitmapDescriptor {
- val descriptor = BitmapDescriptorFactory.fromBitmap(bitmap)
- cache.put(key, CachedIcon(descriptor, bitmap.allocationByteCount.coerceAtLeast(1)))
- sizeCache.put(key, bitmap.width.toFloat() to bitmap.height.toFloat())
- return descriptor
+ ): CachedIcon {
+ val icon =
+ CachedIcon(
+ descriptor = BitmapDescriptorFactory.fromBitmap(bitmap),
+ byteCount = bitmap.allocationByteCount.coerceAtLeast(1),
+ sizePx = bitmap.width.toFloat() to bitmap.height.toFloat(),
+ )
+ cache.put(key, icon)
+ return icon
}
private fun logRejectedRemoteMarkerUri(
uri: String,
reason: String,
) {
- Log.w(NITRO_MAPS_LOG_TAG, "Rejected remote marker image URI ($reason): $uri")
+ Log.w(NITRO_MAPS_LOG_TAG, "Rejected remote marker image URI ($reason): ${loggableUri(uri)}")
+ }
+
+ /** Once per image: a failed load is not cached, so every re-render retries it. */
+ private fun logLoadFailure(
+ image: MarkerImage,
+ key: String,
+ reason: String,
+ ) {
+ // Bounded: URIs that differ per request would otherwise grow it forever.
+ if (loggedFailureKeys.size >= MAX_LOGGED_FAILURE_KEYS) {
+ loggedFailureKeys.clear()
+ }
+ if (loggedFailureKeys.add(key)) {
+ Log.w(NITRO_MAPS_LOG_TAG, "Failed to load marker image ($reason): ${loggableUri(image.uri)}")
+ }
}
private fun resizeBitmap(
source: Bitmap,
- image: MarkerImage,
+ target: Pair?,
): Bitmap {
- val width = image.width ?: return source
- val height = image.height ?: return source
- val targetWidth = (width * density).toInt().coerceAtLeast(1)
- val targetHeight = (height * density).toInt().coerceAtLeast(1)
+ val (targetWidth, targetHeight) = target ?: return source
if (source.width == targetWidth && source.height == targetHeight) {
return source
@@ -419,9 +456,11 @@ internal class MarkerIconFactory(
private companion object {
const val DEFAULT_ICON_KEY = "__default__"
+ const val PLACEHOLDER_ICON_KEY = "__placeholder__"
private const val DEFAULT_MARKER_WIDTH_DP = 40f
private const val DEFAULT_MARKER_HEIGHT_DP = 52f
private const val MAX_DECODE_DIMENSION = 2048
+ private const val MAX_LOGGED_FAILURE_KEYS = 256
private const val MAX_DECODE_PIXELS = 2048L * 2048L
private const val MIN_ICON_CACHE_BYTES = 1024 * 1024
private const val MAX_ICON_CACHE_BYTES = 32 * 1024 * 1024
@@ -435,9 +474,27 @@ internal class MarkerIconFactory(
}
private val loadExecutor: ExecutorService = Executors.newSingleThreadExecutor()
+ private val loggedFailureKeys: MutableSet = ConcurrentHashMap.newKeySet()
+
+ /** Without the query string and credentials, which can carry a signed token or a password. */
+ private fun loggableUri(uri: String): String =
+ try {
+ val parsed = URI(uri)
+ URI(parsed.scheme, null, parsed.host, parsed.port, parsed.path, null, null).toString()
+ } catch (_: Exception) {
+ ""
+ }
// Shared by every map, and first built on the load executor: an HTTP client loads the system
// trust store when it is created.
private val remoteImageFetcher by lazy { RemoteMarkerImageFetcher() }
}
}
+
+/**
+ * Shown while a marker's first image loads, or after it failed: a marker without an icon is the
+ * default pin. Built on first use, once the Maps SDK is initialized.
+ */
+internal val placeholderMarkerIcon: BitmapDescriptor by lazy {
+ BitmapDescriptorFactory.fromBitmap(Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888))
+}
diff --git a/package/android/src/main/java/com/margelo/nitro/nitromaps/MarkerImage+DisplaySize.kt b/package/android/src/main/java/com/margelo/nitro/nitromaps/MarkerImage+DisplaySize.kt
new file mode 100644
index 00000000..91b726cf
--- /dev/null
+++ b/package/android/src/main/java/com/margelo/nitro/nitromaps/MarkerImage+DisplaySize.kt
@@ -0,0 +1,54 @@
+package com.margelo.nitro.nitromaps
+
+import kotlin.math.floor
+import kotlin.math.roundToInt
+import kotlin.math.sqrt
+
+/**
+ * The size, in pixels, this image is drawn at when its source bitmap is
+ * [sourceWidthPx]×[sourceHeightPx]. An explicit `width` and `height` win; otherwise a usable
+ * `scale` maps the source pixels to dp. `null` keeps the source size. Mirrors
+ * `MarkerImageDisplaySize.swift`.
+ */
+internal fun MarkerImage.displaySizePx(
+ sourceWidthPx: Int,
+ sourceHeightPx: Int,
+ density: Float,
+): Pair? {
+ val widthDp = width
+ val heightDp = height
+ if (widthDp != null && heightDp != null && widthDp > 0 && heightDp > 0) {
+ return (widthDp * density).toInt().coerceAtLeast(1) to (heightDp * density).toInt().coerceAtLeast(1)
+ }
+
+ val scale = scale?.takeIf { it.isFinite() && it > 0 } ?: return null
+ val pxPerSourcePx = density / scale
+ return (sourceWidthPx * pxPerSourcePx).roundToInt().coerceAtLeast(1) to
+ (sourceHeightPx * pxPerSourcePx).roundToInt().coerceAtLeast(1)
+}
+
+/**
+ * This size shrunk, keeping its aspect ratio, until neither side exceeds [maxDimension] and the
+ * area stays within [maxPixels], so a large `width`/`height` or a small `scale` cannot resize a
+ * sampled bitmap back past the decode limits.
+ */
+internal fun Pair.boundedTo(
+ maxDimension: Int,
+ maxPixels: Long,
+): Pair {
+ val (width, height) = this
+ val pixels = width.toLong() * height
+ if (maxOf(width, height) <= maxDimension && pixels <= maxPixels) {
+ return this
+ }
+ val factor =
+ minOf(
+ maxDimension.toDouble() / maxOf(width, height),
+ sqrt(maxPixels.toDouble() / pixels),
+ )
+ // The epsilon keeps a side that scales to exactly the limit from flooring one pixel short.
+ return floor(width * factor + ROUNDING_EPSILON).toInt().coerceAtLeast(1) to
+ floor(height * factor + ROUNDING_EPSILON).toInt().coerceAtLeast(1)
+}
+
+private const val ROUNDING_EPSILON = 1e-6
diff --git a/package/android/src/test/java/com/margelo/nitro/nitromaps/MarkerImageDisplaySizeTest.kt b/package/android/src/test/java/com/margelo/nitro/nitromaps/MarkerImageDisplaySizeTest.kt
new file mode 100644
index 00000000..f97affb0
--- /dev/null
+++ b/package/android/src/test/java/com/margelo/nitro/nitromaps/MarkerImageDisplaySizeTest.kt
@@ -0,0 +1,70 @@
+package com.margelo.nitro.nitromaps
+
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertNull
+import org.junit.Test
+
+class MarkerImageDisplaySizeTest {
+ private fun image(
+ width: Double? = null,
+ height: Double? = null,
+ scale: Double? = null,
+ ) = MarkerImage("https://example.test/pin.png", width, height, scale, null)
+
+ @Test
+ fun `explicit width and height win over scale`() {
+ assertEquals(111 to 183, image(width = 37.0, height = 61.0, scale = 2.0).displaySizePx(50, 82, 3f))
+ }
+
+ @Test
+ fun `scale maps source pixels to dp on every density`() {
+ // A 50×82 px bitmap authored for a 25×41 dp pin.
+ val pin = image(scale = 2.0)
+ assertEquals(25 to 41, pin.displaySizePx(50, 82, 1f))
+ assertEquals(50 to 82, pin.displaySizePx(50, 82, 2f))
+ assertEquals(75 to 123, pin.displaySizePx(50, 82, 3f))
+ }
+
+ @Test
+ fun `only one explicit dimension falls back to scale`() {
+ assertEquals(40 to 60, image(width = 40.0, scale = 3.0).displaySizePx(60, 90, 2f))
+ }
+
+ @Test
+ fun `without a usable scale the source size is kept`() {
+ assertNull(image().displaySizePx(50, 82, 3f))
+ assertNull(image(scale = 0.0).displaySizePx(50, 82, 3f))
+ assertNull(image(scale = -1.0).displaySizePx(50, 82, 3f))
+ assertNull(image(scale = Double.NaN).displaySizePx(50, 82, 3f))
+ assertNull(image(scale = Double.POSITIVE_INFINITY).displaySizePx(50, 82, 3f))
+ }
+
+ @Test
+ fun `tiny results stay at least one pixel`() {
+ assertEquals(1 to 1, image(scale = 100.0).displaySizePx(10, 10, 1f))
+ }
+
+ @Test
+ fun `a size within the limits is kept`() {
+ assertEquals(150 to 246, (150 to 246).boundedTo(2048, 2048L * 2048L))
+ assertEquals(2048 to 2048, (2048 to 2048).boundedTo(2048, 2048L * 2048L))
+ }
+
+ @Test
+ fun `a scale-enlarged size is bounded with its aspect ratio`() {
+ // A 4000×3000 source at scale 1 on density 3 asks for 12000×9000.
+ val target = image(scale = 1.0).displaySizePx(4000, 3000, 3f)!!.boundedTo(2048, 2048L * 2048L)
+ assertEquals(2048 to 1536, target)
+ }
+
+ @Test
+ fun `the pixel limit binds when both sides fit`() {
+ val (width, height) = (2000 to 2000).boundedTo(4096, 1000L * 1000L)
+ assertEquals(1000 to 1000, width to height)
+ }
+
+ @Test
+ fun `an extreme aspect ratio keeps at least one pixel`() {
+ assertEquals(2048 to 1, (100_000 to 1).boundedTo(2048, 2048L * 2048L))
+ }
+}
diff --git a/package/ios/GoogleMarkerVisualApplier.swift b/package/ios/GoogleMarkerVisualApplier.swift
index bb68533a..34c8b62a 100644
--- a/package/ios/GoogleMarkerVisualApplier.swift
+++ b/package/ios/GoogleMarkerVisualApplier.swift
@@ -5,7 +5,15 @@ import UIKit
/// Applies a marker descriptor's visual fields onto a `GMSMarker`. Main-thread only.
final class GoogleMarkerVisualApplier {
private static let defaultIconToken: NSString = "__default__"
+ private static let placeholderIconToken: NSString = "__placeholder__"
private static let defaultPinImage = GMSMarker.markerImage(with: nil)
+ /// Shown while a marker's first image loads, or after it failed: a `nil` icon is the default pin.
+ static let placeholderIcon: UIImage = {
+ let format = UIGraphicsImageRendererFormat()
+ format.opaque = false
+ format.scale = 1
+ return UIGraphicsImageRenderer(size: CGSize(width: 1, height: 1), format: format).image { _ in }
+ }()
private struct PendingIconLoad {
let applicationToken: NSObject
@@ -36,13 +44,14 @@ final class GoogleMarkerVisualApplier {
marker.rotation = descriptor.rotation ?? 0
marker.isFlat = descriptor.flat == true
marker.opacity = Float(descriptor.opacity ?? 1)
- applyAnchor(descriptor, to: marker)
+ // After the icon: the anchor has to know whether a replacement is still loading.
applyIcon(descriptor, to: marker)
+ applyAnchor(descriptor, to: marker)
}
private func applyAnchor(_ descriptor: MarkerDescriptor, to marker: GMSMarker) {
marker.groundAnchor = descriptor.effectiveGoogleMapsAnchor(
- imageSize: anchorImageSize(descriptor, icon: marker.icon)
+ imageSize: anchorImageSize(descriptor, marker: marker)
)
}
@@ -79,7 +88,21 @@ final class GoogleMarkerVisualApplier {
return
}
+ // A re-render while the same image loads keeps that load instead of starting another one.
+ if let pending = state.pending, pending.imageToken == imageToken {
+ state.pending = PendingIconLoad(
+ applicationToken: pending.applicationToken,
+ imageToken: imageToken,
+ descriptor: descriptor
+ )
+ return
+ }
+
cancelPending(state)
+ // A marker that already shows an image keeps it until the new one is ready, like a cache hit.
+ if !showsImage(state) {
+ showPlaceholder(on: marker, state: state)
+ }
let applicationToken = NSObject()
state.pending = PendingIconLoad(
applicationToken: applicationToken,
@@ -97,6 +120,8 @@ final class GoogleMarkerVisualApplier {
}
state.pending = nil
guard let uiImage else {
+ // The loader logged why. The placeholder token makes the next apply retry the load.
+ self.showPlaceholder(on: marker, state: state)
return
}
self.setIcon(
@@ -121,6 +146,18 @@ final class GoogleMarkerVisualApplier {
state.appliedImageToken = token
}
+ private func showsImage(_ state: MarkerIconState) -> Bool {
+ guard let token = state.appliedImageToken, token != Self.placeholderIconToken else {
+ return false
+ }
+ return !token.hasPrefix(Self.defaultIconToken as String)
+ }
+
+ private func showPlaceholder(on marker: GMSMarker, state: MarkerIconState) {
+ marker.icon = Self.placeholderIcon
+ state.appliedImageToken = Self.placeholderIconToken
+ }
+
private func state(for marker: GMSMarker) -> MarkerIconState {
if let existing = states.object(forKey: marker) {
return existing
@@ -134,7 +171,15 @@ final class GoogleMarkerVisualApplier {
state.pending = nil
}
- private func anchorImageSize(_ descriptor: MarkerDescriptor, icon: UIImage?) -> CGSize {
+ private func anchorImageSize(_ descriptor: MarkerDescriptor, marker: GMSMarker) -> CGSize {
+ let icon = marker.icon
+ // While a replacement loads the old image stays on the map, so the anchor is sized for it.
+ // `setIcon` sizes it again for the replacement once that lands.
+ if let state = states.object(forKey: marker), state.pending != nil, showsImage(state),
+ let icon, icon.size.width > 0, icon.size.height > 0
+ {
+ return icon.size
+ }
if let image = descriptor.image, let width = image.width, let height = image.height,
width > 0, height > 0
{
@@ -143,7 +188,7 @@ final class GoogleMarkerVisualApplier {
if descriptor.image == nil {
return Self.defaultPinImage.size
}
- if let icon, icon.size.width > 0, icon.size.height > 0 {
+ if let icon, icon !== Self.placeholderIcon, icon.size.width > 0, icon.size.height > 0 {
return icon.size
}
return Self.defaultPinImage.size
diff --git a/package/ios/MarkerImageLoader.swift b/package/ios/MarkerImageLoader.swift
index 3eb5974e..3727c6b2 100644
--- a/package/ios/MarkerImageLoader.swift
+++ b/package/ios/MarkerImageLoader.swift
@@ -36,6 +36,9 @@ enum MarkerImageLoader {
/// The category matches `NITRO_MAPS_LOG_TAG` on Android, so a rejected image is found the same
/// way on both platforms.
private static let logger = Logger(subsystem: "com.nitromaps", category: "NitroMaps")
+ /// A failed load is not cached, so every re-render retries it; the warning is logged once.
+ private static let failureLogLock = NSLock()
+ private static var loggedFailureKeys = Set()
static func cachedImage(for image: MarkerImage) -> UIImage? {
cache.object(forKey: cacheKey(for: image))
@@ -61,6 +64,8 @@ enum MarkerImageLoader {
let loaded = loadLocal(uri: uri, image: image)
if let loaded {
cache.setObject(loaded, forKey: cacheKey, cost: byteCost(of: loaded))
+ } else {
+ logLoadFailure(uri: uri, cacheKey: cacheKey, reason: "not found or not decodable")
}
DispatchQueue.main.async {
completion(loaded)
@@ -80,7 +85,7 @@ enum MarkerImageLoader {
private static func loadLocal(uri: String, image: MarkerImage) -> UIImage? {
if uri.hasPrefix("file://"), let url = URL(string: uri) {
- if let data = try? Data(contentsOf: url), let uiImage = UIImage(data: data) {
+ if let data = try? Data(contentsOf: url), let uiImage = decode(data, image: image) {
return resize(uiImage, image: image)
}
}
@@ -171,21 +176,52 @@ enum MarkerImageLoader {
)
}
+ /// Logged like `logRejected`: the public half drops the query string and credentials.
+ private static func logLoadFailure(uri: String, cacheKey: NSString, reason: String) {
+ failureLogLock.lock()
+ // Bounded like the image cache: URIs that differ per request would otherwise grow it forever.
+ if loggedFailureKeys.count >= maximumCachedImages {
+ loggedFailureKeys.removeAll()
+ }
+ let isFirst = loggedFailureKeys.insert(cacheKey).inserted
+ failureLogLock.unlock()
+ guard isFirst else {
+ return
+ }
+ logger.warning(
+ """
+ Failed to load marker image (\(reason, privacy: .public)): \
+ \(RemoteMarkerUriPolicy.loggableURI(uri), privacy: .public) \
+ [full: \(uri, privacy: .private)]
+ """
+ )
+ }
+
private static func startRemoteTask(
url: URL,
cacheKey: NSString,
image: MarkerImage,
completion: @escaping (UIImage?) -> Void
) {
- let task = session.dataTask(with: url) { data, _, _ in
+ let task = session.dataTask(with: url) { data, response, error in
let uiImage: UIImage?
- if let data, let decoded = UIImage(data: data) {
- uiImage = resize(decoded, image: image)
- if let uiImage {
- cache.setObject(uiImage, forKey: cacheKey, cost: byteCost(of: uiImage))
- }
+ let statusCode = (response as? HTTPURLResponse)?.statusCode
+ if let statusCode, !(200..<300).contains(statusCode) {
+ // An error page can still decode as an image; it must not be cached or shown.
+ uiImage = nil
+ logLoadFailure(uri: image.uri, cacheKey: cacheKey, reason: "HTTP \(statusCode)")
+ } else if let data, let decoded = decode(data, image: image) {
+ let resized = resize(decoded, image: image)
+ cache.setObject(resized, forKey: cacheKey, cost: byteCost(of: resized))
+ uiImage = resized
} else {
uiImage = nil
+ let status = statusCode.map { " (HTTP \($0))" } ?? ""
+ logLoadFailure(
+ uri: image.uri,
+ cacheKey: cacheKey,
+ reason: error == nil ? "not decodable\(status)" : "request failed"
+ )
}
DispatchQueue.main.async {
@@ -253,18 +289,39 @@ enum MarkerImageLoader {
return max(1, pixelWidth * pixelHeight * 4)
}
- private static func resize(_ uiImage: UIImage, image: MarkerImage) -> UIImage {
- guard let width = image.width, let height = image.height else {
- return uiImage
- }
+ /// Decodes at `MarkerImage.scale`, so `size` is already in points and `resize` has nothing to
+ /// redraw unless an explicit width and height ask for another size.
+ private static func decode(_ data: Data, image: MarkerImage) -> UIImage? {
+ UIImage(data: data, scale: MarkerImageDisplaySize.decodeScale(image.scale))
+ }
- let targetSize = CGSize(width: CGFloat(width), height: CGFloat(height))
+ private static func resize(_ uiImage: UIImage, image: MarkerImage) -> UIImage {
+ let targetSize = MarkerImageDisplaySize.points(
+ size: uiImage.size,
+ imageScale: uiImage.scale,
+ width: image.width,
+ height: image.height,
+ scale: image.scale
+ )
if uiImage.size == targetSize {
return uiImage
}
- let renderer = UIGraphicsImageRenderer(size: targetSize)
+ // A `scale` alone only changes how many pixels make a point: retag the bitmap instead of
+ // redrawing it at a larger size.
+ let hasExplicitSize = (image.width ?? 0) > 0 && (image.height ?? 0) > 0
+ if !hasExplicitSize, let cgImage = uiImage.cgImage {
+ return UIImage(
+ cgImage: cgImage,
+ scale: MarkerImageDisplaySize.decodeScale(image.scale),
+ orientation: uiImage.imageOrientation
+ )
+ }
+
+ let format = UIGraphicsImageRendererFormat.preferred()
+ format.scale = MarkerImageDisplaySize.rasterScale(points: targetSize, screenScale: format.scale)
+ let renderer = UIGraphicsImageRenderer(size: targetSize, format: format)
return renderer.image { _ in
uiImage.draw(in: CGRect(origin: .zero, size: targetSize))
}
diff --git a/package/ios/MarkerImageSize/MarkerImageDisplaySize.swift b/package/ios/MarkerImageSize/MarkerImageDisplaySize.swift
new file mode 100644
index 00000000..4c350368
--- /dev/null
+++ b/package/ios/MarkerImageSize/MarkerImageDisplaySize.swift
@@ -0,0 +1,58 @@
+import CoreGraphics
+
+/// How large a marker image is drawn, in points. Mirrors `MarkerImage+DisplaySize.kt`.
+enum MarkerImageDisplaySize {
+ /// The scale raw image bytes are decoded at: `MarkerImage.scale` when it is usable, else 1,
+ /// which is what `UIImage(data:)` assumes.
+ static func decodeScale(_ scale: Double?) -> CGFloat {
+ guard let scale, scale.isFinite, scale > 0 else {
+ return 1
+ }
+ return CGFloat(scale)
+ }
+
+ /// An explicit `width` and `height` win. Otherwise a usable `scale` maps the decoded pixels to
+ /// points, and without one the image keeps the size it was decoded at — an asset catalog image
+ /// already carries its `@2x`/`@3x` scale.
+ ///
+ /// - Parameters:
+ /// - size: the decoded image's `size`, in points.
+ /// - imageScale: the decoded image's `scale`, so `size * imageScale` is its pixel size.
+ static func points(
+ size: CGSize,
+ imageScale: CGFloat,
+ width: Double?,
+ height: Double?,
+ scale: Double?
+ ) -> CGSize {
+ if let width, let height, width > 0, height > 0 {
+ return CGSize(width: width, height: height)
+ }
+ guard let scale, scale.isFinite, scale > 0 else {
+ return size
+ }
+ let pixelsPerPoint = imageScale / CGFloat(scale)
+ return CGSize(width: size.width * pixelsPerPoint, height: size.height * pixelsPerPoint)
+ }
+
+ /// Same limits as `MAX_DECODE_DIMENSION` / `MAX_DECODE_PIXELS` in `MarkerIconFactory.kt`.
+ static let maxRasterDimension: CGFloat = 2048
+ static let maxRasterPixels: CGFloat = 2048 * 2048
+
+ /// The scale to rasterize `points` at: `screenScale`, lowered until neither side of the bitmap
+ /// exceeds `maxRasterDimension` pixels and its area stays within `maxRasterPixels`, so a large
+ /// `width`/`height` cannot allocate an unbounded bitmap. The point size, and so the size on the
+ /// map, stays the same.
+ static func rasterScale(points: CGSize, screenScale: CGFloat) -> CGFloat {
+ let longestSide = max(points.width, points.height)
+ let area = points.width * points.height
+ guard longestSide > 0, area > 0 else {
+ return screenScale
+ }
+ return min(
+ screenScale,
+ maxRasterDimension / longestSide,
+ (maxRasterPixels / area).squareRoot()
+ )
+ }
+}
diff --git a/package/ios/NitroImageAnnotationView.swift b/package/ios/NitroImageAnnotationView.swift
index ab01643d..125cdc69 100644
--- a/package/ios/NitroImageAnnotationView.swift
+++ b/package/ios/NitroImageAnnotationView.swift
@@ -6,6 +6,10 @@ final class NitroImageAnnotationView: MKAnnotationView {
static let reuseIdentifier = "NitroImage"
private var loadToken: NSString?
+ /// Identifies the latest image request. A completion from an older request is ignored.
+ private var loadGeneration = 0
+ /// MapKit sets `annotation` on dequeue, before `configure(for:)`, so it cannot tell a reuse.
+ private weak var configuredMarker: MapMarkerAnnotation?
override init(annotation: MKAnnotation?, reuseIdentifier: String?) {
super.init(annotation: annotation, reuseIdentifier: reuseIdentifier)
@@ -20,7 +24,9 @@ final class NitroImageAnnotationView: MKAnnotationView {
}
func configure(for marker: MapMarkerAnnotation) {
+ let isSameAnnotation = configuredMarker === marker
annotation = marker
+ configuredMarker = marker
isDraggable = marker.draggable
canShowCallout = marker.title != nil || marker.subtitle != nil
alpha = marker.opacity
@@ -37,17 +43,33 @@ final class NitroImageAnnotationView: MKAnnotationView {
}
let token = MarkerImageLoader.cacheKey(for: imageDescriptor)
- if loadToken == token {
+ // Only for the same marker: on a reused view the token may belong to a load that left the
+ // previous marker's image showing.
+ if loadToken == token, isSameAnnotation {
applyLayout(for: marker, imageSize: self.image?.size ?? .zero)
return
}
loadToken = token
- self.image = nil
- applyLayout(for: marker, imageSize: .zero)
+ loadGeneration += 1
+ let generation = loadGeneration
+ if let cached = MarkerImageLoader.cachedImage(for: imageDescriptor) {
+ self.image = cached
+ applyLayout(for: marker, imageSize: cached.size)
+ return
+ }
+
+ // A swap on the same marker keeps the current image until the new one is ready, so it does
+ // not blink. A reused view must not show the previous marker's image.
+ if !isSameAnnotation {
+ self.image = nil
+ }
+ applyLayout(for: marker, imageSize: self.image?.size ?? .zero)
MarkerImageLoader.load(imageDescriptor) { [weak self] uiImage in
guard let self else { return }
+ // A reused view can start a second load for the same image; the older one must not win.
+ guard generation == self.loadGeneration else { return }
guard let marker = self.annotation as? MapMarkerAnnotation,
let image = marker.image,
diff --git a/package/ios/Package.swift b/package/ios/Package.swift
index 41133a3b..f169fa3e 100644
--- a/package/ios/Package.swift
+++ b/package/ios/Package.swift
@@ -36,6 +36,10 @@ let package = Package(
name: "NitroMapsRemoteImagePolicy",
path: "RemoteImagePolicy"
),
+ .target(
+ name: "NitroMapsMarkerImageSize",
+ path: "MarkerImageSize"
+ ),
.testTarget(
name: "NitroMapsCameraTests",
dependencies: ["NitroMapsCamera"],
@@ -72,5 +76,10 @@ let package = Package(
dependencies: ["NitroMapsRemoteImagePolicy"],
path: "Tests/RemoteImagePolicy"
),
+ .testTarget(
+ name: "NitroMapsMarkerImageSizeTests",
+ dependencies: ["NitroMapsMarkerImageSize"],
+ path: "Tests/MarkerImageSize"
+ ),
]
)
diff --git a/package/ios/Tests/MarkerImageSize/MarkerImageDisplaySizeTests.swift b/package/ios/Tests/MarkerImageSize/MarkerImageDisplaySizeTests.swift
new file mode 100644
index 00000000..14332c5c
--- /dev/null
+++ b/package/ios/Tests/MarkerImageSize/MarkerImageDisplaySizeTests.swift
@@ -0,0 +1,119 @@
+import CoreGraphics
+import Testing
+
+@testable import NitroMapsMarkerImageSize
+
+@Test
+func explicitWidthAndHeightWinOverScale() {
+ let size = MarkerImageDisplaySize.points(
+ size: CGSize(width: 50, height: 82),
+ imageScale: 1,
+ width: 37,
+ height: 61,
+ scale: 2
+ )
+ #expect(size == CGSize(width: 37, height: 61))
+}
+
+@Test
+func scaleMapsDecodedPixelsToPoints() {
+ // A 50×82 px bitmap authored for a 25×41 pt pin, decoded by `UIImage(data:)` at scale 1.
+ let size = MarkerImageDisplaySize.points(
+ size: CGSize(width: 50, height: 82),
+ imageScale: 1,
+ width: nil,
+ height: nil,
+ scale: 2
+ )
+ #expect(size == CGSize(width: 25, height: 41))
+}
+
+@Test
+func imageDecodedAtTheRequestedScaleKeepsItsSize() {
+ let size = MarkerImageDisplaySize.points(
+ size: CGSize(width: 25, height: 41),
+ imageScale: 2,
+ width: nil,
+ height: nil,
+ scale: 2
+ )
+ #expect(size == CGSize(width: 25, height: 41))
+}
+
+@Test
+func withoutScaleTheDecodedSizeIsKept() {
+ // An asset catalog image carries its own `@3x` scale.
+ let size = MarkerImageDisplaySize.points(
+ size: CGSize(width: 25, height: 41),
+ imageScale: 3,
+ width: nil,
+ height: nil,
+ scale: nil
+ )
+ #expect(size == CGSize(width: 25, height: 41))
+}
+
+@Test
+func onlyOneExplicitDimensionFallsBackToScale() {
+ let size = MarkerImageDisplaySize.points(
+ size: CGSize(width: 60, height: 90),
+ imageScale: 1,
+ width: 40,
+ height: nil,
+ scale: 3
+ )
+ #expect(size == CGSize(width: 20, height: 30))
+}
+
+@Test
+func unusableScalesDecodeAtOne() {
+ #expect(MarkerImageDisplaySize.decodeScale(nil) == 1)
+ #expect(MarkerImageDisplaySize.decodeScale(0) == 1)
+ #expect(MarkerImageDisplaySize.decodeScale(-2) == 1)
+ #expect(MarkerImageDisplaySize.decodeScale(.nan) == 1)
+ #expect(MarkerImageDisplaySize.decodeScale(.infinity) == 1)
+ #expect(MarkerImageDisplaySize.decodeScale(3) == 3)
+}
+
+@Test
+func unusableScaleKeepsTheDecodedSize() {
+ let size = MarkerImageDisplaySize.points(
+ size: CGSize(width: 50, height: 82),
+ imageScale: 2,
+ width: nil,
+ height: nil,
+ scale: 0
+ )
+ #expect(size == CGSize(width: 50, height: 82))
+}
+
+@Test
+func smallImagesRasterizeAtTheScreenScale() {
+ #expect(
+ MarkerImageDisplaySize.rasterScale(points: CGSize(width: 37, height: 61), screenScale: 3) == 3)
+}
+
+@Test
+func largeImagesRasterizeWithinTheBitmapLimits() {
+ // 4000×3000 pt at 3× would be a 12000×9000 px bitmap.
+ let points = CGSize(width: 4000, height: 3000)
+ let scale = MarkerImageDisplaySize.rasterScale(points: points, screenScale: 3)
+ let pixelWidth = points.width * scale
+ let pixelHeight = points.height * scale
+ #expect(pixelWidth <= MarkerImageDisplaySize.maxRasterDimension + 0.001)
+ #expect(pixelHeight <= MarkerImageDisplaySize.maxRasterDimension + 0.001)
+ #expect(pixelWidth * pixelHeight <= MarkerImageDisplaySize.maxRasterPixels + 1)
+ #expect(abs(pixelWidth / pixelHeight - 4.0 / 3.0) < 0.0001)
+}
+
+@Test
+func longThinImagesAreBoundedBySide() {
+ let scale = MarkerImageDisplaySize.rasterScale(
+ points: CGSize(width: 10_000, height: 10), screenScale: 2)
+ #expect(abs(10_000 * scale - MarkerImageDisplaySize.maxRasterDimension) < 0.001)
+}
+
+@Test
+func emptySizesKeepTheScreenScale() {
+ #expect(MarkerImageDisplaySize.rasterScale(points: .zero, screenScale: 2) == 2)
+}
diff --git a/package/iosTests/GoogleMarkerVisualApplierTests.swift b/package/iosTests/GoogleMarkerVisualApplierTests.swift
index 3f5f1c14..d38901cd 100644
--- a/package/iosTests/GoogleMarkerVisualApplierTests.swift
+++ b/package/iosTests/GoogleMarkerVisualApplierTests.swift
@@ -24,17 +24,13 @@ final class GoogleMarkerVisualApplierTests: XCTestCase {
applier.apply(markerDescriptor(image: image, anchor: MarkerAnchor(x: 0, y: 0)), to: marker)
applier.apply(markerDescriptor(image: image, anchor: MarkerAnchor(x: 1, y: 1)), to: marker)
- XCTAssertEqual(completions.count, 2)
-
- let staleIcon = makeIcon()
- let latestIcon = makeIcon()
- completions[0](staleIcon)
-
- XCTAssertNil(marker.icon)
+ XCTAssertEqual(completions.count, 1)
+ XCTAssertTrue(marker.icon === GoogleMarkerVisualApplier.placeholderIcon)
- completions[1](latestIcon)
+ let icon = makeIcon()
+ completions[0](icon)
- XCTAssertTrue(marker.icon === latestIcon)
+ XCTAssertTrue(marker.icon === icon)
XCTAssertEqual(marker.groundAnchor.x, 1, accuracy: 0.0001)
XCTAssertEqual(marker.groundAnchor.y, 1, accuracy: 0.0001)
}
@@ -74,9 +70,124 @@ final class GoogleMarkerVisualApplierTests: XCTestCase {
XCTAssertEqual(marker.groundAnchor.x, 0, accuracy: 0.0001)
XCTAssertEqual(marker.groundAnchor.y, 0, accuracy: 0.0001)
}
+
+ func testUncachedImageShowsThePlaceholderInsteadOfTheDefaultPin() {
+ var completions: [(UIImage?) -> Void] = []
+ let applier = GoogleMarkerVisualApplier(
+ cachedImage: { _ in nil },
+ loadImage: { _, completion in completions.append(completion) }
+ )
+ let marker = GMSMarker()
+
+ applier.apply(markerDescriptor(image: remoteImage("a.png"), anchor: nil), to: marker)
+
+ XCTAssertTrue(marker.icon === GoogleMarkerVisualApplier.placeholderIcon)
+
+ let icon = makeIcon()
+ completions[0](icon)
+
+ XCTAssertTrue(marker.icon === icon)
+ }
+
+ func testSwapToAnUncachedImageKeepsTheCurrentImageUntilItLoads() {
+ let iconA = makeIcon()
+ let iconB = makeIcon()
+ var completions: [(UIImage?) -> Void] = []
+ let applier = GoogleMarkerVisualApplier(
+ cachedImage: { image in image.uri.hasSuffix("a.png") ? iconA : nil },
+ loadImage: { _, completion in completions.append(completion) }
+ )
+ let marker = GMSMarker()
+
+ applier.apply(markerDescriptor(image: remoteImage("a.png"), anchor: nil), to: marker)
+ applier.apply(markerDescriptor(image: remoteImage("b.png"), anchor: nil), to: marker)
+
+ XCTAssertTrue(marker.icon === iconA)
+
+ completions[0](iconB)
+
+ XCTAssertTrue(marker.icon === iconB)
+ }
+
+ func testAnchorFollowsTheShownIconWhileAReplacementLoads() {
+ let iconA = makeIcon()
+ var completions: [(UIImage?) -> Void] = []
+ let applier = GoogleMarkerVisualApplier(
+ cachedImage: { image in image.uri.hasSuffix("a.png") ? iconA : nil },
+ loadImage: { _, completion in completions.append(completion) }
+ )
+ let marker = GMSMarker()
+ let imageB = MarkerImage(
+ uri: "https://example.test/b.png",
+ width: 80,
+ height: 80,
+ scale: 1,
+ origin: nil
+ )
+ let offset = MarkerPoint(x: 0, y: 20)
+
+ applier.apply(
+ markerDescriptor(image: remoteImage("a.png"), anchor: nil, centerOffset: offset),
+ to: marker
+ )
+ applier.apply(markerDescriptor(image: imageB, anchor: nil, centerOffset: offset), to: marker)
+
+ XCTAssertTrue(marker.icon === iconA)
+ XCTAssertEqual(marker.groundAnchor.y, 0.5, accuracy: 0.0001)
+
+ completions[0](makeIcon(side: 80))
+
+ XCTAssertEqual(marker.groundAnchor.y, 0.75, accuracy: 0.0001)
+ }
+
+ func testFailedLoadShowsThePlaceholderAndTheNextApplyRetries() {
+ var completions: [(UIImage?) -> Void] = []
+ let applier = GoogleMarkerVisualApplier(
+ cachedImage: { _ in nil },
+ loadImage: { _, completion in completions.append(completion) }
+ )
+ let marker = GMSMarker()
+ let descriptor = markerDescriptor(image: remoteImage("a.png"), anchor: nil)
+
+ applier.apply(descriptor, to: marker)
+ completions[0](nil)
+
+ XCTAssertTrue(marker.icon === GoogleMarkerVisualApplier.placeholderIcon)
+
+ applier.apply(descriptor, to: marker)
+
+ XCTAssertEqual(completions.count, 2)
+ }
+
+ func testRemovingTheImageAfterThePlaceholderRestoresTheDefaultPin() {
+ let applier = GoogleMarkerVisualApplier(
+ cachedImage: { _ in nil },
+ loadImage: { _, _ in }
+ )
+ let marker = GMSMarker()
+
+ applier.apply(markerDescriptor(image: remoteImage("a.png"), anchor: nil), to: marker)
+ applier.apply(markerDescriptor(image: nil, anchor: nil), to: marker)
+
+ XCTAssertNil(marker.icon)
+ }
+}
+
+private func remoteImage(_ name: String) -> MarkerImage {
+ MarkerImage(
+ uri: "https://example.test/\(name)",
+ width: 40,
+ height: 40,
+ scale: 1,
+ origin: nil
+ )
}
-private func markerDescriptor(image: MarkerImage, anchor: MarkerAnchor) -> MarkerDescriptor {
+private func markerDescriptor(
+ image: MarkerImage?,
+ anchor: MarkerAnchor?,
+ centerOffset: MarkerPoint? = nil
+) -> MarkerDescriptor {
MarkerDescriptor(
id: "marker",
coordinate: Coordinate(latitude: 0, longitude: 0),
@@ -87,7 +198,7 @@ private func markerDescriptor(image: MarkerImage, anchor: MarkerAnchor) -> Marke
image: image,
markerColor: nil,
anchor: anchor,
- centerOffset: nil,
+ centerOffset: centerOffset,
rotation: nil,
flat: nil,
opacity: nil,
@@ -96,7 +207,7 @@ private func markerDescriptor(image: MarkerImage, anchor: MarkerAnchor) -> Marke
)
}
-private func makeIcon() -> UIImage {
- UIGraphicsImageRenderer(size: CGSize(width: 40, height: 40)).image { _ in }
+private func makeIcon(side: CGFloat = 40) -> UIImage {
+ UIGraphicsImageRenderer(size: CGSize(width: side, height: side)).image { _ in }
}
#endif
diff --git a/package/src/native/specs/overlays.ts b/package/src/native/specs/overlays.ts
index 93015e01..83c65b64 100644
--- a/package/src/native/specs/overlays.ts
+++ b/package/src/native/specs/overlays.ts
@@ -9,8 +9,14 @@ export type MarkerImageOrigin = 'bundled' | 'remote';
export interface MarkerImage {
uri: string;
+ /** Display width in dp. Used only together with `height`; both win over `scale`. */
width?: number;
+ /** Display height in dp. Used only together with `width`; both win over `scale`. */
height?: number;
+ /**
+ * Pixels per dp of the bitmap, e.g. `2` for an `@2x` image. Without `width`/`height`, the
+ * image draws at its pixel size divided by `scale`.
+ */
scale?: number;
/** Absent means user-supplied — the Android remote host policy applies. */