diff --git a/.claude/settings.json b/.claude/settings.json new file mode 100644 index 0000000..671a084 --- /dev/null +++ b/.claude/settings.json @@ -0,0 +1,6 @@ +{ + "attribution": { + "commit": "", + "pr": "" + } +} diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 79f872f..f0d3bb0 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -38,8 +38,29 @@ jobs: cache: 'gradle' - name: Build core and compose locally + env: + HEAD_REF: ${{ github.head_ref }} run: | - git clone --depth 1 https://github.com/MapConductor/android-sdk-core.git _core + # コア側に PR と同名のブランチがあるなら、そちらを組む。 + # + # ここを default ブランチ固定にしていると、**コアの未マージな変更に追随する + # PR は永久に赤いまま**になる。実際 CameraBearing をコアへ足したとき、 + # プロバイダ側の PR が 10 本まとめて Unresolved reference で落ちた。 + # コアが先にマージされるまで待つ、という運用は取り込み順の事故を呼ぶので、 + # 同名ブランチがあれば拾う形にしてある(無ければ従来どおり default)。 + clone_matching() { + repo="$1"; dir="$2" + url="https://github.com/MapConductor/$repo.git" + if [ -n "$HEAD_REF" ] && git ls-remote --exit-code --heads "$url" "$HEAD_REF" >/dev/null 2>&1; then + echo "$repo: matching branch $HEAD_REF" + git clone --depth 1 --branch "$HEAD_REF" "$url" "$dir" + else + echo "$repo: default branch" + git clone --depth 1 "$url" "$dir" + fi + } + + clone_matching android-sdk-core _core cd _core ./gradlew --no-daemon publishToMavenLocal cd .. @@ -53,7 +74,7 @@ jobs: } EOF - git clone --depth 1 https://github.com/MapConductor/android-sdk-compose.git _compose + clone_matching android-sdk-compose _compose cd _compose ./gradlew --no-daemon publishToMavenLocal cd .. diff --git a/api/android-for-longdo.api b/api/android-for-longdo.api index 0c5a2f1..c485826 100644 --- a/api/android-for-longdo.api +++ b/api/android-for-longdo.api @@ -27,6 +27,7 @@ public final class com.mapconductor.longdo.LongdoDesign implements com.mapconduc public java.lang.Object getValue(); } public final class com.mapconductor.longdo.LongdoDesign$Companion { + public final com.mapconductor.longdo.LongdoDesign getNone(); public final com.mapconductor.longdo.LongdoDesign getNormal(); public final com.mapconductor.longdo.LongdoDesign getEasy(); public final com.mapconductor.longdo.LongdoDesign getPastel(); @@ -105,6 +106,8 @@ public final class com.mapconductor.longdo.LongdoMapViewController extends com.m public void setOnMarkerClickListener(kotlin.jvm.functions.Function1); public java.lang.Object compositionRasterLayers(java.util.List, kotlin.coroutines.Continuation); public java.lang.Object updateRasterLayer(com.mapconductor.core.raster.RasterLayerState, kotlin.coroutines.Continuation); + public void mountRasterLayer(com.mapconductor.core.raster.RasterLayerState); + public void unmountRasterLayer(java.lang.String); public boolean hasRasterLayer(com.mapconductor.core.raster.RasterLayerState); public boolean hasPolyline(com.mapconductor.core.polyline.PolylineState); public void setOnPolylineClickListener(kotlin.jvm.functions.Function1); @@ -120,7 +123,9 @@ public final class com.mapconductor.longdo.LongdoMapViewController extends com.m public final class com.mapconductor.longdo.LongdoMapViewController$Companion { } public final class com.mapconductor.longdo.LongdoMapViewControllerCameraKt { + public static final double LONGDO_VERTICAL_FOV; public static final boolean applyCameraRestrictionCorrectionIfNeeded(com.mapconductor.longdo.LongdoMapViewController, com.mapconductor.core.map.MapCameraPosition); + public static final double viewportHeightDp(com.mapconductor.longdo.LongdoMapViewController); public static final void handleMoveCamera(com.mapconductor.longdo.LongdoMapViewController, com.mapconductor.core.map.MapCameraPosition); public static final void handleAnimateCamera(com.mapconductor.longdo.LongdoMapViewController, com.mapconductor.core.map.MapCameraPosition, long); public static final void applyCamera(com.mapconductor.longdo.LongdoMapViewController, com.mapconductor.core.map.MapCameraPosition); @@ -140,7 +145,7 @@ public final class com.mapconductor.longdo.LongdoMapViewControllerMarkerTilesKt public static final void renderTiledMarkers(com.mapconductor.longdo.LongdoMapViewController, java.util.List); public static final void applyMarkerTileRaster(com.mapconductor.longdo.LongdoMapViewController, com.mapconductor.core.raster.RasterLayerState); public static final void removeMarkerTileRaster(com.mapconductor.longdo.LongdoMapViewController); - public static final boolean handleMarkerTap(com.mapconductor.longdo.LongdoMapViewController, com.mapconductor.core.features.GeoPoint, double); + public static final boolean handleMarkerTap(com.mapconductor.longdo.LongdoMapViewController, com.mapconductor.core.features.GeoPoint); } public final class com.mapconductor.longdo.LongdoMapViewControllerRasterKt { public static final void applyRaster(com.mapconductor.longdo.LongdoMapViewController, com.mapconductor.core.raster.RasterLayerState); @@ -148,6 +153,8 @@ public final class com.mapconductor.longdo.LongdoMapViewControllerRasterKt { public static final java.lang.String rasterSourceSpec(com.mapconductor.longdo.LongdoMapViewController, com.mapconductor.core.raster.RasterLayerSource); public static final java.lang.String rasterLayerSpec(com.mapconductor.longdo.LongdoMapViewController, java.lang.String, java.lang.String, float, boolean); public static final java.lang.String addRasterJs(com.mapconductor.longdo.LongdoMapViewController, java.lang.String, java.lang.String, java.lang.String, java.lang.String); + public static final java.lang.String addRasterJs(com.mapconductor.longdo.LongdoMapViewController, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String); + public static final java.lang.String readdRastersAfterStyleSwapJs(com.mapconductor.longdo.LongdoMapViewController, java.util.List); public static final java.lang.String removeRasterJs(com.mapconductor.longdo.LongdoMapViewController, java.lang.String); public static final java.lang.String setRasterOpacityJs(com.mapconductor.longdo.LongdoMapViewController, java.lang.String, float); public static final java.lang.String setRasterVisibilityJs(com.mapconductor.longdo.LongdoMapViewController, java.lang.String, boolean); @@ -164,12 +171,15 @@ public final class com.mapconductor.longdo.LongdoMapViewHolder implements com.ma public androidx.compose.ui.geometry.Offset toScreenOffset-x-9fifI(com.mapconductor.core.features.GeoPointInterface); public com.mapconductor.core.features.GeoPoint fromScreenOffsetSync-k-4lQ0M(long); public java.lang.Object fromScreenOffset-3MmeM6k(long, kotlin.coroutines.Continuation); + public com.mapconductor.core.projection.ProjectedPoint toProjectedPoint(com.mapconductor.core.features.GeoPointInterface); + public com.mapconductor.core.features.GeoPoint fromProjectedPoint(com.mapconductor.core.projection.ProjectedPoint); + public com.mapconductor.core.projection.MapCoordinateSystem getCoordinateSystem(); public java.lang.Object getMapView(); public java.lang.Object getMap(); } public final class com.mapconductor.longdo.LongdoMapViewKt { - public static final void LongdoMapView(com.mapconductor.longdo.LongdoViewState, androidx.compose.ui.Modifier, com.mapconductor.core.marker.MarkerTilingOptions, com.mapconductor.core.map.CameraRestriction, kotlin.jvm.functions.Function1, kotlin.Unit>, kotlin.jvm.functions.Function1, kotlin.jvm.functions.Function1, kotlin.jvm.functions.Function1, kotlin.jvm.functions.Function1, kotlin.jvm.functions.Function1, kotlin.jvm.functions.Function3, androidx.compose.runtime.Composer, int, int, int); - public static final void LongdoMapSurface(com.mapconductor.longdo.LongdoViewState, androidx.compose.ui.Modifier, com.mapconductor.core.marker.MarkerTilingOptions, com.mapconductor.core.map.CameraRestriction, kotlin.jvm.functions.Function1, kotlin.Unit>, kotlin.jvm.functions.Function1, kotlin.jvm.functions.Function1, kotlin.jvm.functions.Function1, kotlin.jvm.functions.Function1, kotlin.jvm.functions.Function1, kotlin.jvm.functions.Function1, kotlin.jvm.functions.Function3, androidx.compose.runtime.Composer, int, int, int); + public static final void LongdoMapView(com.mapconductor.longdo.LongdoViewState, androidx.compose.ui.Modifier, com.mapconductor.core.marker.MarkerTilingOptions, com.mapconductor.core.map.CameraRestriction, kotlin.jvm.functions.Function1, kotlin.Unit>, kotlin.jvm.functions.Function1, kotlin.jvm.functions.Function1, kotlin.jvm.functions.Function1, kotlin.jvm.functions.Function1, kotlin.jvm.functions.Function1, com.mapconductor.core.map.MapViewStyle, kotlin.jvm.functions.Function1, kotlin.Unit>, kotlin.jvm.functions.Function3, androidx.compose.runtime.Composer, int, int, int); + public static final void LongdoMapSurface(com.mapconductor.longdo.LongdoViewState, androidx.compose.ui.Modifier, com.mapconductor.core.marker.MarkerTilingOptions, com.mapconductor.core.map.CameraRestriction, kotlin.jvm.functions.Function1, kotlin.Unit>, kotlin.jvm.functions.Function1, kotlin.jvm.functions.Function1, kotlin.jvm.functions.Function1, kotlin.jvm.functions.Function1, kotlin.jvm.functions.Function1, kotlin.jvm.functions.Function1, com.mapconductor.core.map.MapViewStyle, kotlin.jvm.functions.Function1, kotlin.Unit>, kotlin.jvm.functions.Function3, androidx.compose.runtime.Composer, int, int, int); } public final class com.mapconductor.longdo.LongdoMapViewSaver extends com.mapconductor.compose.map.BaseMapViewSaver { public static final java.lang.String KEY_DESIGN_ID; @@ -186,6 +196,14 @@ final class com.mapconductor.longdo.LongdoMapViewSaver$Companion { public final class com.mapconductor.longdo.LongdoMapViewScope extends com.mapconductor.compose.MapViewScope { public com.mapconductor.longdo.LongdoMapViewScope(); } +public final class com.mapconductor.longdo.LongdoOverlayStacking { + public static final com.mapconductor.longdo.LongdoOverlayStacking INSTANCE; + public final java.lang.String addLayerJs(java.lang.String, com.mapconductor.core.controller.OverlayKind, int); + public final java.lang.String addPolygonTileLayerJs(java.lang.String); + public final java.lang.String addCircleTileLayerJs(java.lang.String); + public final java.lang.String addPolylineTileLayerJs(java.lang.String); + public final java.lang.String addMarkerTileLayerJs(java.lang.String); +} public final class com.mapconductor.longdo.LongdoOverlayState { public com.mapconductor.longdo.LongdoOverlayState(); public final androidx.compose.runtime.snapshots.SnapshotStateMap getRenderPx(); @@ -223,6 +241,18 @@ public final class com.mapconductor.longdo.NativeCamera { public int hashCode(); public boolean equals(java.lang.Object); } +public final class com.mapconductor.longdo.PageLayerWait { + public static final com.mapconductor.longdo.PageLayerWait INSTANCE; + public static final java.lang.String MAP_EXPR; + public static final long TIMEOUT_MS; + public static final long INTERVAL_MS; + public final java.lang.String script(java.util.List); + public final int parse(java.lang.String); + public final java.lang.Object await(java.util.List, long, long, kotlin.jvm.functions.Function2, ? extends java.lang.Object>, kotlin.coroutines.Continuation); +} +public final class com.mapconductor.longdo.PageLayerWaitKt { + public static final java.lang.Object awaitPageLayers(com.longdo.sdk3.LongdoMap, java.util.List, kotlin.coroutines.Continuation); +} public final class com.mapconductor.longdo.circle.LongdoCircleController extends com.mapconductor.core.circle.CircleController { public com.mapconductor.longdo.circle.LongdoCircleController(com.mapconductor.longdo.circle.LongdoCircleOverlayRenderer, com.mapconductor.core.circle.CircleManagerInterface); public com.mapconductor.longdo.circle.LongdoCircleController(com.mapconductor.longdo.circle.LongdoCircleOverlayRenderer, com.mapconductor.core.circle.CircleManagerInterface, int, kotlin.jvm.internal.DefaultConstructorMarker); @@ -327,6 +357,7 @@ public final class com.mapconductor.longdo.marker.LongdoClusterMarkerRenderer im public java.lang.Object onPostProcess(kotlin.coroutines.Continuation); public void onDragSelectionChanged(com.mapconductor.core.marker.MarkerEntityInterface, com.mapconductor.core.marker.MarkerEntityInterface); public void onDragPositionChanged(com.mapconductor.core.features.GeoPointInterface); + public java.lang.Object onDrawOrderFrameChanged(com.mapconductor.core.marker.MarkerDrawOrder$Frame, java.util.List>, kotlin.coroutines.Continuation); } public final class com.mapconductor.longdo.marker.LongdoMarkerTileRenderer { public static final double TILE_SIZE; @@ -338,10 +369,15 @@ public final class com.mapconductor.longdo.marker.LongdoMarkerTileRenderer { public final com.mapconductor.core.raster.RasterLayerState render(java.util.List); public final java.lang.String getRasterLayerId(); public final void clear(); + public final com.mapconductor.core.marker.MarkerState findMarkerAt(com.mapconductor.core.features.GeoPointInterface, kotlin.jvm.functions.Function1); public final com.mapconductor.core.marker.MarkerState findMarkerAt(com.mapconductor.core.features.GeoPointInterface, double); } final class com.mapconductor.longdo.marker.LongdoMarkerTileRenderer$Companion { } +public final class com.mapconductor.longdo.marker.MarkerIdIndex { + public com.mapconductor.longdo.marker.MarkerIdIndex(); + public final synchronized boolean contains(java.util.List, java.lang.String); +} public final class com.mapconductor.longdo.polygon.LongdoPolygonController extends com.mapconductor.core.polygon.PolygonController { public com.mapconductor.longdo.polygon.LongdoPolygonController(com.mapconductor.longdo.polygon.LongdoPolygonOverlayRenderer, com.mapconductor.core.polygon.PolygonManagerInterface); public com.mapconductor.longdo.polygon.LongdoPolygonController(com.mapconductor.longdo.polygon.LongdoPolygonOverlayRenderer, com.mapconductor.core.polygon.PolygonManagerInterface, int, kotlin.jvm.internal.DefaultConstructorMarker); diff --git a/build.gradle.kts b/build.gradle.kts index 2e689d6..be28c68 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -89,6 +89,11 @@ dependencies { } else { api("com.mapconductor:compose:$libraryVersion") } + + testImplementation(libs.junit) + // Saver の保存 → 復元を実機の Bundle / Parcel で確かめる(SaverRoundTripTest)。 + androidTestImplementation(libs.androidx.junit) + androidTestImplementation(libs.androidx.espresso.core) } // Set project version for NMCP plugin diff --git a/gradle.properties b/gradle.properties index 26d9949..8b1a332 100644 --- a/gradle.properties +++ b/gradle.properties @@ -3,10 +3,10 @@ android.useAndroidX=true kotlin.code.style=official android.nonTransitiveRClass=true -compileSdk=35 +compileSdk=37 minSdk=26 javaVersion=17 jvmTarget=17 -libraryVersion=1.3.1 +libraryVersion=1.4.0 android.generateSyncIssueWhenLibraryConstraintsAreEnabled=false diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index 25b5251..02511dc 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -1,12 +1,15 @@ [versions] -composeLibs = "1.7.8" -agp = "9.2.1" -kotlin = "2.0.21" +composeLibs = "1.12.1" +# material3 は compose-ui とは別のバージョン系列。composeLibs(ui 系)を流用すると +# 存在しない material3:1.7.8 を要求してクラスパスごと解決に失敗する。 +material3 = "1.4.0" +agp = "9.4.1" +kotlin = "2.4.20" -composeBom = "2025.02.00" -lifecycleRuntimeKtx = "2.8.7" +composeBom = "2026.09.00" +lifecycleRuntimeKtx = "2.11.0" longdoSdk = "1.3.0" -activityCompose = "1.9.3" +activityCompose = "1.13.0" ktLint = "14.2.0" junit = "4.13.2" junitVersion = "1.3.0" @@ -28,7 +31,7 @@ longdo-sdk = { module = "com.longdo.map:sdk3", version.ref = "longdoSdk" } # Sample app androidx-activity-compose = { group = "androidx.activity", name = "activity-compose", version.ref = "activityCompose" } -androidx-material3 = { group = "androidx.compose.material3", name = "material3", version.ref = "composeLibs" } +androidx-material3 = { group = "androidx.compose.material3", name = "material3", version.ref = "material3" } androidx-ui-tooling = { group = "androidx.compose.ui", name = "ui-tooling", version.ref = "composeLibs" } # Test diff --git a/src/androidTest/java/com/mapconductor/longdo/LongdoMapViewSaverTest.kt b/src/androidTest/java/com/mapconductor/longdo/LongdoMapViewSaverTest.kt new file mode 100644 index 0000000..eb6b41f --- /dev/null +++ b/src/androidTest/java/com/mapconductor/longdo/LongdoMapViewSaverTest.kt @@ -0,0 +1,97 @@ +package com.mapconductor.longdo + +import androidx.compose.runtime.saveable.Saver +import androidx.compose.runtime.saveable.SaverScope +import androidx.test.ext.junit.runners.AndroidJUnit4 +import com.mapconductor.core.features.GeoPoint +import com.mapconductor.core.map.AttributionRule +import com.mapconductor.core.map.MapCameraPosition +import com.mapconductor.core.map.MapUISettings +import org.junit.Assert.assertEquals +import org.junit.Test +import org.junit.runner.RunWith +import android.os.Bundle +import android.os.Parcel + +/** + * 回転などの構成変更で state が [LongdoMapViewSaver] を通って作り直されても、デザイン(id・ + * attributionRules ほか)と uiSettings・カメラが落ちないこと。Bundle は実機の Parcel を一度通す。 + */ +@RunWith(AndroidJUnit4::class) +class LongdoMapViewSaverTest { + private val rules = + listOf(AttributionRule("© test"), AttributionRule("© ranged", minZoom = 3, maxZoom = 15)) + + private val camera = + MapCameraPosition( + position = GeoPoint(21.38, -157.93), + zoom = 12.0, + bearing = 20.0, + tilt = 10.0, + ) + + @Test + fun keepsDesignOutsideThePresets() { + // 以前は id だけを保存して fromId で戻しており、定義に無い id は Normal になっていた。 + val design = LongdoDesign(id = "my-gray", layerName = "GRAY") + val state = LongdoViewState(mapDesignType = design, id = "longdo-1", initialCameraPosition = camera) + state.uiSettings = MapUISettings(rotateGesture = false, tiltGesture = false) + + val restored = roundTrip(LongdoMapViewSaver().createSaver(), state) + + assertEquals(design, restored.mapDesignType) + assertCommon(restored, "longdo-1") + } + + @Test + fun keepsAttributionRulesOfAnAppDesign() { + val design = + object : LongdoMapDesignTypeInterface { + override val id: String = "app-design" + override val layerName: String = "POLITICAL" + override val attributionRules: List = rules + + override fun getValue(): String = id + } + val restored = roundTrip(LongdoMapViewSaver().createSaver(), LongdoViewState(design, "longdo-2")) + + assertEquals("app-design", restored.mapDesignType.id) + assertEquals("POLITICAL", restored.mapDesignType.layerName) + assertEquals(rules, restored.mapDesignType.attributionRules) + } + + @Test + fun keepsPresetDesign() { + val restored = roundTrip(LongdoMapViewSaver().createSaver(), LongdoViewState(LongdoDesign.Pastel, "longdo-3")) + assertEquals(LongdoDesign.Pastel, restored.mapDesignType) + } + + private fun assertCommon( + restored: com.mapconductor.core.map.MapViewStateInterface<*>, + id: String, + ) { + assertEquals(id, restored.id) + assertEquals(false, restored.uiSettings.rotateGesture) + assertEquals(false, restored.uiSettings.tiltGesture) + assertEquals(true, restored.uiSettings.scrollGesture) + assertEquals(12.0, restored.cameraPosition.zoom, 1e-9) + assertEquals(20.0, restored.cameraPosition.bearing, 1e-9) + assertEquals(21.38, restored.cameraPosition.position.latitude, 1e-9) + } + + private fun roundTrip( + saver: Saver, + value: T, + ): T { + val saved = with(saver) { SaverScope { true }.save(value) }!! + // 一度 Parcel に書いて読み戻す(プロセスが落ちたあとの復元と同じ経路)。 + val parcel = Parcel.obtain() + try { + parcel.writeBundle(saved) + parcel.setDataPosition(0) + return saver.restore(parcel.readBundle(javaClass.classLoader)!!)!! + } finally { + parcel.recycle() + } + } +} diff --git a/src/main/java/com/mapconductor/longdo/LongdoAnnotations.kt b/src/main/java/com/mapconductor/longdo/LongdoAnnotations.kt index 0a0c17b..af2cef5 100644 --- a/src/main/java/com/mapconductor/longdo/LongdoAnnotations.kt +++ b/src/main/java/com/mapconductor/longdo/LongdoAnnotations.kt @@ -30,6 +30,7 @@ import androidx.compose.ui.unit.IntSize import androidx.compose.ui.unit.dp import com.mapconductor.compose.info.InfoBubbleEntry import com.mapconductor.core.marker.DefaultMarkerIcon +import com.mapconductor.core.marker.iconRevision import com.mapconductor.core.marker.MarkerAnimation import com.mapconductor.core.marker.MarkerState import com.mapconductor.settings.Settings @@ -67,7 +68,10 @@ internal fun LongdoMarkerOverlay( onDragMove: (marker: MarkerState, devicePx: Offset) -> Unit = { _, _ -> }, ) { val density = LocalDensity.current.density - val bitmapIcon = remember(marker.icon) { (marker.icon ?: DefaultMarkerIcon()).toBitmapIcon() } + // URL の画像が届くと、アイコンは同じインスタンスのまま見た目だけ変わる。iconRevision が + // そのとき増えるので、それもキーにする(読むことで描き直しも起きる)。 + val bitmapIcon = + remember(marker.icon, marker.iconRevision) { (marker.icon ?: DefaultMarkerIcon()).toBitmapIcon() } val widthPx = bitmapIcon.size.width val heightPx = bitmapIcon.size.height val anchor = bitmapIcon.anchor diff --git a/src/main/java/com/mapconductor/longdo/LongdoDesign.kt b/src/main/java/com/mapconductor/longdo/LongdoDesign.kt index eae84db..632fb37 100644 --- a/src/main/java/com/mapconductor/longdo/LongdoDesign.kt +++ b/src/main/java/com/mapconductor/longdo/LongdoDesign.kt @@ -30,6 +30,9 @@ data class LongdoDesign( // 以下は Longdo Map API3(`longdo.Layers`)が標準提供するベースレイヤ。 // レイヤ名は SDK の `longdo.Layers` に実在するものを用いる(実行時列挙で検証済み)。 + /** ベースマップ無し。`longdo.Layers.CLEAR`(何も載っていないベースレイヤ)。 */ + val None = LongdoDesign("None", "CLEAR") + /** 標準地図。 */ val Normal = LongdoDesign("Normal", "NORMAL") @@ -72,7 +75,7 @@ data class LongdoDesign( /** SDK が標準提供する全デザイン([MapDesignMapPage] のセレクタで用いる)。 */ val all: List = listOf( - Normal, Easy, Pastel, PastelGray, Hard, Gray, + None, Normal, Easy, Pastel, PastelGray, Hard, Gray, Light, Night, Dark, Political, Osm, Satellite, Hybrid, ) diff --git a/src/main/java/com/mapconductor/longdo/LongdoMapView.kt b/src/main/java/com/mapconductor/longdo/LongdoMapView.kt index 3288ca6..5703d71 100644 --- a/src/main/java/com/mapconductor/longdo/LongdoMapView.kt +++ b/src/main/java/com/mapconductor/longdo/LongdoMapView.kt @@ -38,6 +38,8 @@ import com.mapconductor.core.ResourceProvider import com.mapconductor.core.circle.CircleCapableInterface import com.mapconductor.core.features.GeoPoint import com.mapconductor.core.groundimage.GroundImageCapableInterface +import com.mapconductor.core.map.CameraBearing +import com.mapconductor.core.map.CameraPaddingEmulation import com.mapconductor.core.map.LocalMapOverlayRegistry import com.mapconductor.core.map.LocalMapServiceRegistry import com.mapconductor.core.map.LocalMapViewController @@ -45,10 +47,14 @@ import com.mapconductor.core.map.MapCameraPosition import com.mapconductor.core.map.MapCapability import com.mapconductor.core.map.MapCapabilityStatus import com.mapconductor.core.map.MapServiceRegistrations +import com.mapconductor.core.map.MapViewStyle +import com.mapconductor.core.map.MapViewStyleEffect import com.mapconductor.core.map.VisibleRegion import com.mapconductor.core.marker.MarkerCapableInterface +import com.mapconductor.core.marker.MarkerDrawOrder import com.mapconductor.core.marker.MarkerRenderingSupportKey import com.mapconductor.core.marker.MarkerState +import com.mapconductor.core.marker.rememberMarkerDrawOrderFrame import com.mapconductor.core.polygon.PolygonCapableInterface import com.mapconductor.core.polyline.PolylineCapableInterface import com.mapconductor.core.raster.RasterLayerCapableInterface @@ -87,6 +93,15 @@ fun LongdoMapView( onCameraMoveStart: OnCameraMoveHandler? = null, onCameraMove: OnCameraMoveHandler? = null, onCameraMoveEnd: OnCameraMoveHandler? = null, + /** + * How the map looks, when the app states it rather than naming a design. + * + * A vector style *is* the basemap. `com.mapconductor:vectorstyle` builds + * one; what happens underneath depends on this backend and the app does + * not have to know. + */ + style: MapViewStyle? = null, + onStyleDiagnostics: ((List) -> Unit)? = null, content: (@Composable MapViewScope.() -> Unit)? = null, ) { LongdoMapSurface( @@ -100,6 +115,8 @@ fun LongdoMapView( onCameraMoveStart = onCameraMoveStart, onCameraMove = onCameraMove, onCameraMoveEnd = onCameraMoveEnd, + style = style, + onStyleDiagnostics = onStyleDiagnostics, content = content, ) } @@ -131,6 +148,15 @@ fun LongdoMapSurface( onCameraMove: OnCameraMoveHandler? = null, onCameraMoveEnd: OnCameraMoveHandler? = null, onControllerReady: ((LongdoMapViewController) -> Unit)? = null, + /** + * How the map looks, when the app states it rather than naming a design. + * + * A vector style *is* the basemap. `com.mapconductor:vectorstyle` builds + * one; what happens underneath depends on this backend and the app does + * not have to know. + */ + style: MapViewStyle? = null, + onStyleDiagnostics: ((List) -> Unit)? = null, content: (@Composable MapViewScope.() -> Unit)? = null, ) { val context = LocalContext.current @@ -205,6 +231,16 @@ fun LongdoMapSurface( onDispose { registrations.disposeAll() } } + // 同じ理由で、スタイルの設置もここで呼ぶ(MapViewBase を通るプロバイダは + // あちらで 1 回呼んでいる)。何が起きるかはバックエンドが宣言した能力で + // 決まるので、このプロバイダ固有の分岐は無い。 + MapViewStyleEffect( + state = state, + style = style, + controller = controller, + onDiagnostics = onStyleDiagnostics, + ) + // タイル経路に倒すかはコントローラが件数を見て決める(他プロバイダと同じ規則)。 // ここで null を Default へ正規化するのも maplibre / googlemaps / here と揃えてある。 controller.markerTilingOptions = @@ -290,29 +326,33 @@ fun LongdoMapSurface( pushTargets() onLoaded?.invoke(currentState) } - bridge.onMapClick = { point, zoom -> + bridge.onMapClick = { point, _ -> // marker → circle → groundImage → polyline → polygon → map のカスケード。 // **必ずどれか 1 つだけ**が配送される(他プロバイダと同じ)。 // 順序と先勝ちはコアの dispatchOverlayTap が持つ。マーカーだけは Longdo の // タイルレンダラでヒットテストするのでここで先に見る。 - if (!controller.handleMarkerTap(point, zoom) && !controller.dispatchOverlayTap(point)) { + if (!controller.handleMarkerTap(point) && !controller.dispatchOverlayTap(point)) { onClick?.invoke(point) } } bridge.onCameraMove = cameraMove@{ lon, lat, zoom, bearing, tilt, bounds -> - val base = currentState.cameraPosition val region = bounds?.let { VisibleRegion(bounds = it, nearLeft = null, nearRight = null, farLeft = null, farRight = null) } + // Longdo が返す中心は画面中央。パディングを付けているなら、その中央の位置に直す。 val updated = - MapCameraPosition( - position = GeoPoint(latitude = lat, longitude = lon), - zoom = LongdoMapViewController.longdoZoomToCore(zoom), - bearing = bearing, - tilt = tilt, - paddings = base.paddings, - visibleRegion = region, + CameraPaddingEmulation.fromNativeCamera( + MapCameraPosition( + position = GeoPoint(latitude = lat, longitude = lon), + zoom = LongdoMapViewController.longdoZoomToCore(zoom), + bearing = CameraBearing.bearingFromNativeHeading(bearing), + tilt = tilt, + visibleRegion = region, + ), + controller.cameraPaddings, + LONGDO_VERTICAL_FOV, + controller.viewportHeightDp(), ) // 範囲・ズーム制限に違反していれば矩形内へ引き戻す(Longdo にはネイティブの範囲制限 API が // 無いため)。android-sdk の HERE/ArcGIS/TomTom と同じく、補正した回は state 更新も @@ -378,8 +418,12 @@ fun LongdoMapSurface( ) } + // 地図が回って止まったら、同じ zIndex の前後を画面の上下で並べ直す。 + val drawOrderFrame = rememberMarkerDrawOrderFrame { currentState.cameraPosition } if (mapReady) { - markers.forEach { markerState -> + // 後に置いたものほど上に描かれる。zIndex が大きいほど、同じなら画面で下ほど上 + // ([MarkerDrawOrder])。足した順には任せない。 + markers.sortedBy { MarkerDrawOrder.of(it.zIndex, it.position, drawOrderFrame) }.forEach { markerState -> key(markerState.id) { LongdoMarkerOverlay( marker = markerState, @@ -497,6 +541,17 @@ fun LongdoMapSurface( onDispose { moveDispatcher.cancel() controller.destroy() + // No MapViewBase here to do it: the state (which the app keeps) must + // not hold on to the destroyed controller and its overlays. + state.detachController(controller) + // The WebView is the map. Not destroyed, it keeps its renderer and + // the JS bridge, and through them the controller with every overlay. + // This runs for a configuration change too: the old Activity's + // WebView is never shown again (the state is what survives). + (longdoMap.parent as? ViewGroup)?.removeView(longdoMap) + longdoMap.removeJavascriptInterface(BRIDGE_NAME) + longdoMap.stopLoading() + longdoMap.destroy() } } } diff --git a/src/main/java/com/mapconductor/longdo/LongdoMapViewController.kt b/src/main/java/com/mapconductor/longdo/LongdoMapViewController.kt index 63999ba..c3c126f 100644 --- a/src/main/java/com/mapconductor/longdo/LongdoMapViewController.kt +++ b/src/main/java/com/mapconductor/longdo/LongdoMapViewController.kt @@ -1,6 +1,9 @@ package com.mapconductor.longdo import com.longdo.sdk3.LongdoMap +import com.mapconductor.core.circle.CIRCLE_TILE_LAYER_ID +import com.mapconductor.core.circle.CircleTiler +import com.mapconductor.core.circle.circleTileRasterLayerState import com.mapconductor.core.circle.CircleCapableInterface import com.mapconductor.core.circle.OnCircleEventHandler import com.mapconductor.core.controller.BaseMapViewController @@ -8,7 +11,10 @@ import com.mapconductor.core.features.GeoRectBounds import com.mapconductor.core.groundimage.GroundImageCapableInterface import com.mapconductor.core.groundimage.GroundImageState import com.mapconductor.core.groundimage.OnGroundImageEventHandler +import com.mapconductor.core.map.CameraPaddingEmulation import com.mapconductor.core.map.MapCameraPosition +import com.mapconductor.core.map.MapPaddings +import com.mapconductor.core.map.MapPaddingsInterface import com.mapconductor.core.map.MapUISettings import com.mapconductor.core.marker.MarkerCapableInterface import com.mapconductor.core.marker.MarkerRenderingSupport @@ -17,10 +23,16 @@ import com.mapconductor.core.marker.MarkerTilingOptions import com.mapconductor.core.marker.OnMarkerEventHandler import com.mapconductor.core.marker.StrategyMarkerController import com.mapconductor.core.polygon.OnPolygonEventHandler +import com.mapconductor.core.polygon.POLYGON_TILE_LAYER_ID import com.mapconductor.core.polygon.PolygonCapableInterface +import com.mapconductor.core.polygon.PolygonTiler +import com.mapconductor.core.polygon.polygonTileRasterLayerState import com.mapconductor.core.polyline.OnPolylineEventHandler +import com.mapconductor.core.polyline.POLYLINE_TILE_LAYER_ID import com.mapconductor.core.polyline.PolylineCapableInterface import com.mapconductor.core.polyline.PolylineState +import com.mapconductor.core.polyline.PolylineTiler +import com.mapconductor.core.polyline.polylineTileRasterLayerState import com.mapconductor.core.raster.RasterLayerCapableInterface import com.mapconductor.core.raster.RasterLayerState import com.mapconductor.longdo.circle.LongdoCircleController @@ -28,6 +40,7 @@ import com.mapconductor.longdo.circle.LongdoCircleOverlayRenderer import com.mapconductor.longdo.groundimage.LongdoGroundImageController import com.mapconductor.longdo.groundimage.LongdoGroundImageOverlayRenderer import com.mapconductor.longdo.marker.LongdoMarkerTileRenderer +import com.mapconductor.longdo.marker.MarkerIdIndex import com.mapconductor.longdo.polygon.LongdoPolygonController import com.mapconductor.longdo.polygon.LongdoPolygonOverlayRenderer import com.mapconductor.longdo.polyline.LongdoPolylineController @@ -38,7 +51,9 @@ import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.first import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext /** * MapConductor コアと Longdo Map API3 SDK([LongdoMap])を橋渡しするマップコントローラ。 @@ -104,6 +119,49 @@ class LongdoMapViewController( registerOverlayController(polygonController) registerOverlayController(groundImageController) registerOverlayController(circleController) + // Many polygons are drawn as raster tiles. Longdo has no RasterLayer + // controller, so they are mounted like the marker tiles: outside the + // app's RasterLayer composition, which therefore never removes them. + polygonController.tiler = + PolygonTiler().apply { + onTemplate = { template, tileSize -> + if (template != null) { + // Returns once the tile layer is on the page's map: the tiled + // polygons' onAdded is called on the return. + mountRasterLayerOnMap(polygonTileRasterLayerState(template, tileSize)) + } else { + unmountRasterLayer(POLYGON_TILE_LAYER_ID) + } + } + } + + // Many circles too: the same raster layer path, in the circle band. + circleController.tiler = + CircleTiler().apply { + onTemplate = { template, tileSize -> + if (template != null) { + // Returns once the tile layer is on the page's map: the tiled + // circles' onAdded is called on the return. + mountRasterLayerOnMap(circleTileRasterLayerState(template, tileSize)) + } else { + unmountRasterLayer(CIRCLE_TILE_LAYER_ID) + } + } + } + + // Many polylines too: the same raster layer path, in the polyline band. + polylineController.tiler = + PolylineTiler().apply { + onTemplate = { template, tileSize -> + if (template != null) { + // Returns once the tile layer is on the page's map: the tiled + // polylines' onAdded is called on the return. + mountRasterLayerOnMap(polylineTileRasterLayerState(template, tileSize)) + } else { + unmountRasterLayer(POLYLINE_TILE_LAYER_ID) + } + } + } // ホルダーの投影にカメラを供給する。ホルダーはコントローラより先に作られるので // ここで繋ぐ。これが無いと toScreenOffset が常に null を返し、InfoBubble と // マーカー追従が理由も出ずに落ちる。 @@ -190,6 +248,14 @@ class LongdoMapViewController( @Volatile internal var mapReady: Boolean = false + /** + * 今カメラに付いているパディング(dp)。 + * + * Longdo Map API3 にはパディングの口が無いので、カメラ中心をずらして再現し + * ([CameraPaddingEmulation])、読むときに元へ戻すためにここで覚えておく。 + */ + internal var cameraPaddings: MapPaddingsInterface = MapPaddings.Zeros + /** ready 前に要求された最後のカメラ位置。ready 時に適用する。 */ internal var pendingCameraPosition: MapCameraPosition? = null @@ -229,6 +295,11 @@ class LongdoMapViewController( dispatchCameraToOverlays() // Gesture JS issued before ready is dropped by the page; re-apply now. applyUISettings(appliedUISettings) + if (pendingMountedRasters.isNotEmpty()) { + val waiting = pendingMountedRasters.values.toList() + pendingMountedRasters.clear() + mainCoroutine.launch { waiting.forEach { applyRaster(it) } } + } } override fun setMapDesignType(value: LongdoMapDesignTypeInterface) { @@ -239,6 +310,10 @@ class LongdoMapViewController( listOf(LongdoMap.LongdoStatic("Layers", value.layerName)), ) {} } + // ベース切替は内部 MapLibre のスタイル差し替えで、こちらが `map.Renderer` へ足した + // ソース/レイヤはそこで消える。新しいスタイルが載ったら載せ直す。 + val rasters = appliedRasters.values.toList() + listOfNotNull(markerTileState) + if (rasters.isNotEmpty()) runRasterJs(readdRastersAfterStyleSwapJs(rasters)) } // --- MarkerCapableInterface --- @@ -246,6 +321,8 @@ class LongdoMapViewController( override suspend fun compositionMarkers(data: List) { if (shouldUseMarkerLayer(data.size)) { renderTiledMarkers(data) + // The tiled markers' onAdded waits for their tile layer (see [PageLayerWait]). + markerTileState?.let { longdoMap.awaitPageLayers(listOf(rasterLayerId(it.id))) } } else { _markers.value = data } @@ -260,12 +337,17 @@ class LongdoMapViewController( } } - override fun hasMarker(state: MarkerState): Boolean = - if (markerTileRenderer?.markers?.isNotEmpty() == true) { - markerTileRenderer?.markers?.any { it.id == state.id } ?: false + override fun hasMarker(state: MarkerState): Boolean { + val tiled = markerTileRenderer?.markers + return if (tiled?.isNotEmpty() == true) { + tiledMarkerIds.contains(tiled, state.id) } else { - _markers.value.any { it.id == state.id } + overlayMarkerIds.contains(_markers.value, state.id) } + } + + private val tiledMarkerIds = MarkerIdIndex() + private val overlayMarkerIds = MarkerIdIndex() @Deprecated("Use MarkerState.onDragStart instead.") override fun setOnMarkerDragStart(listener: OnMarkerEventHandler?) = Unit @@ -291,17 +373,86 @@ class LongdoMapViewController( override suspend fun compositionRasterLayers(data: List) { val newIds = data.map { it.id }.toSet() - appliedRasters.keys.filter { it !in newIds }.toList().forEach { id -> - runRasterJs(removeRasterJs(id)) - appliedRasters.remove(id) - } + appliedRasters.keys + .filter { it !in newIds && it !in mountedRasterIds } + .toList() + .forEach { id -> + runRasterJs(removeRasterJs(id)) + appliedRasters.remove(id) + } data.forEach { applyRaster(it) } + // Returns once the layers are on the page's map, so their onAdded comes after + // (see [PageLayerWait]). A source Longdo cannot show is not applied, nor waited for. + longdoMap.awaitPageLayers(data.filter { it.id in appliedRasters }.map { rasterLayerId(it.id) }) } + /** + * content の外から載せたラスタの id。上の掃除から外すためにある。 + * + * `compositionRasterLayers` は「アプリが宣言した集合」で全置換するので、 + * 外から載せたものは次の再コンポーズで消える。他プロバイダでは + * [com.mapconductor.core.raster.RasterLayerController] の `upsert` が + * 同じ役割(`upsertedIds`)を持っている。 + */ + private val mountedRasterIds = mutableSetOf() + + /** [mountRasterLayer] が ready 前に受け取ったもの。 */ + private val pendingMountedRasters = mutableMapOf() + override suspend fun updateRasterLayer(state: RasterLayerState) { applyRaster(state) } + /** + * content の外から載せるラスタ(マーカータイル、ベクタースタイルのラスタ化)。 + * + * 他プロバイダは [com.mapconductor.core.raster.RasterLayerController] を + * オーバーレイコントローラとして登録してあるので基底の実装で足りるが、 + * Longdo は内部 MapLibre GL へ JS で直接足すのでそれが無い。 + * id は [mountedRasterIds] に控えて composition の掃除から外す。 + */ + override fun mountRasterLayer(state: RasterLayerState) { + mountedRasterIds.add(state.id) + // ready 前に流した JS はページに捨てられる(`runRasterJs` は握りつぶす)。 + // content 経由のラスタは composition が ready より後なので起きないが、 + // ビューの外から載せるものは地図より先に来る。退避して [onMapReady] で出す。 + if (!mapReady) { + pendingMountedRasters[state.id] = state + return + } + mainCoroutine.launch { applyRaster(state) } + } + + /** + * [mountRasterLayer] that returns once the layer is on the page's map, for + * the polygon tiles: the tiled polygons' `onAdded` is called on the return. + * [mountRasterLayer] only queues the script (and before `ready` only keeps + * the layer), so they were reported before the map had their tiles' layer. + * Applied here rather than launched, so that a replaced source is gone + * before the layer is looked for. + */ + internal suspend fun mountRasterLayerOnMap(state: RasterLayerState) { + withContext(Dispatchers.Main.immediate) { + if (mapReady) { + mountedRasterIds.add(state.id) + applyRaster(state) + } else { + mountRasterLayer(state) + mapLoaded.first { it } + } + } + longdoMap.awaitPageLayers(listOf(rasterLayerId(state.id))) + } + + override fun unmountRasterLayer(id: String) { + mountedRasterIds.remove(id) + pendingMountedRasters.remove(id) + mainCoroutine.launch { + runRasterJs(removeRasterJs(id)) + appliedRasters.remove(id) + } + } + override fun hasRasterLayer(state: RasterLayerState): Boolean = appliedRasters.containsKey(state.id) // --- PolylineCapableInterface --- @@ -374,6 +525,8 @@ class LongdoMapViewController( circleController.clear() removeMarkerTileRaster() markerTileRenderer?.clear() + // 拡張モジュール(クラスタリングなど)が登録した Strategy のマーカーも消す。 + clearStrategyMarkerControllers() } internal var appliedUISettings: MapUISettings = MapUISettings.Default diff --git a/src/main/java/com/mapconductor/longdo/LongdoMapViewControllerCamera.kt b/src/main/java/com/mapconductor/longdo/LongdoMapViewControllerCamera.kt index 22ab115..e2ac41b 100644 --- a/src/main/java/com/mapconductor/longdo/LongdoMapViewControllerCamera.kt +++ b/src/main/java/com/mapconductor/longdo/LongdoMapViewControllerCamera.kt @@ -1,114 +1,139 @@ -package com.mapconductor.longdo - -import com.mapconductor.core.features.GeoPointInterface -import com.mapconductor.core.features.GeoRectBounds -import com.mapconductor.core.map.MapCameraPosition -import com.mapconductor.core.spherical.Spherical -import org.json.JSONObject -import kotlin.math.abs -import kotlin.math.tan - -// カメラの適用。Longdo のズームは MapConductor の論理ズームと 1 段ずれるため、 -// ZoomAltitudeConverter を通してから渡す。 - -/** - * カメラ停止時に [setCameraRestriction] の制限違反を補正する。補正したら true。 - * - * Longdo Map API3 には(Google の `setLatLngBoundsForCameraTarget` に相当する) - * カメラ範囲制限の JS API が無いため、android-sdk の HERE/ArcGIS/TomTom と同じく - * カメラ停止時に矩形内へクランプして再適用する方式で制限する。 - * 再適用すると再度カメライベントが発火し、そこでは補正不要になり通常フローへ進む。 - */ -internal fun LongdoMapViewController.applyCameraRestrictionCorrectionIfNeeded(current: MapCameraPosition): Boolean { - val corrected = correctForCameraRestriction(current) ?: return false - moveCamera(corrected) - return true -} - -internal fun LongdoMapViewController.handleMoveCamera(position: MapCameraPosition) { - if (mapReady) applyCamera(position) else pendingCameraPosition = position -} - -internal fun LongdoMapViewController.handleAnimateCamera( - position: MapCameraPosition, - duration: Long, -) { - // Longdo の JS ブリッジでは中心(location)とズーム(zoom)が別コマンドで、双方をアニメーション指定 - // すると後発のズームがパンのアニメーションを打ち切ってしまい中心が移動しない。カメラ同期では同期先が - // ソース側の連続イベントを追って滑らかに追従するため、ここでは瞬時に確定位置へ適用する。 - if (mapReady) applyCamera(position) else pendingCameraPosition = position -} - -/** - * Longdo の `map.location` / `map.zoom` / `map.rotate` / `map.pitch` を呼んでカメラを確定位置へ即時移動する。 - * - * - ズームは統一ズーム(Google)→ Longdo ネイティブズームへ変換して渡す。 - * - 方位([MapCameraPosition.bearing])は Longdo の `rotate`(北から時計回り=Google と同一規約)へ渡す。 - * - 傾き([MapCameraPosition.tilt])は Longdo の `pitch` へ渡す。負の傾き(仰角ビュー)は [nativeCameraFor] で - * 前進ターゲット+正 pitch に擬似変換する。 - * - * すべて `animate=false`(即時)で呼ぶ。中心・ズーム・方位・傾きのアニメーションは別コマンドのため、 - * いずれかをアニメーション指定すると後続コマンドが直前のアニメーションを打ち切ってしまう。 - */ -internal fun LongdoMapViewController.applyCamera(position: MapCameraPosition) { - val native = nativeCameraFor(position) - runCatching { - longdoMap.call("location", listOf(native.target.toLongdoLocation(), false)) {} - longdoMap.call("zoom", listOf(native.longdoZoom, false)) {} - longdoMap.call("rotate", listOf(position.bearing, false)) {} - longdoMap.call("pitch", listOf(native.pitch)) {} - } -} - -/** Longdo ネイティブへ渡すカメラ(中心・ズーム・pitch)。 */ -internal data class NativeCamera( - val target: GeoPointInterface, - val longdoZoom: Double, - val pitch: Double, -) - -/** - * 統一カメラ([MapCameraPosition])を Longdo ネイティブのカメラへ変換する。 - * - * tilt ≥ 0 は中心・ズームをそのまま用い、pitch を 0〜[LongdoMapViewController.MAX_PITCH] にクランプする。 - * - * tilt < 0(水平線より上方を向く仰角ビュー)は Longdo(MapLibre GL)が上向き pitch を表現できないため、 - * Google Maps 実装と同方式で擬似再現する: カメラ eye を固定したまま、地面ターゲットを bearing 方向へ - * `altitude * tan(|tilt|)` メートル前進させ、`|tilt|` の下向き pitch で描画する。ズームは変更しない。 - */ -internal fun LongdoMapViewController.nativeCameraFor(position: MapCameraPosition): NativeCamera { - val longdoZoom = LongdoMapViewController.coreZoomToLongdo(position.zoom) - if (position.tilt >= 0.0) { - return NativeCamera( - position.position, longdoZoom, - position.tilt - .coerceIn(0.0, LongdoMapViewController.MAX_PITCH), - ) - } - val tiltAbsDeg = abs(position.tilt).coerceIn(0.0, LongdoMapViewController.MAX_PITCH) - val tiltAbsRad = Math.toRadians(tiltAbsDeg) - // 高度は統一ズーム(Google)基準で算出する(Longdo ネイティブズームではない)。 - val altitude = zoomConverter.zoomLevelToAltitude(position.zoom, position.position.latitude, 0.0) - val distanceForward = altitude * tan(tiltAbsRad) - val target = Spherical.computeOffset(position.position, distanceForward, position.bearing) - return NativeCamera(target, longdoZoom, tiltAbsDeg) -} - -internal fun LongdoMapViewController.handleFitBounds( - bounds: GeoRectBounds, - padding: Int, -) { - val sw = bounds.southWest ?: return - val ne = bounds.northEast ?: return - val bound = - JSONObject() - .put("minLon", sw.longitude) - .put("minLat", sw.latitude) - .put("maxLon", ne.longitude) - .put("maxLat", ne.latitude) - // NOTE: Longdo Map API3 の map.bound(box) は境界矩形のみを引数に取り padding 相当の - // 余白パラメータを持たないため、padding は反映できない(矩形を膨らませる擬似対応は行わない)。 - if (mapReady) { - runCatching { longdoMap.call("bound", listOf(bound)) {} } - } -} +package com.mapconductor.longdo + +import com.mapconductor.core.features.GeoPointInterface +import com.mapconductor.core.features.GeoRectBounds +import com.mapconductor.core.map.CameraBearing +import com.mapconductor.core.map.CameraPaddingEmulation +import com.mapconductor.core.map.MapCameraPosition +import com.mapconductor.core.spherical.Spherical +import org.json.JSONObject +import kotlin.math.abs +import kotlin.math.tan + +// カメラの適用。Longdo のズームは MapConductor の論理ズームと 1 段ずれるため、 +// ZoomAltitudeConverter を通してから渡す。 + +/** + * カメラ停止時に [setCameraRestriction] の制限違反を補正する。補正したら true。 + * + * Longdo Map API3 には(Google の `setLatLngBoundsForCameraTarget` に相当する) + * カメラ範囲制限の JS API が無いため、android-sdk の HERE/ArcGIS/TomTom と同じく + * カメラ停止時に矩形内へクランプして再適用する方式で制限する。 + * 再適用すると再度カメライベントが発火し、そこでは補正不要になり通常フローへ進む。 + */ +internal fun LongdoMapViewController.applyCameraRestrictionCorrectionIfNeeded(current: MapCameraPosition): Boolean { + val corrected = correctForCameraRestriction(current) ?: return false + moveCamera(corrected) + return true +} + +/** + * Longdo の地図(MapLibre GL)の縦方向の視野角(度)。MapLibre の既定値で、地図の大きさに + * よらず一定(焦点距離 = 地図の高さ × 1.5)。 + */ +internal const val LONGDO_VERTICAL_FOV = 36.87 + +/** 地図の高さ(dp)。パディングのエミュレーションで遠近を解くのに使う。 */ +internal fun LongdoMapViewController.viewportHeightDp(): Double { + val density = holder.mapView.resources.displayMetrics.density + return holder.mapView.height / density.toDouble() +} + +internal fun LongdoMapViewController.handleMoveCamera(position: MapCameraPosition) { + position.paddings?.let { cameraPaddings = it } + if (mapReady) applyCamera(position) else pendingCameraPosition = position +} + +internal fun LongdoMapViewController.handleAnimateCamera( + position: MapCameraPosition, + duration: Long, +) { + // Longdo の JS ブリッジでは中心(location)とズーム(zoom)が別コマンドで、双方をアニメーション指定 + // すると後発のズームがパンのアニメーションを打ち切ってしまい中心が移動しない。カメラ同期では同期先が + // ソース側の連続イベントを追って滑らかに追従するため、ここでは瞬時に確定位置へ適用する。 + position.paddings?.let { cameraPaddings = it } + if (mapReady) applyCamera(position) else pendingCameraPosition = position +} + +/** + * Longdo の `map.location` / `map.zoom` / `map.rotate` / `map.pitch` を呼んでカメラを確定位置へ即時移動する。 + * + * - ズームは統一ズーム(Google)→ Longdo ネイティブズームへ変換して渡す。 + * - 方位([MapCameraPosition.bearing])は Longdo の `rotate`(北から時計回り=Google と同一規約)へ渡す。 + * - 傾き([MapCameraPosition.tilt])は Longdo の `pitch` へ渡す。負の傾き(仰角ビュー)は [nativeCameraFor] で + * 前進ターゲット+正 pitch に擬似変換する。 + * + * すべて `animate=false`(即時)で呼ぶ。中心・ズーム・方位・傾きのアニメーションは別コマンドのため、 + * いずれかをアニメーション指定すると後続コマンドが直前のアニメーションを打ち切ってしまう。 + */ +internal fun LongdoMapViewController.applyCamera(position: MapCameraPosition) { + // パディングは中心のずらしで再現する(Longdo にパディングの口が無いため)。 + val padded = + CameraPaddingEmulation.toNativeCamera( + position.copy(paddings = cameraPaddings), + LONGDO_VERTICAL_FOV, + viewportHeightDp(), + ) + val native = nativeCameraFor(padded) + runCatching { + longdoMap.call("location", listOf(native.target.toLongdoLocation(), false)) {} + longdoMap.call("zoom", listOf(native.longdoZoom, false)) {} + longdoMap.call("rotate", listOf(CameraBearing.toNativeHeading(padded.bearing), false)) {} + longdoMap.call("pitch", listOf(native.pitch)) {} + } +} + +/** Longdo ネイティブへ渡すカメラ(中心・ズーム・pitch)。 */ +internal data class NativeCamera( + val target: GeoPointInterface, + val longdoZoom: Double, + val pitch: Double, +) + +/** + * 統一カメラ([MapCameraPosition])を Longdo ネイティブのカメラへ変換する。 + * + * tilt ≥ 0 は中心・ズームをそのまま用い、pitch を 0〜[LongdoMapViewController.MAX_PITCH] にクランプする。 + * + * tilt < 0(水平線より上方を向く仰角ビュー)は Longdo(MapLibre GL)が上向き pitch を表現できないため、 + * Google Maps 実装と同方式で擬似再現する: カメラ eye を固定したまま、地面ターゲットを bearing 方向へ + * `altitude * tan(|tilt|)` メートル前進させ、`|tilt|` の下向き pitch で描画する。ズームは変更しない。 + */ +internal fun LongdoMapViewController.nativeCameraFor(position: MapCameraPosition): NativeCamera { + val longdoZoom = LongdoMapViewController.coreZoomToLongdo(position.zoom) + if (position.tilt >= 0.0) { + return NativeCamera( + position.position, longdoZoom, + position.tilt + .coerceIn(0.0, LongdoMapViewController.MAX_PITCH), + ) + } + val tiltAbsDeg = abs(position.tilt).coerceIn(0.0, LongdoMapViewController.MAX_PITCH) + val tiltAbsRad = Math.toRadians(tiltAbsDeg) + // 高度は統一ズーム(Google)基準で算出する(Longdo ネイティブズームではない)。 + val altitude = zoomConverter.zoomLevelToAltitude(position.zoom, position.position.latitude, 0.0) + val distanceForward = altitude * tan(tiltAbsRad) + val target = + Spherical + .computeOffset(position.position, distanceForward, CameraBearing.toNativeHeading(position.bearing)) + return NativeCamera(target, longdoZoom, tiltAbsDeg) +} + +internal fun LongdoMapViewController.handleFitBounds( + bounds: GeoRectBounds, + padding: Int, +) { + val sw = bounds.southWest ?: return + val ne = bounds.northEast ?: return + val bound = + JSONObject() + .put("minLon", sw.longitude) + .put("minLat", sw.latitude) + .put("maxLon", ne.longitude) + .put("maxLat", ne.latitude) + // NOTE: Longdo Map API3 の map.bound(box) は境界矩形のみを引数に取り padding 相当の + // 余白パラメータを持たないため、padding は反映できない(矩形を膨らませる擬似対応は行わない)。 + if (mapReady) { + runCatching { longdoMap.call("bound", listOf(bound)) {} } + } +} diff --git a/src/main/java/com/mapconductor/longdo/LongdoMapViewControllerMarkerTiles.kt b/src/main/java/com/mapconductor/longdo/LongdoMapViewControllerMarkerTiles.kt index 28b8758..b3855b8 100644 --- a/src/main/java/com/mapconductor/longdo/LongdoMapViewControllerMarkerTiles.kt +++ b/src/main/java/com/mapconductor/longdo/LongdoMapViewControllerMarkerTiles.kt @@ -71,10 +71,12 @@ internal fun LongdoMapViewController.applyMarkerTileRaster(state: RasterLayerSta val prev = markerTileState val layerSpec = rasterLayerSpec(layerId, srcId, state.opacity, state.visible) when { - prev == null -> runRasterJs(addRasterJs(srcId, layerId, spec, layerSpec)) + // マーカーのタイルはマーカーの帯(ポリライン等より上)。 + prev == null -> + runRasterJs(addRasterJs(srcId, layerId, spec, layerSpec, LongdoOverlayStacking.addMarkerTileLayerJs(layerSpec))) prev.source != state.source -> { runRasterJs(removeRasterJs(state.id)) - runRasterJs(addRasterJs(srcId, layerId, spec, layerSpec)) + runRasterJs(addRasterJs(srcId, layerId, spec, layerSpec, LongdoOverlayStacking.addMarkerTileLayerJs(layerSpec))) } } markerTileState = state @@ -92,14 +94,12 @@ internal fun LongdoMapViewController.removeMarkerTileRaster() { * 流さない(他プロバイダと同じ)。 * * @param point タップ座標。 - * @param nativeZoom Longdo ネイティブ(MapLibre)ズーム。 * @return マーカーがタップを消費したら true。 */ internal fun LongdoMapViewController.handleMarkerTap( point: com.mapconductor.core.features.GeoPoint, - nativeZoom: Double, ): Boolean { - val state = markerTileRenderer?.findMarkerAt(point, nativeZoom) ?: return false + val state = markerTileRenderer?.findMarkerAt(point, holder::toScreenOffset) ?: return false // clickable = false のマーカーは透過させる(コアの clickableOnly と同じ方針)。 if (!state.clickable) return false state.onClick?.invoke(state) diff --git a/src/main/java/com/mapconductor/longdo/LongdoMapViewControllerRaster.kt b/src/main/java/com/mapconductor/longdo/LongdoMapViewControllerRaster.kt index 795eb44..a62eb89 100644 --- a/src/main/java/com/mapconductor/longdo/LongdoMapViewControllerRaster.kt +++ b/src/main/java/com/mapconductor/longdo/LongdoMapViewControllerRaster.kt @@ -1,120 +1,174 @@ -package com.mapconductor.longdo - -import com.mapconductor.core.raster.RasterHeaderRuleSet -import com.mapconductor.core.raster.RasterLayerSource -import com.mapconductor.core.raster.RasterLayerState -import com.mapconductor.core.raster.TileScheme -import org.json.JSONArray -import org.json.JSONObject - -/** - * ラスターレイヤーの反映。 - * - * Longdo は WebView 上の JS 地図なので、レイヤーの追加・削除・不透明度は - * すべて JS 文字列を組み立てて流し込む形になる。ID は他レイヤーとぶつからない - * よう `mcrs_` / `mcrl_` を前置する。 - */ -internal fun LongdoMapViewController.applyRaster(state: RasterLayerState) { - RasterHeaderRuleSet.warnUnsupported(provider = "Longdo", state = state) - val srcId = rasterSourceId(state.id) - val layerId = rasterLayerId(state.id) - val spec = rasterSourceSpec(state.source) ?: return // 未対応ソースはスキップ - val prev = appliedRasters[state.id] - val layerSpec = rasterLayerSpec(layerId, srcId, state.opacity, state.visible) - when { - prev == null -> - runRasterJs(addRasterJs(srcId, layerId, spec, layerSpec)) - prev.source != state.source -> { - runRasterJs(removeRasterJs(state.id)) - runRasterJs(addRasterJs(srcId, layerId, spec, layerSpec)) - } - else -> { - if (prev.opacity != state.opacity) runRasterJs(setRasterOpacityJs(layerId, state.opacity)) - if (prev.visible != state.visible) runRasterJs(setRasterVisibilityJs(layerId, state.visible)) - } - } - appliedRasters[state.id] = state -} - -internal fun LongdoMapViewController.runRasterJs(js: String) { - runCatching { longdoMap.run(js) {} } -} - -/** MapLibre のラスターソース仕様(JSON)。未対応ソースは null。 */ -internal fun LongdoMapViewController.rasterSourceSpec(source: RasterLayerSource): String? = - when (source) { - is RasterLayerSource.UrlTemplate -> - JSONObject() - .put("type", "raster") - .put("tiles", JSONArray().put(source.template)) - .put("tileSize", source.tileSize) - .apply { - source.minZoom?.let { put("minzoom", it) } - source.maxZoom?.let { put("maxzoom", it) } - }.put("scheme", if (source.scheme == TileScheme.TMS) "tms" else "xyz") - .toString() - - is RasterLayerSource.TileJson -> - JSONObject().put("type", "raster").put("url", source.url).toString() - - is RasterLayerSource.ArcGisService -> null - } - -internal fun LongdoMapViewController.rasterLayerSpec( - layerId: String, - sourceId: String, - opacity: Float, - visible: Boolean, -): String = - JSONObject() - .put("id", layerId) - .put("type", "raster") - .put("source", sourceId) - .put("paint", JSONObject().put("raster-opacity", opacity.toDouble())) - .put("layout", JSONObject().put("visibility", if (visible) "visible" else "none")) - .toString() - -internal fun LongdoMapViewController.addRasterJs( - sourceId: String, - layerId: String, - sourceSpec: String, - layerSpec: String, -): String = - """ - (function(){var m=map.Renderer; if(!m)return; - var tries=0; - function apply(){ - try{ - if(!m.getSource('$sourceId'))m.addSource('$sourceId',$sourceSpec); - if(!m.getLayer('$layerId'))m.addLayer($layerSpec); - }catch(e){ if(tries++<30)setTimeout(apply,150); } - } - apply(); - })() - """.trimIndent() - -internal fun LongdoMapViewController.removeRasterJs(id: String): String { - val srcId = rasterSourceId(id) - val layerId = rasterLayerId(id) - return "(function(){try{var m=map.Renderer;" + - "if(m.getLayer('$layerId'))m.removeLayer('$layerId');" + - "if(m.getSource('$srcId'))m.removeSource('$srcId');}catch(e){}})()" -} - -internal fun LongdoMapViewController.setRasterOpacityJs( - layerId: String, - opacity: Float, -): String = - "(function(){try{if(map.Renderer.getLayer('$layerId'))" + - "map.Renderer.setPaintProperty('$layerId','raster-opacity',${opacity.toDouble()});}catch(e){}})()" - -internal fun LongdoMapViewController.setRasterVisibilityJs( - layerId: String, - visible: Boolean, -): String = - "(function(){try{if(map.Renderer.getLayer('$layerId'))" + - "map.Renderer.setLayoutProperty('$layerId','visibility','${if (visible) "visible" else "none"}');}catch(e){}})()" - -internal fun LongdoMapViewController.rasterSourceId(id: String): String = "mcrs_$id" - -internal fun LongdoMapViewController.rasterLayerId(id: String): String = "mcrl_$id" +package com.mapconductor.longdo + +import com.mapconductor.core.circle.CIRCLE_TILE_LAYER_ID +import com.mapconductor.core.controller.OverlayKind +import com.mapconductor.core.polygon.POLYGON_TILE_LAYER_ID +import com.mapconductor.core.polyline.POLYLINE_TILE_LAYER_ID +import com.mapconductor.core.raster.RasterHeaderRuleSet +import com.mapconductor.core.raster.RasterLayerSource +import com.mapconductor.core.raster.RasterLayerState +import com.mapconductor.core.raster.TileScheme +import org.json.JSONArray +import org.json.JSONObject + +/** + * ラスターレイヤーの反映。 + * + * Longdo は WebView 上の JS 地図なので、レイヤーの追加・削除・不透明度は + * すべて JS 文字列を組み立てて流し込む形になる。ID は他レイヤーとぶつからない + * よう `mcrs_` / `mcrl_` を前置する。 + */ +internal fun LongdoMapViewController.applyRaster(state: RasterLayerState) { + RasterHeaderRuleSet.warnUnsupported(provider = "Longdo", state = state) + val srcId = rasterSourceId(state.id) + val layerId = rasterLayerId(state.id) + val spec = rasterSourceSpec(state.source) ?: return // 未対応ソースはスキップ + val prev = appliedRasters[state.id] + val layerSpec = rasterLayerSpec(layerId, srcId, state.opacity, state.visible) + when { + prev == null -> + runRasterJs(addRasterJs(srcId, layerId, spec, layerSpec, rasterAddLayerJs(layerSpec, state))) + prev.source != state.source || prev.zIndex != state.zIndex -> { + runRasterJs(removeRasterJs(state.id)) + runRasterJs(addRasterJs(srcId, layerId, spec, layerSpec, rasterAddLayerJs(layerSpec, state))) + } + else -> { + if (prev.opacity != state.opacity) runRasterJs(setRasterOpacityJs(layerId, state.opacity)) + if (prev.visible != state.visible) runRasterJs(setRasterVisibilityJs(layerId, state.visible)) + } + } + appliedRasters[state.id] = state +} + +private fun rasterAddLayerJs( + layerSpec: String, + state: RasterLayerState, +): String = + if (state.id == POLYGON_TILE_LAYER_ID) { + LongdoOverlayStacking.addPolygonTileLayerJs(layerSpec) + } else if (state.id == CIRCLE_TILE_LAYER_ID) { + LongdoOverlayStacking.addCircleTileLayerJs(layerSpec) + } else if (state.id == POLYLINE_TILE_LAYER_ID) { + LongdoOverlayStacking.addPolylineTileLayerJs(layerSpec) + } else { + LongdoOverlayStacking.addLayerJs(layerSpec, OverlayKind.RasterLayer, state.zIndex) + } + +internal fun LongdoMapViewController.runRasterJs(js: String) { + runCatching { longdoMap.run(js) {} } +} + +/** MapLibre のラスターソース仕様(JSON)。未対応ソースは null。 */ +internal fun LongdoMapViewController.rasterSourceSpec(source: RasterLayerSource): String? = + when (source) { + is RasterLayerSource.UrlTemplate -> + JSONObject() + .put("type", "raster") + .put("tiles", JSONArray().put(source.template)) + .put("tileSize", source.tileSize) + .apply { + source.minZoom?.let { put("minzoom", it) } + source.maxZoom?.let { put("maxzoom", it) } + }.put("scheme", if (source.scheme == TileScheme.TMS) "tms" else "xyz") + .toString() + + is RasterLayerSource.TileJson -> + JSONObject().put("type", "raster").put("url", source.url).toString() + + is RasterLayerSource.ArcGisService -> null + } + +internal fun LongdoMapViewController.rasterLayerSpec( + layerId: String, + sourceId: String, + opacity: Float, + visible: Boolean, +): String = + JSONObject() + .put("id", layerId) + .put("type", "raster") + .put("source", sourceId) + .put("paint", JSONObject().put("raster-opacity", opacity.toDouble())) + .put("layout", JSONObject().put("visibility", if (visible) "visible" else "none")) + .toString() + +internal fun LongdoMapViewController.addRasterJs( + sourceId: String, + layerId: String, + sourceSpec: String, + layerSpec: String, +): String = addRasterJs(sourceId, layerId, sourceSpec, layerSpec, LongdoOverlayStacking.addLayerJs(layerSpec, OverlayKind.RasterLayer)) + +/** [addLayer] は帯の順で層を足す JS([LongdoOverlayStacking.addLayerJs])。 */ +internal fun LongdoMapViewController.addRasterJs( + sourceId: String, + layerId: String, + sourceSpec: String, + layerSpec: String, + addLayer: String, +): String = + """ + (function(){var m=map.Renderer; if(!m)return; + var tries=0; + function apply(){ + try{ + if(!m.getSource('$sourceId'))m.addSource('$sourceId',$sourceSpec); + if(!m.getLayer('$layerId'))$addLayer + }catch(e){ if(tries++<30)setTimeout(apply,150); } + } + apply(); + })() + """.trimIndent() + +/** + * ベースレイヤ切替(= 内部スタイルの差し替え)のあとに、[rasters] を載せ直す JS。 + * + * `style.load` で一度、保険に 1.5 秒後にもう一度。どちらも「無ければ足す」なので + * 二重にはならない。差し替え前に走った分は差し替えで消え、あとの分が残る。 + */ +internal fun LongdoMapViewController.readdRastersAfterStyleSwapJs(rasters: List): String { + val adds = + rasters + .mapNotNull { state -> + val spec = rasterSourceSpec(state.source) ?: return@mapNotNull null + val srcId = rasterSourceId(state.id) + val layerId = rasterLayerId(state.id) + val layerSpec = rasterLayerSpec(layerId, srcId, state.opacity, state.visible) + val addLayer = + if (state.id == markerTileState?.id) { + LongdoOverlayStacking.addMarkerTileLayerJs(layerSpec) + } else { + rasterAddLayerJs(layerSpec, state) + } + "try{if(!m.getSource('$srcId'))m.addSource('$srcId',$spec);" + + "if(!m.getLayer('$layerId'))$addLayer}catch(e){}" + }.joinToString("") + return "(function(){var m=map.Renderer;if(!m)return;function re(){$adds}" + + "m.once('style.load',function(){setTimeout(re,0);});setTimeout(re,1500);})()" +} + +internal fun LongdoMapViewController.removeRasterJs(id: String): String { + val srcId = rasterSourceId(id) + val layerId = rasterLayerId(id) + return "(function(){try{var m=map.Renderer;" + + "if(m.getLayer('$layerId'))m.removeLayer('$layerId');" + + "if(m.getSource('$srcId'))m.removeSource('$srcId');}catch(e){}})()" +} + +internal fun LongdoMapViewController.setRasterOpacityJs( + layerId: String, + opacity: Float, +): String = + "(function(){try{if(map.Renderer.getLayer('$layerId'))" + + "map.Renderer.setPaintProperty('$layerId','raster-opacity',${opacity.toDouble()});}catch(e){}})()" + +internal fun LongdoMapViewController.setRasterVisibilityJs( + layerId: String, + visible: Boolean, +): String = + "(function(){try{if(map.Renderer.getLayer('$layerId'))" + + "map.Renderer.setLayoutProperty('$layerId','visibility','${if (visible) "visible" else "none"}');}catch(e){}})()" + +internal fun LongdoMapViewController.rasterSourceId(id: String): String = "mcrs_$id" + +internal fun LongdoMapViewController.rasterLayerId(id: String): String = "mcrl_$id" diff --git a/src/main/java/com/mapconductor/longdo/LongdoMapViewHolder.kt b/src/main/java/com/mapconductor/longdo/LongdoMapViewHolder.kt index aee0c40..aed239c 100644 --- a/src/main/java/com/mapconductor/longdo/LongdoMapViewHolder.kt +++ b/src/main/java/com/mapconductor/longdo/LongdoMapViewHolder.kt @@ -2,9 +2,10 @@ package com.mapconductor.longdo import androidx.compose.ui.geometry.Offset import com.longdo.sdk3.LongdoMap +import com.mapconductor.core.ResourceProvider import com.mapconductor.core.features.GeoPoint import com.mapconductor.core.features.GeoPointInterface -import com.mapconductor.core.ResourceProvider +import com.mapconductor.core.map.CameraPaddingEmulation import com.mapconductor.core.map.MapCameraPosition import com.mapconductor.core.map.MapViewHolderInterface import com.mapconductor.core.projection.WebMercatorScreenProjection @@ -18,7 +19,8 @@ import com.mapconductor.core.projection.WebMercatorScreenProjection * * ブリッジは同期の座標変換 API を持たないが、Longdo の地図は Web Mercator なので * 投影はカメラとビューの大きさだけで決まる。式はコアの [WebMercatorScreenProjection] - * にあり、ここはカメラとサイズを渡すだけ。**各所で式を書き直さないこと。** + * にあり、ここはカメラとサイズと視野角を渡すだけ。**各所で式を書き直さないこと。** + * 視野角を渡すので tilt も透視で扱う(渡さないと奥ほどずれ、tilt 60 で 250px 近くずれていた)。 */ class LongdoMapViewHolder( private val longdoMap: LongdoMap, @@ -32,6 +34,15 @@ class LongdoMapViewHolder( */ internal var cameraProvider: (() -> MapCameraPosition?)? = null + /** + * 投影の中心にするカメラ。パディングを付けたカメラの position はパディング中央なので、 + * 画面中央に来る点(ネイティブへ渡したカメラ中心)へ戻してから使う。 + */ + private fun screenCenteredCamera(heightDp: Float): MapCameraPosition? { + val camera = cameraProvider?.invoke() ?: return null + return CameraPaddingEmulation.toNativeCamera(camera, LONGDO_VERTICAL_FOV, heightDp.toDouble()) + } + /** * 地理座標 → 画面座標(**端末ピクセル**)。カメラ未確定(地図の準備前)なら null。 * @@ -41,14 +52,15 @@ class LongdoMapViewHolder( * 中心からのずれが density 分だけ小さくなり、マーカーと吹き出しがずれる。 */ override fun toScreenOffset(position: GeoPointInterface): Offset? { - val camera = cameraProvider?.invoke() ?: return null val density = ResourceProvider.getDensity() + val camera = screenCenteredCamera(longdoMap.height / density) ?: return null val offsetDp = WebMercatorScreenProjection.toScreenOffset( position = position, camera = camera, widthPx = longdoMap.width / density, heightPx = longdoMap.height / density, + fovDegrees = LONGDO_VERTICAL_FOV, ) ?: return null return Offset(offsetDp.x * density, offsetDp.y * density) } @@ -58,13 +70,14 @@ class LongdoMapViewHolder( * こちらを使う。非同期版は基底の既定実装がここへ委譲する。 */ override fun fromScreenOffsetSync(offset: Offset): GeoPoint? { - val camera = cameraProvider?.invoke() ?: return null val density = ResourceProvider.getDensity() + val camera = screenCenteredCamera(longdoMap.height / density) ?: return null return WebMercatorScreenProjection.fromScreenOffset( offset = Offset(offset.x / density, offset.y / density), camera = camera, widthPx = longdoMap.width / density, heightPx = longdoMap.height / density, + fovDegrees = LONGDO_VERTICAL_FOV, ) } } diff --git a/src/main/java/com/mapconductor/longdo/LongdoOverlayStacking.kt b/src/main/java/com/mapconductor/longdo/LongdoOverlayStacking.kt new file mode 100644 index 0000000..0988da3 --- /dev/null +++ b/src/main/java/com/mapconductor/longdo/LongdoOverlayStacking.kt @@ -0,0 +1,44 @@ +package com.mapconductor.longdo + +import com.mapconductor.core.controller.OverlayKind +import com.mapconductor.core.controller.OverlayStacking + +/** + * 重なり順([OverlayStacking]: ラスター < GroundImage < ポリゴン < サークル < ポリライン < マーカー)。 + * + * Longdo の地図は WebView の中の MapLibre GL JS(`map.Renderer`)で、レイヤーは + * `addLayer` した順に上へ積まれていた(追加・送り直し・スタイル差し替えの順に左右される)。 + * ここで作る JS は、足す層の帯と zIndex を `m.__mcStack` に記録し、今のスタイルの並びから + * 「鍵が自分より大きい一番下の SDK の層」を beforeId に選んで `addLayer` する。 + * ラスターだけはベースマップのラベル(SDK の層でない最初の symbol 層)の下に入れる。 + */ +internal object LongdoOverlayStacking { + private const val FN = + "function(m,s,b,z){var K=m.__mcStack||(m.__mcStack={});K[s.id]=[b,z];" + + "if(m.getLayer(s.id))return;var L=m.getStyle().layers,i,k,bi=-1;" + + "for(i=0;ib||(k[0]==b&&k[1]>z))){bi=i;break;}}" + + "if(b==0){for(i=0;i() { override fun saveMapDesign( state: LongdoViewState, bundle: Bundle, ) { - bundle.putString(KEY_DESIGN_ID, state.mapDesignType.id) + val design = state.mapDesignType + bundle.putString(KEY_DESIGN_ID, design.id) + bundle.putString(KEY_LAYER_NAME, design.layerName) + MapViewStateBundle.putAttributionRules(bundle, design.attributionRules) } override fun createState( stateId: String, mapDesignBundle: Bundle?, cameraPosition: MapCameraPosition, - ): LongdoViewState { - val designId = mapDesignBundle?.getString(KEY_DESIGN_ID) - return LongdoViewState( - mapDesignType = LongdoDesign.fromId(designId), + ): LongdoViewState = + LongdoViewState( + mapDesignType = restoreDesign(mapDesignBundle), id = stateId, initialCameraPosition = cameraPosition, ) + + private fun restoreDesign(bundle: Bundle?): LongdoMapDesignTypeInterface { + val designId = bundle?.getString(KEY_DESIGN_ID) + // レイヤ名を持たない以前の形式は id から引く。 + val layerName = bundle?.getString(KEY_LAYER_NAME) ?: return LongdoDesign.fromId(designId) + val id = designId ?: LongdoDesign.Normal.id + val rules = MapViewStateBundle.getAttributionRules(bundle) + // LongdoDesign は attributionRules を持てない。規則が無ければ LongdoDesign で戻し、 + // 定義済み(LongdoDesign.Gray など)と等しくなるようにする。 + return if (rules.isEmpty()) { + LongdoDesign(id = id, layerName = layerName) + } else { + RestoredLongdoDesign(id = id, layerName = layerName, attributionRules = rules) + } } override fun getStateId(state: LongdoViewState): String = state.id @@ -92,6 +114,19 @@ class LongdoMapViewSaver : BaseMapViewSaver() { } } +// 公開 API の門番(javap)にコンパニオンの定数が載らないよう、ファイル private にする。 +private const val KEY_LAYER_NAME = "longdo_layer_name" + +/** attributionRules を持つデザインを復元するときの入れ物([LongdoDesign] は規則を持てない)。 */ +@InternalMapConductorApi +internal data class RestoredLongdoDesign( + override val id: String, + override val layerName: String, + override val attributionRules: List, +) : LongdoMapDesignTypeInterface { + override fun getValue(): String = id +} + /** * [LongdoViewState] を生成・記憶する Composable ファクトリ。 * diff --git a/src/main/java/com/mapconductor/longdo/PageLayerWait.kt b/src/main/java/com/mapconductor/longdo/PageLayerWait.kt new file mode 100644 index 0000000..8ca9e01 --- /dev/null +++ b/src/main/java/com/mapconductor/longdo/PageLayerWait.kt @@ -0,0 +1,113 @@ +package com.mapconductor.longdo + +import com.longdo.sdk3.LongdoMap +import android.util.Log +import kotlin.coroutines.resume +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.delay +import kotlinx.coroutines.suspendCancellableCoroutine +import kotlinx.coroutines.withTimeoutOrNull + +/** + * Waits until the page's map has the layers an overlay was just given. + * + * Longdo is a page in a WebView: `LongdoMap.run` queues the script and returns, + * and an add that finds the style not ready retries from the page with + * `setTimeout`. + * So a renderer's `onAdd` returned before its layers were on the map, and + * the overlay's `onAdded` (asked for right after the hand-over) came while + * the map still showed nothing. Boston's 604 downtown polygons reported + * `onAdded` 0.1 s after the hand-over; the last of their layers reached the + * map 1.4 s after it (Lenovo TB520FU). + * Renderers call [await] at the end of `onAdd`, so `compositionXxx` + * returns, and `onAdded` is called, once the layers are there. + * + * Only that the layers are in the style is waited for, not their tiles or + * images (same as every other provider). + */ +internal object PageLayerWait { + /** The page's map, or a falsy value while there is none. */ + const val MAP_EXPR = "window.map && map.Renderer" + + /** + * Only a guard against a layer the page refused, which never shows up: + * a few hundred layers can take the page well over 10 s. + */ + const val TIMEOUT_MS = 60_000L + const val INTERVAL_MS = 100L + + /** + * Script that answers how many of [ids], from the front, the map has + * (as text, e.g. `"3"`); `"0"` while there is no map. + */ + fun script(ids: List): String { + val list = ids.joinToString(",", "[", "]") { quote(it) } + return "(function(){try{var m=$MAP_EXPR;if(!m)return '0';var ids=$list;" + + "for(var i=0;i, + timeoutMs: Long = TIMEOUT_MS, + intervalMs: Long = INTERVAL_MS, + evaluate: suspend (String) -> String?, + ): Boolean { + if (ids.isEmpty()) return true + var missing = ids + val done = + withTimeoutOrNull(timeoutMs) { + while (missing.isNotEmpty()) { + val present = + try { + parse(evaluate(script(missing))) + } catch (e: CancellationException) { + throw e + } catch (_: Exception) { + 0 + } + // Layers mostly arrive in the order they were added: ask only for the rest. + missing = missing.drop(present) + if (missing.isNotEmpty()) delay(intervalMs) + } + true + } ?: false + if (!done) { + runCatching { Log.w(TAG, "${missing.size} of ${ids.size} layers not on the map after $timeoutMs ms") } + } + return done + } + + private fun quote(text: String): String = + buildString { + append('"') + for (c in text) { + when { + c == '"' -> append("\\\"") + c == '\\' -> append("\\\\") + c < ' ' || c == '\u2028' || c == '\u2029' -> append(String.format("\\u%04x", c.code)) + else -> append(c) + } + } + append('"') + } + + private const val TAG = "PageLayerWait" +} + +/** [PageLayerWait.await] against this map's page. */ +internal suspend fun LongdoMap.awaitPageLayers(ids: List): Boolean = + PageLayerWait.await(ids) { js -> + suspendCancellableCoroutine { continuation -> + run(js) { result -> if (continuation.isActive) continuation.resume(result) } + } + } diff --git a/src/main/java/com/mapconductor/longdo/circle/LongdoCircleController.kt b/src/main/java/com/mapconductor/longdo/circle/LongdoCircleController.kt index e28d300..6ebbf5b 100644 --- a/src/main/java/com/mapconductor/longdo/circle/LongdoCircleController.kt +++ b/src/main/java/com/mapconductor/longdo/circle/LongdoCircleController.kt @@ -15,8 +15,8 @@ class LongdoCircleController( override val renderer: LongdoCircleOverlayRenderer, circleManager: CircleManagerInterface = CircleManager(), ) : CircleController(circleManager, renderer) { - /** 既知の円を再適用する(地図 `ready` 後の復元用)。 */ + /** 既知の円を再適用する(地図 `ready` 後の復元用)。タイルで描く円(ハンドル無し)は飛ばす。 */ fun reapply() { - renderer.reapply(circleManager.allEntities().map { it.circle }) + renderer.reapply(circleManager.nativeEntities().mapNotNull { it.circle as LongdoCircleHandle? }) } } diff --git a/src/main/java/com/mapconductor/longdo/circle/LongdoCircleOverlayRenderer.kt b/src/main/java/com/mapconductor/longdo/circle/LongdoCircleOverlayRenderer.kt index fb4a939..f1ddd1e 100644 --- a/src/main/java/com/mapconductor/longdo/circle/LongdoCircleOverlayRenderer.kt +++ b/src/main/java/com/mapconductor/longdo/circle/LongdoCircleOverlayRenderer.kt @@ -5,8 +5,11 @@ import com.longdo.sdk3.LongdoMap import com.mapconductor.core.circle.CircleEntityInterface import com.mapconductor.core.circle.CircleOverlayRendererInterface import com.mapconductor.core.circle.CircleState +import com.mapconductor.core.controller.OverlayKind import com.mapconductor.core.geometry.OverlayGeoJson import com.mapconductor.core.geometry.circleToRing +import com.mapconductor.longdo.LongdoOverlayStacking +import com.mapconductor.longdo.awaitPageLayers import org.json.JSONObject /** @@ -21,9 +24,17 @@ import org.json.JSONObject class LongdoCircleOverlayRenderer( private val longdoMap: LongdoMap, ) : CircleOverlayRendererInterface { + /** + * Returns once the layers are on the page's map, so the circles' + * `onAdded` comes after they are (see [com.mapconductor.longdo.PageLayerWait]). + */ override suspend fun onAdd( data: List, - ): List = data.map { addCircle(it.state) } + ): List { + val handles = data.map { addCircle(it.state) } + longdoMap.awaitPageLayers(handles.filterNotNull().flatMap { listOf(it.fillLayerId, it.lineLayerId) }) + return handles + } override suspend fun onChange( data: List>, @@ -55,8 +66,12 @@ class LongdoCircleOverlayRenderer( handles.forEach { runJs(addJs(it)) } } + /** 層の id → zIndex(帯の中の順)。 */ + private val zIndexByLayer = java.util.concurrent.ConcurrentHashMap() + private fun addCircle(state: CircleState): LongdoCircleHandle? { val feature = buildGeoJson(state) ?: return null + zIndexByLayer["circle-fill-${state.id}"] = state.zIndex ?: 0 val fillArgb = state.fillColor.toArgb() val strokeArgb = state.strokeColor.toArgb() val handle = @@ -137,6 +152,9 @@ class LongdoCircleOverlayRenderer( .put("line-opacity", handle.strokeOpacity) .put("line-width", handle.strokeWidth), ).toString() + // サークルの帯。輪郭は塗りの直後。 + val fillAdd = LongdoOverlayStacking.addLayerJs(fillSpec, OverlayKind.Circle, zIndexByLayer[handle.fillLayerId] ?: 0) + val lineAdd = LongdoOverlayStacking.addLayerJs(lineSpec, OverlayKind.Circle, zIndexByLayer[handle.fillLayerId] ?: 0) return """ (function(){var m=map.Renderer; if(!m)return; var tries=0; @@ -144,8 +162,8 @@ class LongdoCircleOverlayRenderer( try{ if(!m.getSource('${handle.sourceId}')) m.addSource('${handle.sourceId}',{type:'geojson',data:${handle.featureJson}}); - if(!m.getLayer('${handle.fillLayerId}'))m.addLayer($fillSpec); - if(!m.getLayer('${handle.lineLayerId}'))m.addLayer($lineSpec); + if(!m.getLayer('${handle.fillLayerId}'))$fillAdd + if(!m.getLayer('${handle.lineLayerId}'))$lineAdd }catch(e){ if(tries++<30)setTimeout(apply,150); } } apply(); diff --git a/src/main/java/com/mapconductor/longdo/groundimage/LongdoGroundImageOverlayRenderer.kt b/src/main/java/com/mapconductor/longdo/groundimage/LongdoGroundImageOverlayRenderer.kt index 0157ef3..3ab1b1d 100644 --- a/src/main/java/com/mapconductor/longdo/groundimage/LongdoGroundImageOverlayRenderer.kt +++ b/src/main/java/com/mapconductor/longdo/groundimage/LongdoGroundImageOverlayRenderer.kt @@ -1,10 +1,13 @@ package com.mapconductor.longdo.groundimage import com.longdo.sdk3.LongdoMap +import com.mapconductor.core.controller.OverlayKind import com.mapconductor.core.features.GeoRectBounds import com.mapconductor.core.groundimage.GroundImageEntityInterface import com.mapconductor.core.groundimage.GroundImageOverlayRendererInterface import com.mapconductor.core.groundimage.GroundImageState +import com.mapconductor.longdo.LongdoOverlayStacking +import com.mapconductor.longdo.awaitPageLayers import org.json.JSONObject import java.io.ByteArrayOutputStream import android.graphics.Bitmap @@ -29,9 +32,17 @@ import android.util.Base64 class LongdoGroundImageOverlayRenderer( private val longdoMap: LongdoMap, ) : GroundImageOverlayRendererInterface { + /** + * Returns once the layers are on the page's map, so the ground images' + * `onAdded` comes after they are (see [com.mapconductor.longdo.PageLayerWait]). + */ override suspend fun onAdd( data: List, - ): List = data.map { addGroundImage(it.state) } + ): List { + val handles = data.map { addGroundImage(it.state) } + longdoMap.awaitPageLayers(handles.mapNotNull { it?.layerId }) + return handles + } override suspend fun onChange( data: List>, @@ -146,6 +157,8 @@ class LongdoGroundImageOverlayRenderer( .put("paint", JSONObject().put("raster-opacity", handle.opacity)) .put("layout", JSONObject().put("visibility", "visible")) .toString() + // GroundImage の帯(ラスターの上、ポリゴンの下)。 + val layerAdd = LongdoOverlayStacking.addLayerJs(layerSpec, OverlayKind.GroundImage) return """ (function(){var m=map.Renderer; if(!m)return; var tries=0; @@ -154,7 +167,7 @@ class LongdoGroundImageOverlayRenderer( if(!m.getSource('${handle.sourceId}')) m.addSource('${handle.sourceId}', {type:'image',url:'${handle.imageUrl}',coordinates:${handle.coordinatesJson}}); - if(!m.getLayer('${handle.layerId}'))m.addLayer($layerSpec); + if(!m.getLayer('${handle.layerId}'))$layerAdd }catch(e){ if(tries++<30)setTimeout(apply,150); } } apply(); diff --git a/src/main/java/com/mapconductor/longdo/marker/LongdoMarkerTileRenderer.kt b/src/main/java/com/mapconductor/longdo/marker/LongdoMarkerTileRenderer.kt index ae3897d..f302a6a 100644 --- a/src/main/java/com/mapconductor/longdo/marker/LongdoMarkerTileRenderer.kt +++ b/src/main/java/com/mapconductor/longdo/marker/LongdoMarkerTileRenderer.kt @@ -1,5 +1,8 @@ package com.mapconductor.longdo.marker +import com.mapconductor.core.InternalMapConductorApi +import com.mapconductor.core.marker.MarkerHitPick +import androidx.compose.ui.geometry.Offset import com.mapconductor.core.features.GeoPointInterface import com.mapconductor.core.marker.MarkerEntity import com.mapconductor.core.marker.MarkerManager @@ -10,10 +13,10 @@ import com.mapconductor.core.raster.RasterLayerSource import com.mapconductor.core.raster.RasterLayerState import com.mapconductor.core.raster.TileScheme import com.mapconductor.core.tileserver.TileServerRegistry -import java.util.UUID import kotlin.math.cos import kotlin.math.pow import kotlin.math.sqrt +import java.util.UUID /** * 大量マーカー(「Bunch of Markers」等)を、他モジュール(maplibre / maptiler 等)と同じ方式= @@ -95,8 +98,31 @@ class LongdoMarkerTileRenderer( } /** - * タップ座標付近のマーカーを返す(クリック用の簡易ヒットテスト)。 + * タップ座標に当たるマーカーを返す。選び方はコアの [MarkerHitPick.pick] と同じで、 + * 指の下にアイコンかラベルが描かれているマーカーが、先端の近い別のマーカーより優先する。 + * + * @param project 地理座標をビューの画面座標へ投影する(holder の toScreenOffset)。 + */ + @OptIn(InternalMapConductorApi::class) + fun findMarkerAt( + tap: GeoPointInterface, + project: (GeoPointInterface) -> Offset?, + ): MarkerState? { + if (markers.isEmpty()) return null + val touchScreen = project(tap) ?: return null + val bounds = MarkerHitPick.searchBounds(tap, touchScreen, project) ?: return null + val candidates = markers.filter { bounds.contains(it.position) } + return MarkerHitPick.pickBy(touchScreen, candidates, { it }, project) + } + + /** + * 旧来の判定(先端からの距離だけを見る)。ラベルやアイコンの大きさを見ないので、 + * 指の下に描かれているマーカーより先端の近い別のマーカーを選ぶことがある。 */ + @Deprecated( + "先端からの距離だけで選ぶ旧来の判定。findMarkerAt(tap, project) を使う。", + ReplaceWith("findMarkerAt(tap, project)"), + ) fun findMarkerAt( tap: GeoPointInterface, nativeZoom: Double, @@ -131,6 +157,7 @@ class LongdoMarkerTileRenderer( cacheSizeBytes = markerTiling.cacheSize, debugTileOverlay = markerTiling.debugTileOverlay, iconScaleCallback = markerTiling.iconScaleCallback, + declutterPx = markerTiling.declutterPx, ) tileRenderer = renderer tileServer.register(gid, renderer) diff --git a/src/main/java/com/mapconductor/longdo/marker/MarkerIdIndex.kt b/src/main/java/com/mapconductor/longdo/marker/MarkerIdIndex.kt new file mode 100644 index 0000000..65d7804 --- /dev/null +++ b/src/main/java/com/mapconductor/longdo/marker/MarkerIdIndex.kt @@ -0,0 +1,28 @@ +package com.mapconductor.longdo.marker + +import com.mapconductor.core.marker.MarkerState + +/** + * The ids of a marker list, rebuilt only when the list itself is replaced. + * + * `hasMarker` is asked once per marker after every composition (that is how + * `MarkerState.onAdded` finds out what is on the map) and on every in-place + * change. A linear search of the list made the first of those quadratic: 1e5 + * markers, 1e10 comparisons. + */ +internal class MarkerIdIndex { + private var list: List? = null + private var ids: Set = emptySet() + + @Synchronized + fun contains( + markers: List, + id: String, + ): Boolean { + if (markers !== list) { + ids = markers.mapTo(HashSet(markers.size * 2)) { it.id } + list = markers + } + return id in ids + } +} diff --git a/src/main/java/com/mapconductor/longdo/polygon/LongdoPolygonController.kt b/src/main/java/com/mapconductor/longdo/polygon/LongdoPolygonController.kt index 55cc043..0683c06 100644 --- a/src/main/java/com/mapconductor/longdo/polygon/LongdoPolygonController.kt +++ b/src/main/java/com/mapconductor/longdo/polygon/LongdoPolygonController.kt @@ -17,6 +17,8 @@ class LongdoPolygonController( ) : PolygonController(polygonManager, renderer) { /** 既知のポリゴンを再適用する(地図 `ready` 後の復元用)。 */ fun reapply() { - renderer.reapply(polygonManager.allEntities().map { it.polygon }) + // Polygons drawn as tiles (PolygonController.tiler) have no handle. + @Suppress("USELESS_CAST") + renderer.reapply(polygonManager.allEntities().mapNotNull { it.polygon as LongdoPolygonHandle? }) } } diff --git a/src/main/java/com/mapconductor/longdo/polygon/LongdoPolygonOverlayRenderer.kt b/src/main/java/com/mapconductor/longdo/polygon/LongdoPolygonOverlayRenderer.kt index 7bf277f..db2305d 100644 --- a/src/main/java/com/mapconductor/longdo/polygon/LongdoPolygonOverlayRenderer.kt +++ b/src/main/java/com/mapconductor/longdo/polygon/LongdoPolygonOverlayRenderer.kt @@ -2,12 +2,15 @@ package com.mapconductor.longdo.polygon import androidx.compose.ui.graphics.toArgb import com.longdo.sdk3.LongdoMap +import com.mapconductor.core.controller.OverlayKind import com.mapconductor.core.geometry.OverlayGeoJson import com.mapconductor.core.geometry.buildUnwrappedPolygonRings import com.mapconductor.core.polygon.PolygonEntityInterface import com.mapconductor.core.polygon.PolygonOverlayRendererInterface import com.mapconductor.core.polygon.PolygonState import com.mapconductor.core.polygon.unionHoles +import com.mapconductor.longdo.LongdoOverlayStacking +import com.mapconductor.longdo.awaitPageLayers import org.json.JSONObject /** @@ -21,9 +24,17 @@ import org.json.JSONObject class LongdoPolygonOverlayRenderer( private val longdoMap: LongdoMap, ) : PolygonOverlayRendererInterface { + /** + * Returns once the layers are on the page's map, so the polygons' + * `onAdded` comes after they are (see [com.mapconductor.longdo.PageLayerWait]). + */ override suspend fun onAdd( data: List, - ): List = data.map { addPolygon(it.state) } + ): List { + val handles = data.map { addPolygon(it.state) } + longdoMap.awaitPageLayers(handles.filterNotNull().flatMap { listOf(it.fillLayerId, it.lineLayerId) }) + return handles + } override suspend fun onChange( data: List>, @@ -56,8 +67,12 @@ class LongdoPolygonOverlayRenderer( handles.forEach { runJs(addPolygonJs(it)) } } + /** 層の id → zIndex(帯の中の順)。handle は公開型なので持たせずここで覚える。 */ + private val zIndexByLayer = java.util.concurrent.ConcurrentHashMap() + private fun addPolygon(state: PolygonState): LongdoPolygonHandle? { val feature = buildGeoJson(state) ?: return null + zIndexByLayer["polygon-fill-${state.id}"] = state.zIndex val fillArgb = state.fillColor.toArgb() val strokeArgb = state.strokeColor.toArgb() val handle = @@ -140,6 +155,10 @@ class LongdoPolygonOverlayRenderer( .put("line-opacity", handle.strokeOpacity) .put("line-width", handle.strokeWidth), ).toString() + // ポリゴンの帯。帯の中は zIndex の順、輪郭は塗りの直後。 + val z = zIndexByLayer[handle.fillLayerId] ?: 0 + val fillAdd = LongdoOverlayStacking.addLayerJs(fillSpec, OverlayKind.Polygon, z) + val lineAdd = LongdoOverlayStacking.addLayerJs(lineSpec, OverlayKind.Polygon, z) return """ (function(){var m=map.Renderer; if(!m)return; var tries=0; @@ -147,8 +166,8 @@ class LongdoPolygonOverlayRenderer( try{ if(!m.getSource('${handle.sourceId}')) m.addSource('${handle.sourceId}',{type:'geojson',data:${handle.featureJson}}); - if(!m.getLayer('${handle.fillLayerId}'))m.addLayer($fillSpec); - if(!m.getLayer('${handle.lineLayerId}'))m.addLayer($lineSpec); + if(!m.getLayer('${handle.fillLayerId}'))$fillAdd + if(!m.getLayer('${handle.lineLayerId}'))$lineAdd }catch(e){ if(tries++<30)setTimeout(apply,150); } } apply(); diff --git a/src/main/java/com/mapconductor/longdo/polyline/LongdoPolylineController.kt b/src/main/java/com/mapconductor/longdo/polyline/LongdoPolylineController.kt index e503349..dff3eef 100644 --- a/src/main/java/com/mapconductor/longdo/polyline/LongdoPolylineController.kt +++ b/src/main/java/com/mapconductor/longdo/polyline/LongdoPolylineController.kt @@ -14,8 +14,8 @@ class LongdoPolylineController( override val renderer: LongdoPolylineOverlayRenderer, polylineManager: PolylineManagerInterface = PolylineManager(), ) : PolylineController(polylineManager, renderer) { - /** 既知のポリラインを再適用する(地図 `ready` 後の復元用)。 */ + /** 既知のポリラインを再適用する(地図 `ready` 後の復元用)。タイルで描く線(ハンドル無し)は飛ばす。 */ fun reapply() { - renderer.reapply(polylineManager.allEntities().map { it.polyline }) + renderer.reapply(polylineManager.allEntities().mapNotNull { it.polyline as LongdoPolylineHandle? }) } } diff --git a/src/main/java/com/mapconductor/longdo/polyline/LongdoPolylineOverlayRenderer.kt b/src/main/java/com/mapconductor/longdo/polyline/LongdoPolylineOverlayRenderer.kt index b4e08ea..43a2e40 100644 --- a/src/main/java/com/mapconductor/longdo/polyline/LongdoPolylineOverlayRenderer.kt +++ b/src/main/java/com/mapconductor/longdo/polyline/LongdoPolylineOverlayRenderer.kt @@ -2,11 +2,14 @@ package com.mapconductor.longdo.polyline import androidx.compose.ui.graphics.toArgb import com.longdo.sdk3.LongdoMap +import com.mapconductor.core.controller.OverlayKind import com.mapconductor.core.geometry.OverlayGeoJson import com.mapconductor.core.geometry.buildUnwrappedPolylinePath import com.mapconductor.core.polyline.PolylineEntityInterface import com.mapconductor.core.polyline.PolylineOverlayRendererInterface import com.mapconductor.core.polyline.PolylineState +import com.mapconductor.longdo.LongdoOverlayStacking +import com.mapconductor.longdo.awaitPageLayers import org.json.JSONObject /** @@ -19,9 +22,17 @@ import org.json.JSONObject class LongdoPolylineOverlayRenderer( private val longdoMap: LongdoMap, ) : PolylineOverlayRendererInterface { + /** + * Returns once the layers are on the page's map, so the polylines' + * `onAdded` comes after they are (see [com.mapconductor.longdo.PageLayerWait]). + */ override suspend fun onAdd( data: List, - ): List = data.map { addLine(it.state) } + ): List { + val handles = data.map { addLine(it.state) } + longdoMap.awaitPageLayers(handles.mapNotNull { it?.layerId }) + return handles + } override suspend fun onChange( data: List>, @@ -52,8 +63,12 @@ class LongdoPolylineOverlayRenderer( handles.forEach { runJs(addLineJs(it)) } } + /** 層の id → zIndex(帯の中の順)。 */ + private val zIndexByLayer = java.util.concurrent.ConcurrentHashMap() + private fun addLine(state: PolylineState): LongdoPolylineHandle? { val feature = buildGeoJson(state) ?: return null + zIndexByLayer["polyline-layer-${state.id}"] = state.zIndex val argb = state.strokeColor.toArgb() val handle = LongdoPolylineHandle( @@ -122,6 +137,8 @@ class LongdoPolylineOverlayRenderer( .put("line-opacity", handle.opacity) .put("line-width", handle.width), ).toString() + // ポリラインの帯。 + val layerAdd = LongdoOverlayStacking.addLayerJs(layerSpec, OverlayKind.Polyline, zIndexByLayer[handle.layerId] ?: 0) return """ (function(){var m=map.Renderer; if(!m)return; var tries=0; @@ -129,7 +146,7 @@ class LongdoPolylineOverlayRenderer( try{ if(!m.getSource('${handle.sourceId}')) m.addSource('${handle.sourceId}',{type:'geojson',data:${handle.featureJson}}); - if(!m.getLayer('${handle.layerId}'))m.addLayer($layerSpec); + if(!m.getLayer('${handle.layerId}'))$layerAdd }catch(e){ if(tries++<30)setTimeout(apply,150); } } apply(); diff --git a/src/test/java/com/mapconductor/longdo/PageLayerWaitTest.kt b/src/test/java/com/mapconductor/longdo/PageLayerWaitTest.kt new file mode 100644 index 0000000..c8884ea --- /dev/null +++ b/src/test/java/com/mapconductor/longdo/PageLayerWaitTest.kt @@ -0,0 +1,109 @@ +package com.mapconductor.longdo + +import kotlinx.coroutines.runBlocking +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +/** + * [PageLayerWait] returns only once the page's map has every layer, which is + * what holds an overlay's `onAdded` until it is really on the map. + * + * The page is faked: [FakePage] answers the script the way the real one does, + * from a set of layer ids that tests add to between polls. + */ +class PageLayerWaitTest { + /** Answers [PageLayerWait.script] from [layers], counting the calls. */ + private class FakePage { + val layers = mutableSetOf() + val asked = mutableListOf>() + var onAsk: (Int) -> Unit = {} + + fun evaluate(js: String): String { + val ids = + Regex("var ids=\\[(.*?)\\];") + .find(js)!! + .groupValues[1] + .split(',') + .filter { it.isNotEmpty() } + .map { it.trim('"') } + asked += ids + onAsk(asked.size) + val present = ids.takeWhile { it in layers }.size + // evaluateJavascript hands a string value back JSON-quoted. + return "\"$present\"" + } + } + + @Test + fun returnsAtOnceForNoLayers() = + runBlocking { + var calls = 0 + assertTrue( + PageLayerWait.await(emptyList()) { + calls++ + "0" + }, + ) + assertEquals(0, calls) + } + + @Test + fun waitsUntilEveryLayerIsOnTheMap() = + runBlocking { + val page = FakePage() + // The layers arrive over three polls, as the SDK's queue empties. + page.onAsk = { n -> + if (n == 2) page.layers += "a" + if (n == 3) page.layers += listOf("b", "c") + } + val done = PageLayerWait.await(listOf("a", "b", "c"), intervalMs = 1) { page.evaluate(it) } + assertTrue(done) + assertEquals(listOf("a", "b", "c"), page.layers.sorted()) + // Asks again only for the layers still missing. + assertEquals(listOf(listOf("a", "b", "c"), listOf("a", "b", "c"), listOf("b", "c")), page.asked) + } + + @Test + fun givesUpAfterTheTimeout() = + runBlocking { + val page = FakePage() + page.layers += "a" + val done = PageLayerWait.await(listOf("a", "never"), timeoutMs = 100, intervalMs = 5) { page.evaluate(it) } + assertFalse(done) + assertTrue(page.asked.size > 1) + } + + @Test + fun aFailedAskCountsAsNothingYet() = + runBlocking { + var calls = 0 + val done = + PageLayerWait.await(listOf("a"), intervalMs = 1) { + calls++ + when (calls) { + 1 -> throw IllegalStateException("bridge not loaded") + 2 -> null + else -> "\"1\"" + } + } + assertTrue(done) + assertEquals(3, calls) + } + + @Test + fun parseReadsTheCountQuotedOrNot() { + assertEquals(3, PageLayerWait.parse("\"3\"")) + assertEquals(3, PageLayerWait.parse("3")) + assertEquals(0, PageLayerWait.parse(null)) + assertEquals(0, PageLayerWait.parse("null")) + } + + @Test + fun idsAreQuotedForTheScript() { + val js = PageLayerWait.script(listOf("polygon-fill-a\"b", "x\\y")) + assertTrue(js, js.contains("[\"polygon-fill-a\\\"b\",\"x\\\\y\"]")) + assertTrue(js.contains(PageLayerWait.MAP_EXPR)) + } +}