-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathMapMarkerBuilder.kt
More file actions
442 lines (387 loc) · 12.9 KB
/
MapMarkerBuilder.kt
File metadata and controls
442 lines (387 loc) · 12.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
package com.rngooglemapsplus
import MarkerTag
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Canvas
import android.graphics.Typeface
import android.graphics.drawable.PictureDrawable
import android.util.Base64
import android.util.LruCache
import android.widget.ImageView
import android.widget.LinearLayout
import androidx.core.graphics.createBitmap
import com.caverock.androidsvg.SVG
import com.caverock.androidsvg.SVGExternalFileResolver
import com.caverock.androidsvg.SVGParseException
import com.facebook.react.uimanager.PixelUtil.dpToPx
import com.facebook.react.uimanager.ThemedReactContext
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 com.google.android.gms.maps.model.MarkerOptions
import com.rngooglemapsplus.extensions.anchorEquals
import com.rngooglemapsplus.extensions.coordinatesEquals
import com.rngooglemapsplus.extensions.infoWindowAnchorEquals
import com.rngooglemapsplus.extensions.markerInfoWindowStyleEquals
import com.rngooglemapsplus.extensions.markerStyleEquals
import com.rngooglemapsplus.extensions.styleHash
import com.rngooglemapsplus.extensions.toLatLng
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.currentCoroutineContext
import kotlinx.coroutines.ensureActive
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.net.HttpURLConnection
import java.net.URL
import java.net.URLDecoder
import java.util.concurrent.ConcurrentHashMap
import kotlin.coroutines.cancellation.CancellationException
class MapMarkerBuilder(
val context: ThemedReactContext,
private val scope: CoroutineScope = CoroutineScope(SupervisorJob() + Dispatchers.Default),
) {
private val iconCache =
object : LruCache<Int, BitmapDescriptor>(256) {
override fun sizeOf(
key: Int,
value: BitmapDescriptor,
): Int = 1
}
private val jobsById = ConcurrentHashMap<String, Job>()
init {
// / TODO: refactor with androidsvg 1.5 release
SVG.registerExternalFileResolver(
object : SVGExternalFileResolver() {
override fun resolveImage(filename: String?): Bitmap? {
if (filename.isNullOrBlank()) return null
return runCatching {
when {
filename.startsWith("data:image/svg+xml") -> {
val svgContent =
if ("base64," in filename) {
val base64 = filename.substringAfter("base64,")
String(Base64.decode(base64, Base64.DEFAULT), Charsets.UTF_8)
} else {
URLDecoder.decode(filename.substringAfter(","), "UTF-8")
}
val svg = SVG.getFromString(svgContent)
val width = (svg.documentWidth.takeIf { it > 0 } ?: 128f).toInt()
val height = (svg.documentHeight.takeIf { it > 0 } ?: 128f).toInt()
createBitmap(width, height).apply {
density = context.resources.displayMetrics.densityDpi
Canvas(this).also {
svg.renderToCanvas(it)
}
}
}
filename.startsWith("http://") || filename.startsWith("https://") -> {
val conn =
(URL(filename).openConnection() as HttpURLConnection).apply {
connectTimeout = 5000
readTimeout = 5000
requestMethod = "GET"
instanceFollowRedirects = true
}
conn.connect()
val contentType = conn.contentType ?: ""
val result =
if (contentType.contains("svg") || filename.endsWith(".svg")) {
val svgText = conn.inputStream.bufferedReader().use { it.readText() }
val innerSvg = SVG.getFromString(svgText)
val w = innerSvg.documentWidth.takeIf { it > 0 } ?: 128f
val h = innerSvg.documentHeight.takeIf { it > 0 } ?: 128f
createBitmap(w.toInt(), h.toInt()).apply {
density = context.resources.displayMetrics.densityDpi
Canvas(this).also {
innerSvg.renderToCanvas(it)
}
}
} else {
conn.inputStream.use { BitmapFactory.decodeStream(it) }
}
conn.disconnect()
result
}
else -> null
}
}.onFailure {
mapsLog("external svg resolve failed")
}.getOrNull()
}
override fun resolveFont(
fontFamily: String?,
fontWeight: Int,
fontStyle: String?,
): Typeface? {
if (fontFamily.isNullOrBlank()) return null
return runCatching {
val assetManager = context.assets
val candidates =
listOf(
"fonts/$fontFamily.ttf",
"fonts/$fontFamily.otf",
)
for (path in candidates) {
try {
return Typeface.createFromAsset(assetManager, path)
} catch (_: Throwable) {
mapsLog("font resolve failed: $path")
}
}
Typeface.create(fontFamily, Typeface.NORMAL)
}.getOrElse {
Typeface.create(fontFamily, fontWeight)
}
}
override fun isFormatSupported(mimeType: String?): Boolean = mimeType?.startsWith("image/") == true
},
)
}
fun build(
m: RNMarker,
icon: BitmapDescriptor?,
): MarkerOptions =
MarkerOptions().apply {
position(m.coordinate.toLatLng())
icon(icon)
m.title?.let { title(it) }
m.snippet?.let { snippet(it) }
m.opacity?.let { alpha(it.toFloat()) }
m.flat?.let { flat(it) }
m.draggable?.let { draggable(it) }
m.rotation?.let { rotation(it.toFloat()) }
m.infoWindowAnchor?.let { infoWindowAnchor(it.x.toFloat(), it.y.toFloat()) }
m.anchor?.let { anchor((m.anchor.x).toFloat(), (m.anchor.y).toFloat()) }
m.zIndex?.let { zIndex(it.toFloat()) }
}
fun update(
prev: RNMarker,
next: RNMarker,
marker: Marker,
) = onUi {
if (!prev.coordinatesEquals(next)) {
marker.position = next.coordinate.toLatLng()
}
if (!prev.markerStyleEquals(next)) {
buildIconAsync(next) { icon ->
marker.setIcon(icon)
if (!prev.anchorEquals(next)) {
marker.setAnchor(
(next.anchor?.x ?: 0.5f).toFloat(),
(next.anchor?.y ?: 1.0f).toFloat(),
)
}
if (!prev.infoWindowAnchorEquals(next)) {
marker.setInfoWindowAnchor(
(next.infoWindowAnchor?.x ?: 0.5f).toFloat(),
(next.infoWindowAnchor?.y ?: 0f).toFloat(),
)
}
}
} else {
if (!prev.anchorEquals(next)) {
marker.setAnchor(
(next.anchor?.x ?: 0.5f).toFloat(),
(next.anchor?.y ?: 1.0f).toFloat(),
)
}
if (!prev.infoWindowAnchorEquals(next)) {
marker.setInfoWindowAnchor(
(next.infoWindowAnchor?.x ?: 0.5f).toFloat(),
(next.infoWindowAnchor?.y ?: 0f).toFloat(),
)
}
}
if (prev.title != next.title) {
marker.title = next.title
}
if (prev.snippet != next.snippet) {
marker.snippet = next.snippet
}
if (prev.opacity != next.opacity) {
marker.alpha = next.opacity?.toFloat() ?: 1f
}
if (prev.flat != next.flat) {
marker.isFlat = next.flat ?: false
}
if (prev.draggable != next.draggable) {
marker.isDraggable = next.draggable ?: false
}
if (prev.rotation != next.rotation) {
marker.rotation = next.rotation?.toFloat() ?: 0f
}
if (prev.zIndex != next.zIndex) {
marker.zIndex = next.zIndex?.toFloat() ?: 0f
}
if (!prev.markerInfoWindowStyleEquals(next)) {
marker.tag = MarkerTag(id = next.id, iconSvg = next.infoWindowIconSvg)
}
}
fun buildIconAsync(
m: RNMarker,
onReady: (BitmapDescriptor?) -> Unit,
) {
jobsById[m.id]?.cancel()
m.iconSvg ?: return onReady(null)
val key = m.styleHash()
iconCache.get(key)?.let { cached ->
onReady(cached)
return
}
val job =
scope.launch {
try {
ensureActive()
val renderResult = renderBitmap(m.iconSvg, m.id)
if (renderResult?.bitmap == null) {
withContext(Dispatchers.Main) {
ensureActive()
onReady(createFallbackDescriptor())
}
return@launch
}
ensureActive()
val desc = BitmapDescriptorFactory.fromBitmap(renderResult.bitmap)
if (!renderResult.isFallback) {
iconCache.put(key, desc)
}
renderResult.bitmap.recycle()
withContext(Dispatchers.Main) {
ensureActive()
onReady(desc)
}
} catch (_: OutOfMemoryError) {
mapsLog("markerId=${m.id} buildIconAsync out of memory")
clearIconCache()
withContext(Dispatchers.Main) {
ensureActive()
onReady(createFallbackDescriptor())
}
} catch (_: Throwable) {
mapsLog("markerId=${m.id} buildIconAsync failed")
withContext(Dispatchers.Main) {
ensureActive()
onReady(createFallbackDescriptor())
}
} finally {
jobsById.remove(m.id)
}
}
jobsById[m.id] = job
}
fun cancelIconJob(id: String) {
jobsById[id]?.cancel()
jobsById.remove(id)
}
fun cancelAllJobs() {
val ids = jobsById.keys.toList()
ids.forEach { id ->
jobsById[id]?.cancel()
}
jobsById.clear()
clearIconCache()
}
fun clearIconCache() {
iconCache.evictAll()
}
fun buildInfoWindow(markerTag: MarkerTag): ImageView? {
val iconSvg = markerTag.iconSvg ?: return null
val wPx =
markerTag.iconSvg.width
.dpToPx()
.toInt()
val hPx =
markerTag.iconSvg.height
.dpToPx()
.toInt()
if (wPx <= 0 || hPx <= 0) {
mapsLog("markerId=${markerTag.id} invalid svg size")
return ImageView(context)
}
val svgView =
ImageView(context).apply {
layoutParams =
LinearLayout.LayoutParams(
iconSvg.width.dpToPx().toInt(),
iconSvg.height.dpToPx().toInt(),
)
}
try {
val svg =
SVG.getFromString(iconSvg.svgString).apply {
documentWidth = wPx.toFloat()
documentHeight = hPx.toFloat()
}
val drawable = PictureDrawable(svg.renderToPicture())
svgView.setImageDrawable(drawable)
} catch (_: Exception) {
mapsLog("markerId=${markerTag.id} infoWindow: svg render failed")
return ImageView(context)
}
return svgView
}
private fun createFallbackBitmap(): Bitmap =
createBitmap(1, 1, Bitmap.Config.ARGB_8888).apply {
setHasAlpha(true)
}
private fun createFallbackDescriptor(): BitmapDescriptor {
val bmp = createFallbackBitmap()
return BitmapDescriptorFactory.fromBitmap(bmp).also {
bmp.recycle()
}
}
private data class RenderBitmapResult(
val bitmap: Bitmap,
val isFallback: Boolean,
)
private suspend fun renderBitmap(
iconSvg: RNMarkerSvg,
markerId: String,
): RenderBitmapResult? {
val wPx =
iconSvg.width
.dpToPx()
.toInt()
val hPx =
iconSvg.height
.dpToPx()
.toInt()
if (wPx <= 0 || hPx <= 0) {
mapsLog("markerId=$markerId invalid svg size")
return RenderBitmapResult(createFallbackBitmap(), true)
}
var bmp: Bitmap? = null
try {
val svg =
try {
SVG.getFromString(iconSvg.svgString).apply {
documentWidth = wPx.toFloat()
documentHeight = hPx.toFloat()
}
} catch (_: SVGParseException) {
mapsLog("markerId=$markerId icon: svg parse failed")
return RenderBitmapResult(createFallbackBitmap(), true)
} catch (_: IllegalArgumentException) {
mapsLog("markerId=$markerId icon: svg invalid")
return RenderBitmapResult(createFallbackBitmap(), true)
}
currentCoroutineContext().ensureActive()
bmp =
createBitmap(wPx, hPx, Bitmap.Config.ARGB_8888).apply {
density = context.resources.displayMetrics.densityDpi
Canvas(this).also {
svg.renderToCanvas(it)
}
}
currentCoroutineContext().ensureActive()
return RenderBitmapResult(bmp, false)
} catch (e: Exception) {
if (e is CancellationException) throw e
bmp?.recycle()
throw e
}
}
}