From bdc5318c1c71980800244bc00bb03a8222d52cb9 Mon Sep 17 00:00:00 2001 From: Masashi Katsumata Date: Sat, 12 Sep 2026 14:34:53 +0900 Subject: [PATCH 01/23] Make bearing a clockwise map rotation (#12) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Make bearing a clockwise map rotation bearing を「値を増やすと地図が時計回りに回る」向きに統一し、ネイティブ SDK との変換をコアの CameraBearing に集約する。 * ci: build the core module from the matching branch コアの未マージ/未リリースな変更に追随する PR を、コアが先に取り込まれるのを待たずに検証できるようにする。同名ブランチが無ければ従来どおり既定のコアを使う。 * fix: point material3 at its own version line material3 は compose-ui とは別のバージョン系列で、composeLibs(1.7.8)を流用すると存在しない material3:1.7.8 を要求して sample-app のクラスパスごと解決に失敗する。集約ビルド(android-sdk)の catalog と同じ 1.4.0 に合わせる。 * fix: declare material-icons-core for the sample app sample-app が Icons.AutoMirrored を使うが、material3 は material-icons を推移的に持ってこないため単体ビルドで Unresolved reference 'Icons' になる。版は compose BOM 任せで、集約ビルドの catalog と同じ形にする。 --- .github/workflows/build.yml | 25 +++++++++++++++++-- gradle/libs.versions.toml | 8 +++++- sample-app/build.gradle.kts | 1 + .../mapconductor/here/MapCameraPosition.kt | 11 ++++---- 4 files changed, 37 insertions(+), 8 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 1c511f7..3e55946 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -54,8 +54,29 @@ jobs: fi - 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 .. @@ -69,7 +90,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/gradle/libs.versions.toml b/gradle/libs.versions.toml index 353e813..a701d59 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -1,6 +1,9 @@ [versions] coroutines = "1.9.0" composeLibs = "1.7.8" +# material3 は compose-ui とは別のバージョン系列。composeLibs(ui 系)を流用すると +# 存在しない material3:1.7.8 を要求してクラスパスごと解決に失敗する。 +material3 = "1.4.0" agp = "9.2.1" kotlin = "2.0.21" @@ -27,7 +30,10 @@ androidx-lifecycle-common-java8 = { group = "androidx.lifecycle", name = "lifecy # 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" } +# sample-app が Icons.AutoMirrored を使う。material3 は material-icons を推移的に持ってこないので +# 明示的に足す。版は compose BOM 任せ(集約ビルドの catalog と同じ形)。 +androidx-material-icons-core = { group = "androidx.compose.material", name = "material-icons-core" } androidx-ui-tooling = { group = "androidx.compose.ui", name = "ui-tooling", version.ref = "composeLibs" } # Test diff --git a/sample-app/build.gradle.kts b/sample-app/build.gradle.kts index a995c93..7c9ef69 100644 --- a/sample-app/build.gradle.kts +++ b/sample-app/build.gradle.kts @@ -64,6 +64,7 @@ dependencies { implementation(libs.androidx.ui) implementation(libs.androidx.ui.tooling.preview) implementation(libs.androidx.material3) + implementation(libs.androidx.material.icons.core) debugImplementation(platform(libs.androidx.compose.bom)) debugImplementation(libs.androidx.ui.tooling) } diff --git a/src/main/java/com/mapconductor/here/MapCameraPosition.kt b/src/main/java/com/mapconductor/here/MapCameraPosition.kt index 90150a7..94e9ead 100644 --- a/src/main/java/com/mapconductor/here/MapCameraPosition.kt +++ b/src/main/java/com/mapconductor/here/MapCameraPosition.kt @@ -7,6 +7,7 @@ import com.here.sdk.mapview.MapCameraUpdate import com.here.sdk.mapview.MapCameraUpdateFactory import com.here.sdk.mapview.MapMeasure import com.mapconductor.core.features.GeoPoint +import com.mapconductor.core.map.CameraBearing import com.mapconductor.core.map.MapCameraPosition import com.mapconductor.core.map.MapCameraPositionInterface import com.mapconductor.core.spherical.Spherical @@ -30,7 +31,7 @@ internal fun MapCameraPosition.toHereDisplayCamera(): HereDisplayCamera { target = GeoPoint.from(position), tiltDeg = tilt, hereZoomLevel = ZoomAltitudeConverter.googleZoomToHereZoom(zoom, position.latitude), - bearing = bearing, + bearing = CameraBearing.toNativeHeading(bearing), ) } // tilt < 0: HERE cannot represent upward pitch directly. @@ -40,13 +41,13 @@ internal fun MapCameraPosition.toHereDisplayCamera(): HereDisplayCamera { val hereZoomOrig = ZoomAltitudeConverter.googleZoomToHereZoom(zoom, position.latitude) val altitude = converter.zoomLevelToAltitude(hereZoomOrig, position.latitude, 0.0) val distanceForward = altitude * tan(tiltAbsRad) - val target = Spherical.computeOffset(position, distanceForward, bearing) + val target = Spherical.computeOffset(position, distanceForward, CameraBearing.toNativeHeading(bearing)) val adjustedHereZoom = converter.altitudeToZoomLevel(altitude / cos(tiltAbsRad), target.latitude, 0.0) return HereDisplayCamera( target = target, tiltDeg = tiltAbsDeg, hereZoomLevel = adjustedHereZoom, - bearing = bearing, + bearing = CameraBearing.toNativeHeading(bearing), ) } @@ -93,7 +94,7 @@ internal fun MapCamera.State.toMapCameraPosition(logicalTiltHint: Double?): MapC return MapCameraPosition( position = position, zoom = ourZoom, - bearing = orientationAtTarget.bearing, + bearing = CameraBearing.bearingFromNativeHeading(orientationAtTarget.bearing), tilt = pitch, visibleRegion = null, ) @@ -114,7 +115,7 @@ internal fun MapCamera.State.toMapCameraPosition(logicalTiltHint: Double?): MapC return MapCameraPosition( position = originalCenter, zoom = originalGoogleZoom, - bearing = bear, + bearing = CameraBearing.bearingFromNativeHeading(bear), tilt = -pitchAbsDeg, visibleRegion = null, ) From 5f073a9db99b671a0d5cbae53ee4e596caf2608e Mon Sep 17 00:00:00 2001 From: Masashi Katsumata Date: Thu, 17 Sep 2026 05:32:26 +0900 Subject: [PATCH 02/23] Record the cancellable renderTile overload MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit TileProviderInterface gained renderTile(request, isCancelled) as a default method in android-sdk-core, so every implementor's surface picks it up. An addition, not a break — the existing overload is untouched. --- api/android-for-here.api | 1 + 1 file changed, 1 insertion(+) diff --git a/api/android-for-here.api b/api/android-for-here.api index 2c009fb..49d14d6 100644 --- a/api/android-for-here.api +++ b/api/android-for-here.api @@ -413,6 +413,7 @@ final class com.mapconductor.here.raster.HereRasterTileProxyProvider implements public static final com.mapconductor.here.raster.HereRasterTileProxyProvider$Companion Companion; public com.mapconductor.here.raster.HereRasterTileProxyProvider(com.mapconductor.core.raster.RasterLayerState); public byte[] renderTile(com.mapconductor.core.tileserver.TileRequest); + public byte[] renderTile(com.mapconductor.core.tileserver.TileRequest, kotlin.jvm.functions.Function0); } public final class com.mapconductor.here.raster.HereRasterTileProxyProvider$Companion { } From 7bd524fc2bd4e881130224f5d9ecbea896bd8810 Mon Sep 17 00:00:00 2001 From: Masashi Katsumata Date: Mon, 21 Sep 2026 23:44:25 +0900 Subject: [PATCH 03/23] Pass declutterPx through to the marker tile renderer MarkerTilingOptions.declutterPx existed and samples set it, but every controller dropped it on the floor when constructing MarkerTileRenderer, so the renderer ran with 0 and drew every marker on every tile. On a slow device that is the difference between an overview tile costing 538ms and 79ms (SO-02L, 144k markers, z10, MarkerTileRenderBenchmark) -- and the drawn result now actually matches what iOS and react show for the same options. --- .../here/marker/HereMarkerController.kt | 707 +++++++++--------- 1 file changed, 354 insertions(+), 353 deletions(-) diff --git a/src/main/java/com/mapconductor/here/marker/HereMarkerController.kt b/src/main/java/com/mapconductor/here/marker/HereMarkerController.kt index c65698c..1e28324 100644 --- a/src/main/java/com/mapconductor/here/marker/HereMarkerController.kt +++ b/src/main/java/com/mapconductor/here/marker/HereMarkerController.kt @@ -1,353 +1,354 @@ -package com.mapconductor.here.marker - -import com.mapconductor.core.controller.OnCameraChangeReceiverInterface -import com.mapconductor.core.map.MapCameraPosition -import com.mapconductor.core.marker.AbstractMarkerController -import com.mapconductor.core.marker.BitmapIcon -import com.mapconductor.core.marker.DefaultMarkerIcon -import com.mapconductor.core.marker.MarkerEntity -import com.mapconductor.core.marker.MarkerEntityInterface -import com.mapconductor.core.marker.MarkerIngestionEngine -import com.mapconductor.core.marker.MarkerManager -import com.mapconductor.core.marker.MarkerOverlayRendererInterface -import com.mapconductor.core.marker.MarkerState -import com.mapconductor.core.marker.MarkerTileRasterLayerCallback -import com.mapconductor.core.marker.MarkerTileRenderer -import com.mapconductor.core.marker.MarkerTilingOptions -import com.mapconductor.core.marker.MarkerViewportSwitch -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 com.mapconductor.here.HereActualMarker -import com.mapconductor.here.HereViewHolder -import java.util.UUID -import android.os.SystemClock -import kotlinx.coroutines.launch -import kotlinx.coroutines.sync.withPermit - -class HereMarkerController private constructor( - markerManager: MarkerManager, - renderer: HereMarkerRenderer, - private val markerTiling: MarkerTilingOptions, -) : AbstractMarkerController( - markerManager = markerManager, - renderer = renderer, - ), - OnCameraChangeReceiverInterface { - private val defaultMarkerIcon: BitmapIcon = DefaultMarkerIcon().toBitmapIcon() - private val tiledMarkerIds = LinkedHashSet() - - @Volatile - private var lastKnownZoom: Double = 0.0 - - private val tileServer = TileServerRegistry.get() - private var markerTileRenderer: MarkerTileRenderer? = null - private var markerTileGroupId: String? = null - private var markerTileRasterLayerState: RasterLayerState? = null - private var rasterLayerCallback: MarkerTileRasterLayerCallback? = null - private var cacheVersion: Int = 0 - - /** - * ビューポート内が少ないときだけタイルをやめてネイティブマーカーで描く切り替え器。 - * - * レンダラ/マネージャ/semaphore を共有するので、コントローラと同じ排他の下で動く。 - */ - private val viewportSwitch = - MarkerViewportSwitch( - markerManager = markerManager, - renderer = renderer, - defaultMarkerIcon = defaultMarkerIcon, - semaphore = semaphore, - policy = markerTiling.viewport, - setTileLayerVisible = ::setTileLayerVisible, - invalidateTiles = ::updateRasterLayerSource, - ) - - fun setRasterLayerCallback(callback: MarkerTileRasterLayerCallback?) { - rasterLayerCallback = callback - } - - override suspend fun add(data: List) { - // ingest はタイル担当 entity を marker = null で登録し直すので、先に昇格を戻す。 - // semaphore は再入不可なので withPermit の外で呼ぶこと。 - viewportSwitch.retract() - semaphore.withPermit { - val tilingEnabled = - markerTiling.enabled && data.size >= markerManager.minMarkerCount - val result = - MarkerIngestionEngine.ingest( - data = data, - markerManager = markerManager, - renderer = renderer, - defaultMarkerIcon = defaultMarkerIcon, - tilingEnabled = tilingEnabled, - tiledMarkerIds = tiledMarkerIds, - shouldTile = { state -> !state.draggable && state.getAnimation() == null }, - ) - - if (result.tiledDataChanged) { - syncTiledOverlay() - } else if (result.hasTiledMarkers) { - if (markerTileRenderer == null || markerTileRasterLayerState == null) { - syncTiledOverlay() - } - } else { - removeTileOverlay() - } - } - viewportSwitch.requestReapply() - } - - override suspend fun update(state: MarkerState) { - if (!markerManager.hasEntity(state.id)) return - - // 昇格中の 1 件なら先に取り下げる(下で marker = null 登録があるため)。 - // 昇格していないマーカー(ドラッグ中など)では何もしないので、ドラッグは素通りする。 - if (viewportSwitch.isPromoted(state.id)) viewportSwitch.release(state.id) - - val prevEntity = markerManager.getEntity(state.id) ?: return - val currentFinger = state.fingerPrint() - val prevFinger = prevEntity.fingerPrint - if (currentFinger == prevFinger) return - - semaphore.withPermit { - val tilingEnabled = - markerTiling.enabled && markerManager.allEntities().size >= markerManager.minMarkerCount - val wantsTiled = tilingEnabled && !state.draggable && state.getAnimation() == null - val wasTiled = tiledMarkerIds.contains(state.id) - val markerIcon = state.icon?.toBitmapIcon() ?: defaultMarkerIcon - - if (wantsTiled) { - if (!wasTiled) { - prevEntity.marker?.let { renderer.onRemove(listOf(prevEntity)) } - tiledMarkerIds.add(state.id) - } - markerManager.updateEntity( - MarkerEntity( - marker = null, - state = state, - visible = prevEntity.visible, - isRendered = true, - // tiling を立てないと MarkerTileRenderer の絞り込みから漏れ、 - // タイル昇格したのにタイルへ描かれないマーカーになる。 - tiling = true, - ), - ) - renderer.onPostProcess() - syncTiledOverlay() - return@withPermit - } - - if (wasTiled) { - tiledMarkerIds.remove(state.id) - } - - val params = - object : MarkerOverlayRendererInterface.ChangeParamsInterface { - override val current: MarkerEntityInterface = - MarkerEntity( - marker = prevEntity.marker, - state = state, - visible = prevEntity.visible, - isRendered = true, - ) - override val bitmapIcon: BitmapIcon = markerIcon - override val prev: MarkerEntityInterface = prevEntity - } - val markers = renderer.onChange(listOf(params)) - markers.firstOrNull()?.let { actual -> - markerManager.updateEntity( - MarkerEntity( - marker = actual, - state = state, - visible = prevEntity.visible, - isRendered = true, - ), - ) - if (prevFinger.animation != currentFinger.animation) { - state.getAnimation()?.let { renderer.onAnimate(markerManager.getEntity(state.id)!!) } - } - } - renderer.onPostProcess() - - if (tiledMarkerIds.isNotEmpty()) { - syncTiledOverlay() - } else { - removeTileOverlay() - } - } - viewportSwitch.requestReapply() - } - - override suspend fun clear() { - viewportSwitch.destroy() - semaphore.withPermit { - val entities = markerManager.allEntities() - val toRemove = entities.filter { it.marker != null } - if (toRemove.isNotEmpty()) { - renderer.onRemove(toRemove) - } - markerManager.clear() - tiledMarkerIds.clear() - removeTileOverlay() - } - } - - override suspend fun onCameraChanged(mapCameraPosition: MapCameraPosition) { - // 判定と昇格は debounce したうえで切り替え器の中で走る(パン中は動かない)。 - viewportSwitch.onCameraChanged(mapCameraPosition) - lastKnownZoom = mapCameraPosition.zoom - } - - /** - * マーカータイルのラスターレイヤの表示だけを切り替える。 - * - * source(URL)には触らない。触るとタイルを取り直すことになり、切り替えのたびに - * タイルキャッシュを捨てるのと同じになる。 - */ - private suspend fun setTileLayerVisible(visible: Boolean) { - val current = markerTileRasterLayerState ?: return - if (current.visible == visible) return - val newState = current.copy(visible = visible) - markerTileRasterLayerState = newState - rasterLayerCallback?.onRasterLayerUpdate(newState) - } - - override fun destroy() { - viewportSwitch.destroy() - // Clean up tile server registration - // Unregister this map's route only. Never stop the server here: it is - // a process-wide singleton shared by all map controllers and overlay - // modules; stopping it breaks tile loading for every other live map. - markerTileGroupId?.let { groupId -> - tileServer.unregister(groupId) - } - markerTileGroupId = null - markerTileRenderer = null - - (renderer as HereMarkerRenderer).coroutine.launch { - rasterLayerCallback?.onRasterLayerUpdate(null) - } - markerTileRasterLayerState = null - super.destroy() - } - - private suspend fun updateRasterLayerSource() { - val groupId = markerTileGroupId ?: return - val tileRenderer = markerTileRenderer ?: return - val oldState = markerTileRasterLayerState ?: return - cacheVersion = (cacheVersion + 1) and 0x7fffffff - tileRenderer.invalidate() - val cacheBuster = "${cacheVersion}_${SystemClock.elapsedRealtime()}" - - val newState = - oldState.copy( - source = - RasterLayerSource.UrlTemplate( - template = "${tileServer.urlTemplate(groupId, tileRenderer.tileSize)}?cb=$cacheBuster", - tileSize = tileRenderer.tileSize, - maxZoom = 22, - scheme = TileScheme.XYZ, - ), - id = oldState.id, - ) - markerTileRasterLayerState = newState - rasterLayerCallback?.onRasterLayerUpdate(newState) - } - - private suspend fun syncTiledOverlay() { - if (tiledMarkerIds.isEmpty()) { - removeTileOverlay() - return - } - if (!markerTiling.enabled) { - removeTileOverlay() - tiledMarkerIds.clear() - return - } - - getOrCreateTileRenderer() - updateRasterLayerSource() - } - - private fun getOrCreateTileRenderer(): MarkerTileRenderer { - markerTileRenderer?.let { return it } - - val groupId = UUID.randomUUID().toString() - markerTileGroupId = groupId - - // HERE displays one raster tile over 512 logical px, so render tiles at - // 512 with no extra icon scale: icons match regular MapMarker size 1:1. - // (256 gets upscaled 2x -> icons appear double size; 1024 doubles the - // render/PNG-encode cost for no visible gain.) - val tileScale = 1.0 - val outputTileSize = 512 - - cacheVersion = (cacheVersion + 1) and 0x7fffffff - val tileRenderer = - MarkerTileRenderer( - markerManager = markerManager, - tileSize = outputTileSize, - cacheSizeBytes = markerTiling.cacheSize, - debugTileOverlay = markerTiling.debugTileOverlay, - iconScaleCallback = markerTiling.iconScaleCallback, - extraIconScale = tileScale, - ) - markerTileRenderer = tileRenderer - - tileServer.register(groupId, tileRenderer) - - markerTileRasterLayerState = - RasterLayerState( - id = "marker-tile-$groupId", - source = - RasterLayerSource.UrlTemplate( - template = "${tileServer.urlTemplate(groupId, tileRenderer.tileSize)}?cb=$cacheVersion", - tileSize = tileRenderer.tileSize, - maxZoom = 22, - scheme = TileScheme.XYZ, - ), - opacity = 1.0f, - visible = true, - ) - - return tileRenderer - } - - private suspend fun removeTileOverlay() { - markerTileGroupId?.let { groupId -> - tileServer.unregister(groupId) - } - markerTileGroupId = null - markerTileRenderer = null - - rasterLayerCallback?.onRasterLayerUpdate(null) - markerTileRasterLayerState = null - } - - companion object { - fun create( - holder: HereViewHolder, - markerTiling: MarkerTilingOptions = MarkerTilingOptions.Default, - ): HereMarkerController { - val renderer = - HereMarkerRenderer( - holder = holder, - ) - val markerManager = - MarkerManager.defaultManager( - minMarkerCount = markerTiling.minMarkerCount, - ) - val controller = - HereMarkerController( - markerManager = markerManager, - renderer = renderer, - markerTiling = markerTiling, - ) - // HERE camera zoom is updated via onCameraChanged; initialize a best-effort value. - controller.lastKnownZoom = holder.mapView.camera.state.zoomLevel - return controller - } - } -} +package com.mapconductor.here.marker + +import com.mapconductor.core.controller.OnCameraChangeReceiverInterface +import com.mapconductor.core.map.MapCameraPosition +import com.mapconductor.core.marker.AbstractMarkerController +import com.mapconductor.core.marker.BitmapIcon +import com.mapconductor.core.marker.DefaultMarkerIcon +import com.mapconductor.core.marker.MarkerEntity +import com.mapconductor.core.marker.MarkerEntityInterface +import com.mapconductor.core.marker.MarkerIngestionEngine +import com.mapconductor.core.marker.MarkerManager +import com.mapconductor.core.marker.MarkerOverlayRendererInterface +import com.mapconductor.core.marker.MarkerState +import com.mapconductor.core.marker.MarkerTileRasterLayerCallback +import com.mapconductor.core.marker.MarkerTileRenderer +import com.mapconductor.core.marker.MarkerTilingOptions +import com.mapconductor.core.marker.MarkerViewportSwitch +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 com.mapconductor.here.HereActualMarker +import com.mapconductor.here.HereViewHolder +import java.util.UUID +import android.os.SystemClock +import kotlinx.coroutines.launch +import kotlinx.coroutines.sync.withPermit + +class HereMarkerController private constructor( + markerManager: MarkerManager, + renderer: HereMarkerRenderer, + private val markerTiling: MarkerTilingOptions, +) : AbstractMarkerController( + markerManager = markerManager, + renderer = renderer, + ), + OnCameraChangeReceiverInterface { + private val defaultMarkerIcon: BitmapIcon = DefaultMarkerIcon().toBitmapIcon() + private val tiledMarkerIds = LinkedHashSet() + + @Volatile + private var lastKnownZoom: Double = 0.0 + + private val tileServer = TileServerRegistry.get() + private var markerTileRenderer: MarkerTileRenderer? = null + private var markerTileGroupId: String? = null + private var markerTileRasterLayerState: RasterLayerState? = null + private var rasterLayerCallback: MarkerTileRasterLayerCallback? = null + private var cacheVersion: Int = 0 + + /** + * ビューポート内が少ないときだけタイルをやめてネイティブマーカーで描く切り替え器。 + * + * レンダラ/マネージャ/semaphore を共有するので、コントローラと同じ排他の下で動く。 + */ + private val viewportSwitch = + MarkerViewportSwitch( + markerManager = markerManager, + renderer = renderer, + defaultMarkerIcon = defaultMarkerIcon, + semaphore = semaphore, + policy = markerTiling.viewport, + setTileLayerVisible = ::setTileLayerVisible, + invalidateTiles = ::updateRasterLayerSource, + ) + + fun setRasterLayerCallback(callback: MarkerTileRasterLayerCallback?) { + rasterLayerCallback = callback + } + + override suspend fun add(data: List) { + // ingest はタイル担当 entity を marker = null で登録し直すので、先に昇格を戻す。 + // semaphore は再入不可なので withPermit の外で呼ぶこと。 + viewportSwitch.retract() + semaphore.withPermit { + val tilingEnabled = + markerTiling.enabled && data.size >= markerManager.minMarkerCount + val result = + MarkerIngestionEngine.ingest( + data = data, + markerManager = markerManager, + renderer = renderer, + defaultMarkerIcon = defaultMarkerIcon, + tilingEnabled = tilingEnabled, + tiledMarkerIds = tiledMarkerIds, + shouldTile = { state -> !state.draggable && state.getAnimation() == null }, + ) + + if (result.tiledDataChanged) { + syncTiledOverlay() + } else if (result.hasTiledMarkers) { + if (markerTileRenderer == null || markerTileRasterLayerState == null) { + syncTiledOverlay() + } + } else { + removeTileOverlay() + } + } + viewportSwitch.requestReapply() + } + + override suspend fun update(state: MarkerState) { + if (!markerManager.hasEntity(state.id)) return + + // 昇格中の 1 件なら先に取り下げる(下で marker = null 登録があるため)。 + // 昇格していないマーカー(ドラッグ中など)では何もしないので、ドラッグは素通りする。 + if (viewportSwitch.isPromoted(state.id)) viewportSwitch.release(state.id) + + val prevEntity = markerManager.getEntity(state.id) ?: return + val currentFinger = state.fingerPrint() + val prevFinger = prevEntity.fingerPrint + if (currentFinger == prevFinger) return + + semaphore.withPermit { + val tilingEnabled = + markerTiling.enabled && markerManager.allEntities().size >= markerManager.minMarkerCount + val wantsTiled = tilingEnabled && !state.draggable && state.getAnimation() == null + val wasTiled = tiledMarkerIds.contains(state.id) + val markerIcon = state.icon?.toBitmapIcon() ?: defaultMarkerIcon + + if (wantsTiled) { + if (!wasTiled) { + prevEntity.marker?.let { renderer.onRemove(listOf(prevEntity)) } + tiledMarkerIds.add(state.id) + } + markerManager.updateEntity( + MarkerEntity( + marker = null, + state = state, + visible = prevEntity.visible, + isRendered = true, + // tiling を立てないと MarkerTileRenderer の絞り込みから漏れ、 + // タイル昇格したのにタイルへ描かれないマーカーになる。 + tiling = true, + ), + ) + renderer.onPostProcess() + syncTiledOverlay() + return@withPermit + } + + if (wasTiled) { + tiledMarkerIds.remove(state.id) + } + + val params = + object : MarkerOverlayRendererInterface.ChangeParamsInterface { + override val current: MarkerEntityInterface = + MarkerEntity( + marker = prevEntity.marker, + state = state, + visible = prevEntity.visible, + isRendered = true, + ) + override val bitmapIcon: BitmapIcon = markerIcon + override val prev: MarkerEntityInterface = prevEntity + } + val markers = renderer.onChange(listOf(params)) + markers.firstOrNull()?.let { actual -> + markerManager.updateEntity( + MarkerEntity( + marker = actual, + state = state, + visible = prevEntity.visible, + isRendered = true, + ), + ) + if (prevFinger.animation != currentFinger.animation) { + state.getAnimation()?.let { renderer.onAnimate(markerManager.getEntity(state.id)!!) } + } + } + renderer.onPostProcess() + + if (tiledMarkerIds.isNotEmpty()) { + syncTiledOverlay() + } else { + removeTileOverlay() + } + } + viewportSwitch.requestReapply() + } + + override suspend fun clear() { + viewportSwitch.destroy() + semaphore.withPermit { + val entities = markerManager.allEntities() + val toRemove = entities.filter { it.marker != null } + if (toRemove.isNotEmpty()) { + renderer.onRemove(toRemove) + } + markerManager.clear() + tiledMarkerIds.clear() + removeTileOverlay() + } + } + + override suspend fun onCameraChanged(mapCameraPosition: MapCameraPosition) { + // 判定と昇格は debounce したうえで切り替え器の中で走る(パン中は動かない)。 + viewportSwitch.onCameraChanged(mapCameraPosition) + lastKnownZoom = mapCameraPosition.zoom + } + + /** + * マーカータイルのラスターレイヤの表示だけを切り替える。 + * + * source(URL)には触らない。触るとタイルを取り直すことになり、切り替えのたびに + * タイルキャッシュを捨てるのと同じになる。 + */ + private suspend fun setTileLayerVisible(visible: Boolean) { + val current = markerTileRasterLayerState ?: return + if (current.visible == visible) return + val newState = current.copy(visible = visible) + markerTileRasterLayerState = newState + rasterLayerCallback?.onRasterLayerUpdate(newState) + } + + override fun destroy() { + viewportSwitch.destroy() + // Clean up tile server registration + // Unregister this map's route only. Never stop the server here: it is + // a process-wide singleton shared by all map controllers and overlay + // modules; stopping it breaks tile loading for every other live map. + markerTileGroupId?.let { groupId -> + tileServer.unregister(groupId) + } + markerTileGroupId = null + markerTileRenderer = null + + (renderer as HereMarkerRenderer).coroutine.launch { + rasterLayerCallback?.onRasterLayerUpdate(null) + } + markerTileRasterLayerState = null + super.destroy() + } + + private suspend fun updateRasterLayerSource() { + val groupId = markerTileGroupId ?: return + val tileRenderer = markerTileRenderer ?: return + val oldState = markerTileRasterLayerState ?: return + cacheVersion = (cacheVersion + 1) and 0x7fffffff + tileRenderer.invalidate() + val cacheBuster = "${cacheVersion}_${SystemClock.elapsedRealtime()}" + + val newState = + oldState.copy( + source = + RasterLayerSource.UrlTemplate( + template = "${tileServer.urlTemplate(groupId, tileRenderer.tileSize)}?cb=$cacheBuster", + tileSize = tileRenderer.tileSize, + maxZoom = 22, + scheme = TileScheme.XYZ, + ), + id = oldState.id, + ) + markerTileRasterLayerState = newState + rasterLayerCallback?.onRasterLayerUpdate(newState) + } + + private suspend fun syncTiledOverlay() { + if (tiledMarkerIds.isEmpty()) { + removeTileOverlay() + return + } + if (!markerTiling.enabled) { + removeTileOverlay() + tiledMarkerIds.clear() + return + } + + getOrCreateTileRenderer() + updateRasterLayerSource() + } + + private fun getOrCreateTileRenderer(): MarkerTileRenderer { + markerTileRenderer?.let { return it } + + val groupId = UUID.randomUUID().toString() + markerTileGroupId = groupId + + // HERE displays one raster tile over 512 logical px, so render tiles at + // 512 with no extra icon scale: icons match regular MapMarker size 1:1. + // (256 gets upscaled 2x -> icons appear double size; 1024 doubles the + // render/PNG-encode cost for no visible gain.) + val tileScale = 1.0 + val outputTileSize = 512 + + cacheVersion = (cacheVersion + 1) and 0x7fffffff + val tileRenderer = + MarkerTileRenderer( + markerManager = markerManager, + tileSize = outputTileSize, + cacheSizeBytes = markerTiling.cacheSize, + debugTileOverlay = markerTiling.debugTileOverlay, + iconScaleCallback = markerTiling.iconScaleCallback, + declutterPx = markerTiling.declutterPx, + extraIconScale = tileScale, + ) + markerTileRenderer = tileRenderer + + tileServer.register(groupId, tileRenderer) + + markerTileRasterLayerState = + RasterLayerState( + id = "marker-tile-$groupId", + source = + RasterLayerSource.UrlTemplate( + template = "${tileServer.urlTemplate(groupId, tileRenderer.tileSize)}?cb=$cacheVersion", + tileSize = tileRenderer.tileSize, + maxZoom = 22, + scheme = TileScheme.XYZ, + ), + opacity = 1.0f, + visible = true, + ) + + return tileRenderer + } + + private suspend fun removeTileOverlay() { + markerTileGroupId?.let { groupId -> + tileServer.unregister(groupId) + } + markerTileGroupId = null + markerTileRenderer = null + + rasterLayerCallback?.onRasterLayerUpdate(null) + markerTileRasterLayerState = null + } + + companion object { + fun create( + holder: HereViewHolder, + markerTiling: MarkerTilingOptions = MarkerTilingOptions.Default, + ): HereMarkerController { + val renderer = + HereMarkerRenderer( + holder = holder, + ) + val markerManager = + MarkerManager.defaultManager( + minMarkerCount = markerTiling.minMarkerCount, + ) + val controller = + HereMarkerController( + markerManager = markerManager, + renderer = renderer, + markerTiling = markerTiling, + ) + // HERE camera zoom is updated via onCameraChanged; initialize a best-effort value. + controller.lastKnownZoom = holder.mapView.camera.state.zoomLevel + return controller + } + } +} From 341ce1dcfd029c773caeef2a6c6666dfde317a2d Mon Sep 17 00:00:00 2001 From: Masashi Katsumata Date: Mon, 5 Oct 2026 14:52:57 -0700 Subject: [PATCH 04/23] update dependencies (#13) --- gradle.properties | 2 +- gradle/libs.versions.toml | 14 +++++++------- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/gradle.properties b/gradle.properties index 26d9949..c018eb9 100644 --- a/gradle.properties +++ b/gradle.properties @@ -3,7 +3,7 @@ android.useAndroidX=true kotlin.code.style=official android.nonTransitiveRClass=true -compileSdk=35 +compileSdk=37 minSdk=26 javaVersion=17 jvmTarget=17 diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index a701d59..f15f5ea 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -1,15 +1,15 @@ [versions] -coroutines = "1.9.0" -composeLibs = "1.7.8" +coroutines = "1.11.0" +composeLibs = "1.12.1" # material3 は compose-ui とは別のバージョン系列。composeLibs(ui 系)を流用すると # 存在しない material3:1.7.8 を要求してクラスパスごと解決に失敗する。 material3 = "1.4.0" -agp = "9.2.1" -kotlin = "2.0.21" +agp = "9.4.1" +kotlin = "2.4.20" -composeBom = "2025.02.00" -lifecycleRuntimeKtx = "2.8.7" -activityCompose = "1.9.3" +composeBom = "2026.09.00" +lifecycleRuntimeKtx = "2.11.0" +activityCompose = "1.13.0" ktLint = "14.2.0" junit = "4.13.2" From c45c6801a263976b16a4f39fd173c19d74ec2d3b Mon Sep 17 00:00:00 2001 From: Masashi Katsumata Date: Sat, 24 Oct 2026 10:50:59 -0700 Subject: [PATCH 05/23] Vector style support and render local raster tiles without HERE's network fetch (#14) * Render local raster tiles without HERE network fetch * feat: integrate vector style support and pending map fixes * Keep each file's line endings as they are on develop The checkpoint commit rewrote whole files between LF and CRLF, which buried its real changes under line-ending noise. Content is unchanged. --- api/android-for-here.api | 22 ++- .../java/com/mapconductor/here/HereMapView.kt | 12 ++ .../raster/HereRasterLayerOverlayRenderer.kt | 157 +++++++++++++++--- 3 files changed, 170 insertions(+), 21 deletions(-) diff --git a/api/android-for-here.api b/api/android-for-here.api index 49d14d6..ecca64e 100644 --- a/api/android-for-here.api +++ b/api/android-for-here.api @@ -172,7 +172,7 @@ public final class com.mapconductor.here.HereMapViewControllerStore extends com. public final void initSDK(android.content.Context); } public final class com.mapconductor.here.HereMapViewKt { - public static final void HereMapView(com.mapconductor.here.HereViewState, androidx.compose.ui.Modifier, com.mapconductor.core.marker.MarkerTilingOptions, com.mapconductor.core.map.CameraRestriction, kotlin.jvm.functions.Function2, ? extends java.lang.Object>, 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.MapProjection, kotlin.jvm.functions.Function3, androidx.compose.runtime.Composer, int, int, int); + public static final void HereMapView(com.mapconductor.here.HereViewState, androidx.compose.ui.Modifier, com.mapconductor.core.marker.MarkerTilingOptions, com.mapconductor.core.map.CameraRestriction, kotlin.jvm.functions.Function2, ? extends java.lang.Object>, 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.MapProjection, 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.here.HereMapViewSaver extends com.mapconductor.compose.map.BaseMapViewSaver { public com.mapconductor.here.HereMapViewSaver(); @@ -400,11 +400,13 @@ final class com.mapconductor.here.raster.HereRasterLayerOverlayRenderer$TileSpec public final java.lang.String getSourceName(); public final java.lang.String getLayerName(); public final java.util.List getStorageLevels(); + public final java.lang.String getLocalTemplate(); public final com.here.sdk.mapview.datasource.TileUrlProviderCallback component1(); public final java.lang.String component2(); public final java.lang.String component3(); public final java.util.List component4(); - public final com.mapconductor.here.raster.HereRasterLayerOverlayRenderer$TileSpec copy(com.here.sdk.mapview.datasource.TileUrlProviderCallback, java.lang.String, java.lang.String, java.util.List); + public final java.lang.String component5(); + public final com.mapconductor.here.raster.HereRasterLayerOverlayRenderer$TileSpec copy(com.here.sdk.mapview.datasource.TileUrlProviderCallback, java.lang.String, java.lang.String, java.util.List, java.lang.String); public java.lang.String toString(); public int hashCode(); public boolean equals(java.lang.Object); @@ -417,6 +419,22 @@ final class com.mapconductor.here.raster.HereRasterTileProxyProvider implements } public final class com.mapconductor.here.raster.HereRasterTileProxyProvider$Companion { } +final class com.mapconductor.here.raster.LocalRasterTileSource implements com.here.sdk.mapview.datasource.RasterTileSource { + public static final int RENDER_WIDTH; + public static final long TEN_YEARS_MS; + public com.mapconductor.here.raster.LocalRasterTileSource(com.mapconductor.core.tileserver.LocalTileServer, java.lang.String, java.util.List); + public com.here.sdk.mapview.datasource.TileSource$DataVersion getDataVersion(com.here.sdk.mapview.datasource.TileKey); + public void addListener(com.here.sdk.mapview.datasource.TileSource$Listener); + public void removeListener(com.here.sdk.mapview.datasource.TileSource$Listener); + public com.here.sdk.mapview.datasource.TilingScheme getTilingScheme(); + public java.util.List getStorageLevels(); + public com.here.sdk.mapview.datasource.TileSource$LoadTileRequestHandle loadTile(com.here.sdk.mapview.datasource.TileKey, com.here.sdk.mapview.datasource.RasterTileSource$LoadResultHandler); +} +final class com.mapconductor.here.raster.LocalRasterTileSource$Companion { + public final kotlinx.coroutines.CoroutineDispatcher getRenderDispatcher(); + public final com.here.sdk.mapview.datasource.TileSource$DataVersion getVERSION(); + public final com.here.sdk.mapview.datasource.TileSource$TileMetadata getMETADATA(); +} public final class com.mapconductor.here.zoom.ZoomAltitudeConverter extends com.mapconductor.core.zoom.AbstractZoomAltitudeConverter { public static final com.mapconductor.here.zoom.ZoomAltitudeConverter$Companion Companion; public static final double HERE_ZOOM_TO_GOOGLE_ZOOM_AT_EQUATOR; diff --git a/src/main/java/com/mapconductor/here/HereMapView.kt b/src/main/java/com/mapconductor/here/HereMapView.kt index fe90bd8..4fcd793 100644 --- a/src/main/java/com/mapconductor/here/HereMapView.kt +++ b/src/main/java/com/mapconductor/here/HereMapView.kt @@ -22,6 +22,7 @@ import com.mapconductor.core.map.CameraRestriction import com.mapconductor.core.map.MapCameraPosition import com.mapconductor.core.map.MapCameraPositionInterface import com.mapconductor.core.map.MapProjection +import com.mapconductor.core.map.MapViewStyle import com.mapconductor.core.marker.MarkerEventControllerInterface import com.mapconductor.core.marker.MarkerOverlayRendererInterface import com.mapconductor.core.marker.MarkerRenderingStrategyInterface @@ -63,6 +64,15 @@ fun HereMapView( onCameraMove: OnCameraMoveHandler? = null, onCameraMoveEnd: OnCameraMoveHandler? = null, projection: MapProjection = MapProjection.Globe, + /** + * 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 HereViewScope.() -> Unit)? = null, ) { // Warmup the tile server early to reduce latency for raster layers @@ -254,6 +264,8 @@ fun HereMapView( // Pass content if it needs to be rendered within the overlay providers in MapViewBase, // or handle it here if it's specific to HereMapView structure before calling MapViewBase. // For now, assuming content relates to overlay definitions. + style = style, + onStyleDiagnostics = onStyleDiagnostics, content = content, // This might need adjustment based on how overlays are handled ) } diff --git a/src/main/java/com/mapconductor/here/raster/HereRasterLayerOverlayRenderer.kt b/src/main/java/com/mapconductor/here/raster/HereRasterLayerOverlayRenderer.kt index 19b2b7b..f81b068 100644 --- a/src/main/java/com/mapconductor/here/raster/HereRasterLayerOverlayRenderer.kt +++ b/src/main/java/com/mapconductor/here/raster/HereRasterLayerOverlayRenderer.kt @@ -5,6 +5,9 @@ import com.here.sdk.mapview.MapLayer import com.here.sdk.mapview.MapLayerBuilder import com.here.sdk.mapview.datasource.RasterDataSource import com.here.sdk.mapview.datasource.RasterDataSourceConfiguration +import com.here.sdk.mapview.datasource.RasterTileSource +import com.here.sdk.mapview.datasource.TileKey +import com.here.sdk.mapview.datasource.TileSource import com.here.sdk.mapview.datasource.TileUrlProviderCallback import com.here.sdk.mapview.datasource.TileUrlProviderFactory import com.here.sdk.mapview.datasource.TilingScheme @@ -20,6 +23,8 @@ import com.mapconductor.here.HereViewHolder import java.io.ByteArrayOutputStream import java.net.HttpURLConnection import java.net.URL +import java.util.Date +import java.util.concurrent.atomic.AtomicBoolean import android.graphics.Bitmap import android.graphics.BitmapFactory import android.graphics.Canvas @@ -28,6 +33,10 @@ import android.util.Log import android.util.LruCache import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.isActive +import kotlinx.coroutines.launch class HereRasterLayerOverlayRenderer( private val holder: HereViewHolder, @@ -83,30 +92,46 @@ class HereRasterLayerOverlayRenderer( } val urlProvider = tileSpec.provider val storageLevels = tileSpec.storageLevels - val dataSourceProvider = - RasterDataSourceConfiguration.Provider( - urlProvider, - TilingScheme.QUAD_TREE_MERCATOR, - storageLevels, - ) - dataSourceProvider.hasAlphaChannel = true - val cache = - RasterDataSourceConfiguration.Cache( - holder.mapView.context.cacheDir.absolutePath, - ) - val config = - RasterDataSourceConfiguration( - tileSpec.sourceName, - dataSourceProvider, - cache, - ) - val dataSource = RasterDataSource(holder.mapView.mapContext, config) + // Tiles this process draws are handed over in process. HERE fetches + // through its own network stack and, while the device reports no + // connectivity, does not fetch at all -- not even from 127.0.0.1 -- + // so a URL-fed source goes blank the moment the network is away. + // A tile source is asked for bytes and answered from the same + // providers, with no network in between. + val localTemplate = tileSpec.localTemplate + val dataSource = + if (localTemplate != null) { + RasterDataSource( + holder.mapView.mapContext, + tileSpec.sourceName, + LocalRasterTileSource(tileServer, localTemplate, storageLevels), + ) + } else { + val dataSourceProvider = + RasterDataSourceConfiguration.Provider( + urlProvider, + TilingScheme.QUAD_TREE_MERCATOR, + storageLevels, + ) + dataSourceProvider.hasAlphaChannel = true + val cache = + RasterDataSourceConfiguration.Cache( + holder.mapView.context.cacheDir.absolutePath, + ) + val config = + RasterDataSourceConfiguration( + tileSpec.sourceName, + dataSourceProvider, + cache, + ) + RasterDataSource(holder.mapView.mapContext, config) + } return try { val layer = MapLayerBuilder() .withName(tileSpec.layerName) - .withDataSource(config.name, MapContentType.RASTER_IMAGE) + .withDataSource(tileSpec.sourceName, MapContentType.RASTER_IMAGE) .forMap(holder.mapView.hereMap) .build() layer.setEnabled(state.visible) @@ -179,6 +204,13 @@ class HereRasterLayerOverlayRenderer( sourceName = "raster-source-${state.id}", layerName = "raster-layer-${state.id}", storageLevels = buildStorageLevels(source.minZoom, source.maxZoom), + // The proxy route is local by construction; a direct + // template is local when it is one of the server's own. + localTemplate = + template.takeIf { + it.startsWith(tileServer.baseUrl + "/") && + (routeId != null || source.scheme != TileScheme.TMS) + }, ) } is RasterLayerSource.TileJson -> { @@ -235,9 +267,96 @@ class HereRasterLayerOverlayRenderer( val sourceName: String, val layerName: String, val storageLevels: List, + /** The XYZ template on this process's tile server, when the tiles come from there. */ + val localTemplate: String? = null, ) } +/** + * A HERE tile source answered from this process's tile server, with no HTTP + * hop and no dependence on the device's connectivity. + */ +private class LocalRasterTileSource( + private val tileServer: LocalTileServer, + private val template: String, + private val levels: List, +) : RasterTileSource { + override fun getDataVersion(tileKey: TileKey): TileSource.DataVersion = VERSION + + override fun addListener(listener: TileSource.Listener) {} + + override fun removeListener(listener: TileSource.Listener) {} + + override fun getTilingScheme(): TilingScheme = TilingScheme.QUAD_TREE_MERCATOR + + override fun getStorageLevels(): List = levels + + override fun loadTile( + tileKey: TileKey, + handler: RasterTileSource.LoadResultHandler, + ): TileSource.LoadTileRequestHandle { + // Exactly one answer per request, whatever happens. A request HERE + // cancels is still one it is waiting on: leave it unanswered and the + // slot is never freed, and after a few gestures HERE stops asking for + // tiles at all -- the map keeps the last picture and looks frozen. + val answered = AtomicBoolean(false) + + fun answer(bytes: ByteArray?) { + if (!answered.compareAndSet(false, true)) return + if (bytes != null) handler.loaded(tileKey, bytes, METADATA) else handler.failed(tileKey) + } + // HERE counts rows from the south (Tokyo at z12 is row 2483, not + // 1612); the templates count from the north, as XYZ does. + val row = (1 shl tileKey.level) - 1 - tileKey.y + val url = + template + .replace("{z}", tileKey.level.toString()) + .replace("{x}", tileKey.x.toString()) + .replace("{y}", row.toString()) + val job = + scope.launch { + answer(runCatching { tileServer.renderLocalTile(url) { !isActive } }.getOrNull()) + } + // Cancelled, or the coroutine never ran: answered from a render + // thread rather than from whichever thread cancelled it. + job.invokeOnCompletion { if (!answered.get()) scope.launch { answer(null) } } + return TileSource.LoadTileRequestHandle { job.cancel() } + } + + /** + * Renders run here and nowhere else. + * + * HERE asks for a screenful at once and every one of those is a tile to + * draw. On `Dispatchers.Default` they take every thread the rest of the + * SDK shares -- camera callbacks, overlays, the vector renderer itself -- + * and the map stops answering gestures while it fills. This is the same + * width, and the same reasoning, as the tile server's own worker pool, + * which is what the HTTP path went through. + */ + private val scope = CoroutineScope(SupervisorJob() + renderDispatcher) + + private companion object { + @OptIn(ExperimentalCoroutinesApi::class) + val renderDispatcher = Dispatchers.Default.limitedParallelism(RENDER_WIDTH) + + /** Tile rendering is CPU-bound; more workers than cores adds contention, not throughput. */ + const val RENDER_WIDTH = 8 + + val VERSION = TileSource.DataVersion(0, 0) + + /** + * Tiles drawn here change only with their URL, so they are given a + * long life -- but a plausible one. A date near the end of `Long` + * does not survive the trip into the SDK: every tile came back + * already expired, the same one was asked for again every 400 ms, + * and after a pinch the map stopped asking for tiles at all. + */ + val METADATA = TileSource.TileMetadata(VERSION, Date(System.currentTimeMillis() + TEN_YEARS_MS)) + + const val TEN_YEARS_MS = 10L * 365 * 24 * 60 * 60 * 1000 + } +} + data class HereRasterLayerHandle( val dataSource: RasterDataSource, val layer: MapLayer, From cb0945abafb7ff1de53e1b030304bee8249822bb Mon Sep 17 00:00:00 2001 From: Masashi Katsumata Date: Wed, 28 Oct 2026 13:47:11 -0700 Subject: [PATCH 06/23] Add .claude/settings.json --- .claude/settings.json | 6 ++++++ 1 file changed, 6 insertions(+) create mode 100644 .claude/settings.json 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": "" + } +} From b627cfafa788f1498d3c4987a259e70919969c54 Mon Sep 17 00:00:00 2001 From: Masashi Katsumata Date: Thu, 5 Nov 2026 14:58:13 -0800 Subject: [PATCH 07/23] Redraw tiles once per burst of tiled-marker changes Same change as android-for-maplibre: relabelling street trees changes a few dozen tiled markers at once, and each update() replaced the raster source, so the map fetched every visible tile again per marker (on MapLibre, Pixel 5a: 45 replacements, 494 tile renders, last tile 6.1 s after the change). - Changes arriving within a frame share one tile refresh; a pending refresh is cancelled on destroy() so it cannot register the tile route again. - The tiling check reads the entity count without copying all entities. - The icon is baked only when the marker is drawn natively. - onPostProcess runs only when a native marker became tiled (it copies every entity to redraw the native ones). --- .../here/marker/HereMarkerController.kt | 43 ++++++++++++++++--- 1 file changed, 38 insertions(+), 5 deletions(-) diff --git a/src/main/java/com/mapconductor/here/marker/HereMarkerController.kt b/src/main/java/com/mapconductor/here/marker/HereMarkerController.kt index 1e28324..b797825 100644 --- a/src/main/java/com/mapconductor/here/marker/HereMarkerController.kt +++ b/src/main/java/com/mapconductor/here/marker/HereMarkerController.kt @@ -22,7 +22,10 @@ import com.mapconductor.core.tileserver.TileServerRegistry import com.mapconductor.here.HereActualMarker import com.mapconductor.here.HereViewHolder import java.util.UUID +import kotlin.time.Duration.Companion.milliseconds import android.os.SystemClock +import kotlinx.coroutines.Job +import kotlinx.coroutines.delay import kotlinx.coroutines.launch import kotlinx.coroutines.sync.withPermit @@ -112,11 +115,12 @@ class HereMarkerController private constructor( if (currentFinger == prevFinger) return semaphore.withPermit { + // 件数だけが要る。allEntities() は全件の写しを作るので、ラベルの付け替えのように + // 数十本が続けて変わると、そのたびに 14 万件を写すことになる。 val tilingEnabled = - markerTiling.enabled && markerManager.allEntities().size >= markerManager.minMarkerCount + markerTiling.enabled && markerManager.getMemoryStats().entityCount >= markerManager.minMarkerCount val wantsTiled = tilingEnabled && !state.draggable && state.getAnimation() == null val wasTiled = tiledMarkerIds.contains(state.id) - val markerIcon = state.icon?.toBitmapIcon() ?: defaultMarkerIcon if (wantsTiled) { if (!wasTiled) { @@ -134,14 +138,19 @@ class HereMarkerController private constructor( tiling = true, ), ) - renderer.onPostProcess() - syncTiledOverlay() + // タイル担当のままなら、ネイティブのマーカーには何も起きていない。onPostProcess は + // 全件を写してネイティブ分を描き直すので(14 万件で 1 回 50ms)、ネイティブから + // タイルへ移ったときだけ呼ぶ。 + if (!wasTiled) renderer.onPostProcess() + scheduleTileRefresh() return@withPermit } if (wasTiled) { tiledMarkerIds.remove(state.id) } + // ネイティブマーカーとして描くときだけ焼き込む。タイル担当なら要らない。 + val markerIcon = state.icon?.toBitmapIcon() ?: defaultMarkerIcon val params = object : MarkerOverlayRendererInterface.ChangeParamsInterface { @@ -172,7 +181,7 @@ class HereMarkerController private constructor( renderer.onPostProcess() if (tiledMarkerIds.isNotEmpty()) { - syncTiledOverlay() + scheduleTileRefresh() } else { removeTileOverlay() } @@ -180,6 +189,25 @@ class HereMarkerController private constructor( viewportSwitch.requestReapply() } + private var tileRefreshJob: Job? = null + + /** + * 1 本ずつの変更からの描き直しを 1 回にまとめる。 + * + * ラベルの付け替えのように数十本が続けて変わると、1 本ごとにラスターソースを差し替え、 + * そのたびに地図が見えているタイルを全部取り直していた(MapLibre・Pixel 5a で 45 回、 + * 描き直したタイル 494 枚、最後のタイルまで 6 秒)。続けて来た変更は + * [TILE_REFRESH_COALESCE] の間に受けて、まとめて 1 回だけ差し替える。 + */ + private fun scheduleTileRefresh() { + if (tileRefreshJob?.isActive == true) return + tileRefreshJob = + (renderer as HereMarkerRenderer).coroutine.launch { + delay(TILE_REFRESH_COALESCE) + semaphore.withPermit { syncTiledOverlay() } + } + } + override suspend fun clear() { viewportSwitch.destroy() semaphore.withPermit { @@ -216,6 +244,8 @@ class HereMarkerController private constructor( override fun destroy() { viewportSwitch.destroy() + // 待っている描き直しが後から走ると、外したタイル経路をまた登録してしまう。 + tileRefreshJob?.cancel() // Clean up tile server registration // Unregister this map's route only. Never stop the server here: it is // a process-wide singleton shared by all map controllers and overlay @@ -328,6 +358,9 @@ class HereMarkerController private constructor( } companion object { + /** 続けて来る変更を 1 回の描き直しにまとめる窓。1 フレーム分。 */ + private val TILE_REFRESH_COALESCE = 16.milliseconds + fun create( holder: HereViewHolder, markerTiling: MarkerTilingOptions = MarkerTilingOptions.Default, From e0d4d406a0b6e96ab5ca44bafc865582eff8242d Mon Sep 17 00:00:00 2001 From: Masashi Katsumata Date: Fri, 6 Nov 2026 19:25:13 -0800 Subject: [PATCH 08/23] Keep the map design across configuration changes - The controller reported its default (NormalDay) when the change listener was attached, before loadScene read the state's design, so after a rotation -- or with any initial design -- the map came up NormalDay. The controller is now seeded with the state's design first. - The saver kept only the scheme id; Custom designs lost their attribution rules. It now records whether the design was a preset. - Device round-trip test (the test APK bundles the HERE SDK). --- build.gradle.kts | 9 ++ .../mapconductor/here/HereMapViewSaverTest.kt | 85 +++++++++++++++++++ .../java/com/mapconductor/here/HereMapView.kt | 4 + .../here/HereMapViewController.kt | 2 +- .../mapconductor/here/HereViewStateImpl.kt | 37 ++++++-- 5 files changed, 129 insertions(+), 8 deletions(-) create mode 100644 src/androidTest/java/com/mapconductor/here/HereMapViewSaverTest.kt diff --git a/build.gradle.kts b/build.gradle.kts index af80bd2..e170901 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -97,6 +97,15 @@ dependencies { ), ), ) + // 実機テスト(HereMapViewSaverTest)は MapScheme などを実行時に読むので、テスト APK には同梱する。 + androidTestImplementation( + fileTree( + mapOf( + "dir" to rootDir.resolve("libs").toString(), + "include" to arrayOf("heresdk*.jar", "heresdk*.aar"), + ), + ), + ) if (findProject(":android-sdk-compose") != null) { api(project(":android-sdk-compose")) } else { diff --git a/src/androidTest/java/com/mapconductor/here/HereMapViewSaverTest.kt b/src/androidTest/java/com/mapconductor/here/HereMapViewSaverTest.kt new file mode 100644 index 0000000..283b8c5 --- /dev/null +++ b/src/androidTest/java/com/mapconductor/here/HereMapViewSaverTest.kt @@ -0,0 +1,85 @@ +package com.mapconductor.here + +import androidx.compose.runtime.saveable.Saver +import androidx.compose.runtime.saveable.SaverScope +import androidx.test.ext.junit.runners.AndroidJUnit4 +import com.here.sdk.mapview.MapScheme +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.Assert.assertSame +import org.junit.Assert.assertTrue +import org.junit.Test +import org.junit.runner.RunWith +import android.os.Bundle +import android.os.Parcel + +/** + * 回転などの構成変更で state が [HereMapViewSaver] を通って作り直されても、デザイン(id・ + * attributionRules ほか)と uiSettings・カメラが落ちないこと。Bundle は実機の Parcel を一度通す。 + */ +@RunWith(AndroidJUnit4::class) +class HereMapViewSaverTest { + 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 keepsCustomDesignWithAttributionRules() { + val design = HereMapDesign.Custom(MapScheme.SATELLITE, rules) + val state = HereViewState(id = "here-1", mapDesignType = design, cameraPosition = camera) + state.uiSettings = MapUISettings(rotateGesture = false, tiltGesture = false) + + val restored = roundTrip(HereMapViewSaver().createSaver(), state) + + val actual = restored.mapDesignType + assertTrue(actual is HereMapDesign.Custom) + assertEquals(MapScheme.SATELLITE, actual.id) + assertEquals(rules, actual.attributionRules) + assertCommon(restored, "here-1") + } + + @Test + fun keepsPresetDesignAsTheSameObject() { + val state = HereViewState(id = "here-2", mapDesignType = HereMapDesign.LiteNight) + assertSame(HereMapDesign.LiteNight, roundTrip(HereMapViewSaver().createSaver(), state).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/here/HereMapView.kt b/src/main/java/com/mapconductor/here/HereMapView.kt index 4fcd793..e0b6911 100644 --- a/src/main/java/com/mapconductor/here/HereMapView.kt +++ b/src/main/java/com/mapconductor/here/HereMapView.kt @@ -149,6 +149,10 @@ fun HereMapView( controller.setMapClickListener(onMapClick) controller.setMapLongClickListener(onMapLongClick) state.setController(controller) + // コントローラの既定値(NormalDay)のままリスナーを繋ぐと、それが state へ返り、 + // アプリが渡した(あるいは回転後に復元した)デザインが NormalDay に化ける。 + // 下の loadScene は state のデザインを読むので、その前に揃えておく。 + controller.mapDesignType = state.mapDesignType controller.setMapDesignTypeChangeListener(state::onMapDesignTypeChange) cameraRestriction?.let { controller.setCameraRestriction(it) } diff --git a/src/main/java/com/mapconductor/here/HereMapViewController.kt b/src/main/java/com/mapconductor/here/HereMapViewController.kt index e2f132d..8150c0d 100644 --- a/src/main/java/com/mapconductor/here/HereMapViewController.kt +++ b/src/main/java/com/mapconductor/here/HereMapViewController.kt @@ -238,7 +238,7 @@ class HereMapViewController( polygonController.clickListener = listener } - private var mapDesignType: HereMapDesignType = HereMapDesign.NormalDay + internal var mapDesignType: HereMapDesignType = HereMapDesign.NormalDay private var mapDesignTypeChangeListener: HereMapDesignTypeChangeHandler? = null override fun applyUISettings(settings: MapUISettings) { diff --git a/src/main/java/com/mapconductor/here/HereViewStateImpl.kt b/src/main/java/com/mapconductor/here/HereViewStateImpl.kt index e21f0f0..426a0aa 100644 --- a/src/main/java/com/mapconductor/here/HereViewStateImpl.kt +++ b/src/main/java/com/mapconductor/here/HereViewStateImpl.kt @@ -5,12 +5,14 @@ import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.saveable.rememberSaveable +import com.here.sdk.mapview.MapScheme import com.mapconductor.compose.map.BaseMapViewSaver import com.mapconductor.core.map.MapCameraPosition import com.mapconductor.core.map.MapCameraPositionInterface import com.mapconductor.core.map.MapPaddings import com.mapconductor.core.map.MapPaddingsInterface import com.mapconductor.core.map.MapViewState +import com.mapconductor.core.map.MapViewStateBundle import com.mapconductor.core.map.MapViewStateInterface import java.util.UUID import android.app.Activity @@ -60,28 +62,49 @@ class HereMapViewSaver : BaseMapViewSaver() { state: HereViewState, bundle: Bundle, ) { - bundle.putInt("id", state.mapDesignType.getValue().value) + val design = state.mapDesignType + val scheme = design.getValue().value + bundle.putInt("id", scheme) + // 定義済み(NormalDay など)以外は Custom として戻す。id だけだと Custom の + // attributionRules が落ちる。 + bundle.putBoolean(KEY_CUSTOM, design !== presetOrNull(scheme)) + MapViewStateBundle.putAttributionRules(bundle, design.attributionRules) } override fun createState( stateId: String, mapDesignBundle: Bundle?, cameraPosition: MapCameraPosition, - ): HereViewState = - HereViewState( + ): HereViewState { + val scheme = mapDesignBundle?.getInt("id", HereMapDesign.NormalDay.id.value) ?: HereMapDesign.NormalDay.id.value + val preset = presetOrNull(scheme) + val mapScheme = MapScheme.values().firstOrNull { it.value == scheme } + val design = + if ((mapDesignBundle?.getBoolean(KEY_CUSTOM) == true || preset == null) && mapScheme != null) { + HereMapDesign.Custom( + id = mapScheme, + attributionRules = MapViewStateBundle.getAttributionRules(mapDesignBundle), + ) + } else { + preset ?: HereMapDesign.NormalDay + } + return HereViewState( id = stateId, - mapDesignType = - HereMapDesign.create( - id = mapDesignBundle?.getInt("id") ?: HereMapDesign.NormalDay.id.value, - ), + mapDesignType = design, cameraPosition = cameraPosition, ) + } + + private fun presetOrNull(scheme: Int): HereMapDesign? = runCatching { HereMapDesign.create(scheme) }.getOrNull() override fun getCameraPaddings(): MapPaddingsInterface? = MapPaddings.Zeros override fun getStateId(state: HereViewState): String = state.id } +// 公開 API の門番(javap)にコンパニオンの定数が載らないよう、ファイル private にする。 +private const val KEY_CUSTOM = "custom" + @Composable fun rememberHereMapViewState( mapDesign: HereMapDesign = HereMapDesign.NormalDay, From 902936987ae9910aad7734551e7ab8a347251c37 Mon Sep 17 00:00:00 2001 From: Masashi Katsumata Date: Sat, 7 Nov 2026 05:40:54 -0800 Subject: [PATCH 09/23] Draw large polygon sets as raster tiles (PolygonTiler) The polygon controller gets a PolygonTiler, whose tiles are shown through the raster layer path the marker tiles use (upsert / removeById, outside the app's RasterLayer composition). Tiled polygons stay registered for taps and give the map SDK nothing. --- .../mapconductor/here/HereMapViewController.kt | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/src/main/java/com/mapconductor/here/HereMapViewController.kt b/src/main/java/com/mapconductor/here/HereMapViewController.kt index 8150c0d..1e0b58c 100644 --- a/src/main/java/com/mapconductor/here/HereMapViewController.kt +++ b/src/main/java/com/mapconductor/here/HereMapViewController.kt @@ -1,5 +1,8 @@ package com.mapconductor.here +import com.mapconductor.core.polygon.POLYGON_TILE_LAYER_ID +import com.mapconductor.core.polygon.PolygonTiler +import com.mapconductor.core.polygon.polygonTileRasterLayerState import HereMapDesignTypeChangeHandler import HereMapViewControllerInterface import com.here.sdk.core.Point2D @@ -167,6 +170,19 @@ class HereMapViewController( } }, ) + + // Many polygons are drawn as raster tiles, shown through the same RasterLayer + // controller as the marker tiles (upsert / removeById, never the app's layers). + polygonController.tiler = + PolygonTiler().apply { + onTemplate = { template, tileSize -> + if (template != null) { + rasterLayerController.upsert(polygonTileRasterLayerState(template, tileSize)) + } else { + rasterLayerController.removeById(POLYGON_TILE_LAYER_ID) + } + } + } } override fun moveCamera(position: MapCameraPosition) = handleMoveCamera(position) From 7ca1e7f3266654bea752b1031d634c6a21f3ac62 Mon Sep 17 00:00:00 2001 From: Masashi Katsumata Date: Sat, 7 Nov 2026 13:16:50 -0800 Subject: [PATCH 10/23] Destroy the MapView when the map leaves the composition On a configuration change the MapView was only taken off its parent, and a provider switch did nothing at all, so each old MapView stayed alive with the controller it reaches. It is now paused and destroyed through MapViewBase's onDestroyMapView, once. --- .../java/com/mapconductor/here/HereMapView.kt | 52 +++---------------- 1 file changed, 6 insertions(+), 46 deletions(-) diff --git a/src/main/java/com/mapconductor/here/HereMapView.kt b/src/main/java/com/mapconductor/here/HereMapView.kt index e0b6911..4854c23 100644 --- a/src/main/java/com/mapconductor/here/HereMapView.kt +++ b/src/main/java/com/mapconductor/here/HereMapView.kt @@ -1,15 +1,11 @@ package com.mapconductor.here import androidx.compose.runtime.Composable -import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.ui.Modifier import androidx.compose.ui.node.Ref import androidx.compose.ui.platform.LocalContext -import androidx.lifecycle.DefaultLifecycleObserver -import androidx.lifecycle.LifecycleOwner -import androidx.lifecycle.compose.LocalLifecycleOwner import com.here.sdk.mapview.MapProjection as HereMapProjection import com.here.sdk.mapview.MapRenderMode import com.here.sdk.mapview.MapView @@ -44,7 +40,6 @@ import com.mapconductor.here.raster.HereRasterLayerController import com.mapconductor.here.raster.HereRasterLayerOverlayRenderer import java.util.concurrent.atomic.AtomicBoolean import android.annotation.SuppressLint -import android.view.ViewGroup import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.suspendCancellableCoroutine @@ -82,7 +77,6 @@ fun HereMapView( val scope = remember { HereViewScope() } val controllerRef = remember { Ref() } val context = LocalContext.current - val lifecycle = LocalLifecycleOwner.current.lifecycle val registry = remember { scope.buildRegistry() } val cameraState = remember { mutableStateOf(state.cameraPosition) } // Capture the desired initial camera before any early camera callbacks can overwrite state. @@ -224,46 +218,12 @@ fun HereMapView( scope = scope, registry = registry, onMapLoaded = onMapLoaded, - customDisposableEffect = { _, holderRef -> - - // HERE specific DisposableEffect logic - DisposableEffect(lifecycle) { - val stateId = state.id // from BaseMapViewState - val observer = - object : DefaultLifecycleObserver { - override fun onResume(owner: LifecycleOwner) { - // Do not call here to keep the MapView instance - // holderRef.value?.mapView?.onResume() - } - - override fun onPause(owner: LifecycleOwner) { - // Do not call here to keep the MapView instance - // holderRef.value?.mapView?.onPause() - } - - override fun onDestroy(owner: LifecycleOwner) { - val currentHolder = holderRef.value - if (currentHolder != null) { - val activity = context.findActivity() - if (activity?.isChangingConfigurations == true) { - (currentHolder.mapView.parent as? ViewGroup)?.removeView(currentHolder.mapView) - } else { - // Ensure these calls are safe if mapView might be null or already destroyed - currentHolder.mapView.onPause() - currentHolder.mapView.onDestroy() - // Real teardown: free overlay controllers (tile-server - // routes, marker managers) and cancel the controller scope. - HereMapViewControllerStore.get(stateId)?.destroy() - HereMapViewControllerStore.remove(stateId) // Clean up from your store - } - } - } - } - lifecycle.addObserver(observer) - onDispose { - lifecycle.removeObserver(observer) - } - } + // Created resumed in viewProvider, so paused before it is destroyed. A + // MapView left alive keeps its render loop and, through its listeners, + // the controller with every overlay. + onDestroyMapView = { mapView -> + mapView.onPause() + mapView.onDestroy() }, // Pass content if it needs to be rendered within the overlay providers in MapViewBase, // or handle it here if it's specific to HereMapView structure before calling MapViewBase. From eac94c673b6631cee2fddc25dadd4c836bf75793 Mon Sep 17 00:00:00 2001 From: Masashi Katsumata Date: Sat, 7 Nov 2026 16:20:26 -0800 Subject: [PATCH 11/23] Read the controller through the state base, which MapViewBase clears The state kept its own controller field, set on attach and never cleared, so a state the app keeps held the destroyed controller and every overlay of the old map. It now reads the base's attached controller, which MapViewBase detaches when the map is torn down. --- src/main/java/com/mapconductor/here/HereViewStateImpl.kt | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/mapconductor/here/HereViewStateImpl.kt b/src/main/java/com/mapconductor/here/HereViewStateImpl.kt index 426a0aa..d087c75 100644 --- a/src/main/java/com/mapconductor/here/HereViewStateImpl.kt +++ b/src/main/java/com/mapconductor/here/HereViewStateImpl.kt @@ -28,7 +28,10 @@ class HereViewState( cameraPosition: MapCameraPosition = MapCameraPosition.Default, ) : MapViewState(cameraPosition), HereViewStateInterface { - private var controller: HereMapViewControllerInterface? = null + // Read through the base so that letting go of the controller there (MapViewBase + // does it when the map is torn down) leaves nothing behind here. + private val controller: HereMapViewControllerInterface? + get() = attachedMapController as? HereMapViewControllerInterface private var _mapDesignType: HereMapDesignType = mapDesignType @@ -43,7 +46,6 @@ class HereViewState( override fun getMapViewHolder(): HereViewHolder? = super.getMapViewHolder() as? HereViewHolder internal fun setController(controller: HereMapViewControllerInterface) { - this.controller = controller // controller.setMapDesignType(_mapDesignType) attachController(controller) } From 1df9c809d111821aef5b6aee75cac88ba8581a86 Mon Sep 17 00:00:00 2001 From: Masashi Katsumata Date: Sat, 7 Nov 2026 21:23:01 -0800 Subject: [PATCH 12/23] Interpolate the closing edge of geodesic polygons The geodesic ring was densified with createInterpolatePoints, which only interpolates between neighbouring points, so the closing edge (last vertex -> first) of a geodesic polygon was a straight chord in both fill and outline. Use android-sdk-core's densifyGeodesicRing. geodesic=false is unchanged. Requires the android-sdk-core release that adds densifyGeodesicRing. --- .../here/polygon/HerePolygonOverlayRenderer.kt | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/src/main/java/com/mapconductor/here/polygon/HerePolygonOverlayRenderer.kt b/src/main/java/com/mapconductor/here/polygon/HerePolygonOverlayRenderer.kt index 8862948..1cc4d3b 100644 --- a/src/main/java/com/mapconductor/here/polygon/HerePolygonOverlayRenderer.kt +++ b/src/main/java/com/mapconductor/here/polygon/HerePolygonOverlayRenderer.kt @@ -9,6 +9,7 @@ import com.mapconductor.core.ResourceProvider import com.mapconductor.core.features.GeoPoint import com.mapconductor.core.features.GeoPointInterface import com.mapconductor.core.features.GeoRectBounds +import com.mapconductor.core.geometry.densifyGeodesicRing import com.mapconductor.core.normalizeLng import com.mapconductor.core.polygon.AbstractPolygonOverlayRenderer import com.mapconductor.core.polygon.PolygonEntityInterface @@ -239,9 +240,8 @@ class HerePolygonOverlayRenderer( ): List = ( if (geodesic) { - com.mapconductor.core.spherical - .WGS84Geodesic - .createInterpolatePoints(points) + // 閉じる辺(末尾 → 先頭)も大圏で補間する(塗りと輪郭が同じネイティブポリゴン)。 + densifyGeodesicRing(points) } else { points } @@ -255,9 +255,8 @@ class HerePolygonOverlayRenderer( ): List = ( if (geodesic) { - com.mapconductor.core.spherical - .WGS84Geodesic - .createInterpolatePoints(points) + // 閉じる辺(末尾 → 先頭)も大圏で補間する(塗りと輪郭が同じネイティブポリゴン)。 + densifyGeodesicRing(points) } else { points } From 79b9f43a73e3c0a4b3ebeb348f5f63895df46f82 Mon Sep 17 00:00:00 2001 From: Masashi Katsumata Date: Sat, 7 Nov 2026 23:25:58 -0800 Subject: [PATCH 13/23] Densify non-geodesic polygon rings, closing edge included A geodesic=false polygon passed its raw vertices to HERE, so every edge was a straight Web Mercator segment, unlike polylines with geodesic=false (linear lat/lng interpolation), the other providers and ios-for-here. Use android-sdk-core's densifyPolygonRing for both modes; it closes the ring before densifying, so the closing edge (last vertex -> first) matches the others (it replaces the unreleased densifyGeodesicRing). Requires the android-sdk-core release that adds densifyPolygonRing. --- .../polygon/HerePolygonOverlayRenderer.kt | 25 ++++++------------- 1 file changed, 8 insertions(+), 17 deletions(-) diff --git a/src/main/java/com/mapconductor/here/polygon/HerePolygonOverlayRenderer.kt b/src/main/java/com/mapconductor/here/polygon/HerePolygonOverlayRenderer.kt index 1cc4d3b..adf1b56 100644 --- a/src/main/java/com/mapconductor/here/polygon/HerePolygonOverlayRenderer.kt +++ b/src/main/java/com/mapconductor/here/polygon/HerePolygonOverlayRenderer.kt @@ -9,7 +9,7 @@ import com.mapconductor.core.ResourceProvider import com.mapconductor.core.features.GeoPoint import com.mapconductor.core.features.GeoPointInterface import com.mapconductor.core.features.GeoRectBounds -import com.mapconductor.core.geometry.densifyGeodesicRing +import com.mapconductor.core.geometry.densifyPolygonRing import com.mapconductor.core.normalizeLng import com.mapconductor.core.polygon.AbstractPolygonOverlayRenderer import com.mapconductor.core.polygon.PolygonEntityInterface @@ -238,14 +238,10 @@ class HerePolygonOverlayRenderer( points: List, geodesic: Boolean, ): List = - ( - if (geodesic) { - // 閉じる辺(末尾 → 先頭)も大圏で補間する(塗りと輪郭が同じネイティブポリゴン)。 - densifyGeodesicRing(points) - } else { - points - } - ).map { GeoCoordinates(it.latitude, normalizeLng(it.longitude)) } + // 閉じる辺(末尾 → 先頭)も他の辺と同じく補間する(塗りと輪郭が同じネイティブポリゴン)。 + // geodesic は大圏、geodesic=false は緯度経度の線形補間(ポリラインの false と同じ線)。 + densifyPolygonRing(points, geodesic) + .map { GeoCoordinates(it.latitude, normalizeLng(it.longitude)) } .let { pts -> if (pts.size >= 2 && pts.first() == pts.last()) pts.dropLast(1) else pts } /** [toRing] と同じ補間・正規化を、分割へ渡すため GeoPointInterface のまま返す。 */ @@ -253,14 +249,9 @@ class HerePolygonOverlayRenderer( points: List, geodesic: Boolean, ): List = - ( - if (geodesic) { - // 閉じる辺(末尾 → 先頭)も大圏で補間する(塗りと輪郭が同じネイティブポリゴン)。 - densifyGeodesicRing(points) - } else { - points - } - ).map { GeoPoint(latitude = it.latitude, longitude = normalizeLng(it.longitude)) } + // 閉じる辺(末尾 → 先頭)も他の辺と同じく補間する(塗りと輪郭が同じネイティブポリゴン)。 + // geodesic は大圏、geodesic=false は緯度経度の線形補間(ポリラインの false と同じ線)。 + densifyPolygonRing(points, geodesic).map { GeoPoint(latitude = it.latitude, longitude = normalizeLng(it.longitude)) } private fun boundsOf(points: List): GeoRectBounds? { if (points.isEmpty()) return null From 32fde1db329df07eb5d84016db9bc53048f0c81a Mon Sep 17 00:00:00 2001 From: Masashi Katsumata Date: Sat, 7 Nov 2026 23:10:01 -0800 Subject: [PATCH 14/23] Clear strategy markers in clearOverlays() Markers drawn through a StrategyMarkerController (clustering and other extension modules register these with registerOverlayController) were left on the map by clearOverlays(), which only cleared this provider's own controllers. Call BaseMapViewController.clearStrategyMarkerControllers(). Needs android-sdk-core with clearStrategyMarkerControllers() (fix/clear-strategy). --- src/main/java/com/mapconductor/here/HereMapViewController.kt | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/main/java/com/mapconductor/here/HereMapViewController.kt b/src/main/java/com/mapconductor/here/HereMapViewController.kt index 8150c0d..fa2e323 100644 --- a/src/main/java/com/mapconductor/here/HereMapViewController.kt +++ b/src/main/java/com/mapconductor/here/HereMapViewController.kt @@ -88,6 +88,8 @@ class HereMapViewController( groundImageController.clear() circleController.clear() rasterLayerController.clear() + // 拡張モジュール(クラスタリングなど)が登録した Strategy のマーカーも消す。 + clearStrategyMarkerControllers() } override fun setMarkerAnimationOverlayHost(host: MarkerAnimationOverlayHost?) { From 544673c84cbc5a2ea3fb9434e6fc173fbf9ec4c5 Mon Sep 17 00:00:00 2001 From: Masashi Katsumata Date: Sat, 7 Nov 2026 23:55:27 -0800 Subject: [PATCH 15/23] Put rasters and ground images under map items; separate draw-order bands Raster and ground image MapLayers had the default priority and were drawn above polygons, circles and polylines. Polygons and circles shared drawOrder 0..511. Rasters now render before the style's "route" layer and ground images before "traffic_on_route" (raster < ground image, both under map items). Map items get disjoint drawOrder bands: polygons 0..339, circles 340..679, polylines 680..1023. Marker tiles keep rendering last. Stacking order (all providers, all platforms), bottom to top: raster layers < ground images < polygons < circles < polylines < markers. Needs android-sdk-core with OverlayStacking (fix/overlay-stacking-order). --- api/android-for-here.api | 8 +++++ .../mapconductor/here/HereOverlayStacking.kt | 34 +++++++++++++++++++ .../here/circle/HereCircleOverlayRenderer.kt | 5 +-- .../HereGroundImageOverlayRenderer.kt | 3 ++ .../polygon/HerePolygonOverlayRenderer.kt | 7 ++-- .../polyline/HerePolylineOverlayRenderer.kt | 5 +-- .../raster/HereRasterLayerOverlayRenderer.kt | 15 ++++++++ 7 files changed, 70 insertions(+), 7 deletions(-) create mode 100644 src/main/java/com/mapconductor/here/HereOverlayStacking.kt diff --git a/api/android-for-here.api b/api/android-for-here.api index ecca64e..bca3220 100644 --- a/api/android-for-here.api +++ b/api/android-for-here.api @@ -184,6 +184,14 @@ public final class com.mapconductor.here.HereMapViewSaver extends com.mapconduct public com.mapconductor.core.map.MapViewStateInterface createState(java.lang.String, android.os.Bundle, com.mapconductor.core.map.MapCameraPosition); public java.lang.String getStateId(com.mapconductor.core.map.MapViewStateInterface); } +public final class com.mapconductor.here.HereOverlayStacking { + public static final com.mapconductor.here.HereOverlayStacking INSTANCE; + public final int polygonDrawOrder(int); + public final int circleDrawOrder(int); + public final int polylineDrawOrder(int); + public final com.here.sdk.mapview.MapLayerPriority rasterPriority(); + public final com.here.sdk.mapview.MapLayerPriority groundImagePriority(); +} public final class com.mapconductor.here.HereTypeAliasKt { } public final class com.mapconductor.here.HereViewControllerStoreKt { diff --git a/src/main/java/com/mapconductor/here/HereOverlayStacking.kt b/src/main/java/com/mapconductor/here/HereOverlayStacking.kt new file mode 100644 index 0000000..83f5257 --- /dev/null +++ b/src/main/java/com/mapconductor/here/HereOverlayStacking.kt @@ -0,0 +1,34 @@ +package com.mapconductor.here + +import com.here.sdk.mapview.MapLayerPriority +import com.here.sdk.mapview.MapLayerPriorityBuilder + +/** + * 重なり順(ラスター < GroundImage < ポリゴン < サークル < ポリライン < マーカー)。 + * + * HERE では: + * - ポリゴン・サークル・ポリラインは map item で、`drawOrder` を 1 本の数で比べる。 + * 帯ごとに区間を分けて割り当てる(帯の中は zIndex の順)。 + * - ラスターと GroundImage は MapLayer。既定の優先度だと map item より上に描かれて + * ポリゴン等を覆うので、ベースマップのレイヤー(ルートの手前)に入れる。 + * ラスター → GroundImage の順になるよう、別々のレイヤーの手前を指定する。 + * - マーカーは map item の上に描かれる(drawOrder はマーカーどうしの順)。 + */ +internal object HereOverlayStacking { + private const val BAND = 340 + + fun polygonDrawOrder(zIndex: Int): Int = zIndex.coerceIn(0, BAND - 1) + + fun circleDrawOrder(zIndex: Int): Int = BAND + zIndex.coerceIn(0, BAND - 1) + + fun polylineDrawOrder(zIndex: Int): Int = 2 * BAND + zIndex.coerceIn(0, 1023 - 2 * BAND) + + /** ラスター: ベースマップの "route" レイヤーの手前(GroundImage より下)。 */ + fun rasterPriority(): MapLayerPriority = MapLayerPriorityBuilder().renderedBeforeLayer(RASTER_ANCHOR).build() + + /** GroundImage: "traffic_on_route" レイヤーの手前(ラスターより上、map item より下)。 */ + fun groundImagePriority(): MapLayerPriority = MapLayerPriorityBuilder().renderedBeforeLayer(GROUND_IMAGE_ANCHOR).build() + + private const val RASTER_ANCHOR = "route" + private const val GROUND_IMAGE_ANCHOR = "traffic_on_route" +} diff --git a/src/main/java/com/mapconductor/here/circle/HereCircleOverlayRenderer.kt b/src/main/java/com/mapconductor/here/circle/HereCircleOverlayRenderer.kt index 650c875..37c5811 100644 --- a/src/main/java/com/mapconductor/here/circle/HereCircleOverlayRenderer.kt +++ b/src/main/java/com/mapconductor/here/circle/HereCircleOverlayRenderer.kt @@ -15,6 +15,7 @@ import com.mapconductor.core.features.normalize import com.mapconductor.core.geometry.circleToRing import com.mapconductor.core.geometry.closeRing import com.mapconductor.here.HereActualCircle +import com.mapconductor.here.HereOverlayStacking import com.mapconductor.here.HereViewHolder import com.mapconductor.here.toGeoCoordinates import kotlinx.coroutines.CoroutineScope @@ -36,7 +37,7 @@ class HereCircleOverlayRenderer( Color.valueOf(state.strokeColor.toArgb()), lineWidth, ).apply { - drawOrder = (state.zIndex ?: 0).coerceIn(0, 511) + drawOrder = HereOverlayStacking.circleDrawOrder(state.zIndex ?: 0) } coroutine.launch { holder.map.addMapPolygon(mapCircle) @@ -96,7 +97,7 @@ class HereCircleOverlayRenderer( ) } if (finger.zIndex != prevFinger.zIndex) { - current.circle.drawOrder = (current.state.zIndex ?: 0).coerceIn(0, 511) + current.circle.drawOrder = HereOverlayStacking.circleDrawOrder(current.state.zIndex ?: 0) } circle diff --git a/src/main/java/com/mapconductor/here/groundimage/HereGroundImageOverlayRenderer.kt b/src/main/java/com/mapconductor/here/groundimage/HereGroundImageOverlayRenderer.kt index 55f48f4..3783659 100644 --- a/src/main/java/com/mapconductor/here/groundimage/HereGroundImageOverlayRenderer.kt +++ b/src/main/java/com/mapconductor/here/groundimage/HereGroundImageOverlayRenderer.kt @@ -12,6 +12,7 @@ import com.mapconductor.core.groundimage.GroundImageState import com.mapconductor.core.groundimage.GroundImageTileProvider import com.mapconductor.core.tileserver.LocalTileServer import com.mapconductor.here.HereActualGroundImage +import com.mapconductor.here.HereOverlayStacking import com.mapconductor.here.HereViewHolder import android.util.Log import kotlinx.coroutines.CoroutineScope @@ -136,6 +137,8 @@ class HereGroundImageOverlayRenderer( MapLayerBuilder() .withName(layerName) .withDataSource(config.name, MapContentType.RASTER_IMAGE) + // GroundImage の帯(ラスターの上、ポリゴン等の map item の下)。 + .withPriority(HereOverlayStacking.groundImagePriority()) .forMap(holder.mapView.hereMap) .build() HereGroundImageHandle( diff --git a/src/main/java/com/mapconductor/here/polygon/HerePolygonOverlayRenderer.kt b/src/main/java/com/mapconductor/here/polygon/HerePolygonOverlayRenderer.kt index adf1b56..1b602f3 100644 --- a/src/main/java/com/mapconductor/here/polygon/HerePolygonOverlayRenderer.kt +++ b/src/main/java/com/mapconductor/here/polygon/HerePolygonOverlayRenderer.kt @@ -17,6 +17,7 @@ import com.mapconductor.core.polygon.PolygonState import com.mapconductor.core.polygon.splitPolygonWithHolesIntoSimpleRings import com.mapconductor.core.polygon.unionHoles import com.mapconductor.here.HereActualPolygon +import com.mapconductor.here.HereOverlayStacking import com.mapconductor.here.HereViewHolder import android.util.Log import kotlinx.coroutines.CoroutineScope @@ -145,7 +146,7 @@ class HerePolygonOverlayRenderer( } } if (finger.zIndex != prevFinger.zIndex) { - polygon.forEach { it.drawOrder = current.state.zIndex.coerceIn(0, 511) } + polygon.forEach { it.drawOrder = HereOverlayStacking.polygonDrawOrder(current.state.zIndex) } } polygon @@ -161,7 +162,7 @@ class HerePolygonOverlayRenderer( val strokeWidth = ResourceProvider.dpToPx(state.strokeWidth) val transparentFill = Color.valueOf(0f, 0f, 0f, 0f) val fillColor = Color.valueOf(state.fillColor.toArgb()) - val order = state.zIndex.coerceIn(0, 511) + val order = HereOverlayStacking.polygonDrawOrder(state.zIndex) buildList { // 塗り: 穴を持たないピース群へ分解し、1 ピース 1 枚で塗る。 @@ -231,7 +232,7 @@ class HerePolygonOverlayRenderer( Color.valueOf(state.fillColor.toArgb()), Color.valueOf(state.strokeColor.toArgb()), outlineWidth, - ).apply { drawOrder = state.zIndex.coerceIn(0, 511) } + ).apply { drawOrder = HereOverlayStacking.polygonDrawOrder(state.zIndex) } } private fun toRing( diff --git a/src/main/java/com/mapconductor/here/polyline/HerePolylineOverlayRenderer.kt b/src/main/java/com/mapconductor/here/polyline/HerePolylineOverlayRenderer.kt index 6bc12e1..df4398a 100644 --- a/src/main/java/com/mapconductor/here/polyline/HerePolylineOverlayRenderer.kt +++ b/src/main/java/com/mapconductor/here/polyline/HerePolylineOverlayRenderer.kt @@ -16,6 +16,7 @@ import com.mapconductor.core.polyline.PolylineState import com.mapconductor.core.spherical.Planar import com.mapconductor.core.spherical.WGS84Geodesic import com.mapconductor.here.HereActualPolyline +import com.mapconductor.here.HereOverlayStacking import com.mapconductor.here.HereViewHolder import com.mapconductor.here.toGeoCoordinates import kotlinx.coroutines.CoroutineScope @@ -32,7 +33,7 @@ class HerePolylineOverlayRenderer( val representation = createRepresentation(state) val mapPolyline = MapPolyline(geoPolyline, representation).apply { - drawOrder = (state.zIndex + 512).coerceIn(512, 1023) + drawOrder = HereOverlayStacking.polylineDrawOrder(state.zIndex) } coroutine.launch { @@ -66,7 +67,7 @@ class HerePolylineOverlayRenderer( } if (finger.zIndex != prevFinger.zIndex) { - polyline.drawOrder = (current.state.zIndex + 512).coerceIn(512, 1023) + polyline.drawOrder = HereOverlayStacking.polylineDrawOrder(current.state.zIndex) needsReAdd = true } diff --git a/src/main/java/com/mapconductor/here/raster/HereRasterLayerOverlayRenderer.kt b/src/main/java/com/mapconductor/here/raster/HereRasterLayerOverlayRenderer.kt index f81b068..212000a 100644 --- a/src/main/java/com/mapconductor/here/raster/HereRasterLayerOverlayRenderer.kt +++ b/src/main/java/com/mapconductor/here/raster/HereRasterLayerOverlayRenderer.kt @@ -3,6 +3,8 @@ package com.mapconductor.here.raster import com.here.sdk.mapview.MapContentType import com.here.sdk.mapview.MapLayer import com.here.sdk.mapview.MapLayerBuilder +import com.here.sdk.mapview.MapLayerPriority +import com.here.sdk.mapview.MapLayerPriorityBuilder import com.here.sdk.mapview.datasource.RasterDataSource import com.here.sdk.mapview.datasource.RasterDataSourceConfiguration import com.here.sdk.mapview.datasource.RasterTileSource @@ -19,6 +21,7 @@ import com.mapconductor.core.raster.TileScheme import com.mapconductor.core.tileserver.LocalTileServer import com.mapconductor.core.tileserver.TileProviderInterface import com.mapconductor.core.tileserver.TileRequest +import com.mapconductor.here.HereOverlayStacking import com.mapconductor.here.HereViewHolder import java.io.ByteArrayOutputStream import java.net.HttpURLConnection @@ -132,6 +135,7 @@ class HereRasterLayerOverlayRenderer( MapLayerBuilder() .withName(tileSpec.layerName) .withDataSource(tileSpec.sourceName, MapContentType.RASTER_IMAGE) + .withPriority(priorityFor(state)) .forMap(holder.mapView.hereMap) .build() layer.setEnabled(state.visible) @@ -150,6 +154,17 @@ class HereRasterLayerOverlayRenderer( } } + /** + * アプリのラスターはラスターの帯(GroundImage・map item の下)。マーカーのタイルは + * マーカーの帯なので、ポリゴン等の map item より上(最後に描く)。 + */ + private fun priorityFor(state: RasterLayerState): MapLayerPriority = + if (state.id.startsWith("marker-tile-")) { + MapLayerPriorityBuilder().renderedLast().build() + } else { + HereOverlayStacking.rasterPriority() + } + private fun updateLayer( handle: HereRasterLayerHandle, state: RasterLayerState, From 1923dc1dc7cea1903379fda3f951b521d150b037 Mon Sep 17 00:00:00 2001 From: Masashi Katsumata Date: Mon, 9 Nov 2026 06:51:43 -0800 Subject: [PATCH 16/23] Stack the polygon tiles at the bottom of the polygon band With develop's OverlayStacking, a raster layer goes in the raster band, under ground images. The polygon tiles are polygons drawn as images, so they go over ground images and under circles, polylines and markers. --- src/main/java/com/mapconductor/here/HereOverlayStacking.kt | 6 ++++++ .../here/raster/HereRasterLayerOverlayRenderer.kt | 6 +++++- 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/mapconductor/here/HereOverlayStacking.kt b/src/main/java/com/mapconductor/here/HereOverlayStacking.kt index 83f5257..abb1a8b 100644 --- a/src/main/java/com/mapconductor/here/HereOverlayStacking.kt +++ b/src/main/java/com/mapconductor/here/HereOverlayStacking.kt @@ -29,6 +29,12 @@ internal object HereOverlayStacking { /** GroundImage: "traffic_on_route" レイヤーの手前(ラスターより上、map item より下)。 */ fun groundImagePriority(): MapLayerPriority = MapLayerPriorityBuilder().renderedBeforeLayer(GROUND_IMAGE_ANCHOR).build() + /** + * ポリゴンのタイル(SDK が描くラスター): ポリゴンの帯の一番下。GroundImage のアンカー + * "traffic_on_route" の直後(GroundImage より上、map item より下)。 + */ + fun polygonTilePriority(): MapLayerPriority = MapLayerPriorityBuilder().renderedAfterLayer(GROUND_IMAGE_ANCHOR).build() + private const val RASTER_ANCHOR = "route" private const val GROUND_IMAGE_ANCHOR = "traffic_on_route" } diff --git a/src/main/java/com/mapconductor/here/raster/HereRasterLayerOverlayRenderer.kt b/src/main/java/com/mapconductor/here/raster/HereRasterLayerOverlayRenderer.kt index 212000a..53638d3 100644 --- a/src/main/java/com/mapconductor/here/raster/HereRasterLayerOverlayRenderer.kt +++ b/src/main/java/com/mapconductor/here/raster/HereRasterLayerOverlayRenderer.kt @@ -13,6 +13,7 @@ import com.here.sdk.mapview.datasource.TileSource import com.here.sdk.mapview.datasource.TileUrlProviderCallback import com.here.sdk.mapview.datasource.TileUrlProviderFactory import com.here.sdk.mapview.datasource.TilingScheme +import com.mapconductor.core.polygon.POLYGON_TILE_LAYER_ID import com.mapconductor.core.raster.RasterLayerEntityInterface import com.mapconductor.core.raster.RasterLayerOverlayRendererInterface import com.mapconductor.core.raster.RasterLayerSource @@ -156,11 +157,14 @@ class HereRasterLayerOverlayRenderer( /** * アプリのラスターはラスターの帯(GroundImage・map item の下)。マーカーのタイルは - * マーカーの帯なので、ポリゴン等の map item より上(最後に描く)。 + * マーカーの帯なので、ポリゴン等の map item より上(最後に描く)。ポリゴンのタイルは + * ポリゴンの帯の一番下(GroundImage の上、map item の下)。 */ private fun priorityFor(state: RasterLayerState): MapLayerPriority = if (state.id.startsWith("marker-tile-")) { MapLayerPriorityBuilder().renderedLast().build() + } else if (state.id == POLYGON_TILE_LAYER_ID) { + HereOverlayStacking.polygonTilePriority() } else { HereOverlayStacking.rasterPriority() } From d94b6ac7ed31e2d4bb3da1eace2f087e33cf81ec Mon Sep 17 00:00:00 2001 From: Masashi Katsumata Date: Mon, 9 Nov 2026 06:55:03 -0800 Subject: [PATCH 17/23] Update the API baseline Additions only: the polygon tiles' stacking key, and declarations develop added without running apiDump (TILE_REFRESH_COALESCE, and on ArcGIS the marker controller's constructor that takes a boolean). --- api/android-for-here.api | 1 + 1 file changed, 1 insertion(+) diff --git a/api/android-for-here.api b/api/android-for-here.api index bca3220..e3ef70e 100644 --- a/api/android-for-here.api +++ b/api/android-for-here.api @@ -191,6 +191,7 @@ public final class com.mapconductor.here.HereOverlayStacking { public final int polylineDrawOrder(int); public final com.here.sdk.mapview.MapLayerPriority rasterPriority(); public final com.here.sdk.mapview.MapLayerPriority groundImagePriority(); + public final com.here.sdk.mapview.MapLayerPriority polygonTilePriority(); } public final class com.mapconductor.here.HereTypeAliasKt { } From 45c8b1289db15d4e09a5b9c7aacb29c23665830f Mon Sep 17 00:00:00 2001 From: Masashi Katsumata Date: Mon, 9 Nov 2026 09:38:06 -0800 Subject: [PATCH 18/23] Draw large polyline sets as raster tiles (PolylineTiler) The polyline controller gets a PolylineTiler, shown through the same raster layer path as the polygon tiles. HERE's map items are one layer, so the tiles go under them, above the polygon tiles (placed against each other by layer name). Whatever redraws from the polyline manager skips tiled entities (no native line). --- api/android-for-here.api | 2 ++ .../here/HereMapViewController.kt | 15 +++++++++++++ .../mapconductor/here/HereOverlayStacking.kt | 22 ++++++++++++++++++- .../raster/HereRasterLayerOverlayRenderer.kt | 22 +++++++++++++++++-- 4 files changed, 58 insertions(+), 3 deletions(-) diff --git a/api/android-for-here.api b/api/android-for-here.api index e3ef70e..e2b5f04 100644 --- a/api/android-for-here.api +++ b/api/android-for-here.api @@ -192,6 +192,8 @@ public final class com.mapconductor.here.HereOverlayStacking { public final com.here.sdk.mapview.MapLayerPriority rasterPriority(); public final com.here.sdk.mapview.MapLayerPriority groundImagePriority(); public final com.here.sdk.mapview.MapLayerPriority polygonTilePriority(); + public final com.here.sdk.mapview.MapLayerPriority polygonTilePriority(java.lang.String); + public final com.here.sdk.mapview.MapLayerPriority polylineTilePriority(java.lang.String); } public final class com.mapconductor.here.HereTypeAliasKt { } diff --git a/src/main/java/com/mapconductor/here/HereMapViewController.kt b/src/main/java/com/mapconductor/here/HereMapViewController.kt index 3c18070..4f18cf1 100644 --- a/src/main/java/com/mapconductor/here/HereMapViewController.kt +++ b/src/main/java/com/mapconductor/here/HereMapViewController.kt @@ -32,7 +32,10 @@ import com.mapconductor.core.marker.StrategyMarkerController import com.mapconductor.core.marker.dispatchGeoMarkerClick import com.mapconductor.core.polygon.OnPolygonEventHandler import com.mapconductor.core.polyline.OnPolylineEventHandler +import com.mapconductor.core.polyline.POLYLINE_TILE_LAYER_ID import com.mapconductor.core.polyline.PolylineState +import com.mapconductor.core.polyline.PolylineTiler +import com.mapconductor.core.polyline.polylineTileRasterLayerState import com.mapconductor.here.circle.HereCircleController import com.mapconductor.here.groundimage.HereGroundImageController import com.mapconductor.here.marker.HereMarkerController @@ -185,6 +188,18 @@ class HereMapViewController( } } } + + // Many polylines too: the same raster layer path, in the polyline band. + polylineController.tiler = + PolylineTiler().apply { + onTemplate = { template, tileSize -> + if (template != null) { + rasterLayerController.upsert(polylineTileRasterLayerState(template, tileSize)) + } else { + rasterLayerController.removeById(POLYLINE_TILE_LAYER_ID) + } + } + } } override fun moveCamera(position: MapCameraPosition) = handleMoveCamera(position) diff --git a/src/main/java/com/mapconductor/here/HereOverlayStacking.kt b/src/main/java/com/mapconductor/here/HereOverlayStacking.kt index abb1a8b..571998b 100644 --- a/src/main/java/com/mapconductor/here/HereOverlayStacking.kt +++ b/src/main/java/com/mapconductor/here/HereOverlayStacking.kt @@ -33,7 +33,27 @@ internal object HereOverlayStacking { * ポリゴンのタイル(SDK が描くラスター): ポリゴンの帯の一番下。GroundImage のアンカー * "traffic_on_route" の直後(GroundImage より上、map item より下)。 */ - fun polygonTilePriority(): MapLayerPriority = MapLayerPriorityBuilder().renderedAfterLayer(GROUND_IMAGE_ANCHOR).build() + fun polygonTilePriority(): MapLayerPriority = polygonTilePriority(beforeLayer = null) + + /** [polygonTilePriority]; when the polyline tiles are already on the map, just below them ([beforeLayer]). */ + fun polygonTilePriority(beforeLayer: String?): MapLayerPriority = + if (beforeLayer != null) { + MapLayerPriorityBuilder().renderedBeforeLayer(beforeLayer).build() + } else { + MapLayerPriorityBuilder().renderedAfterLayer(GROUND_IMAGE_ANCHOR).build() + } + + /** + * ポリラインのタイル(SDK が描くラスター): ポリゴンのタイルの上([afterLayer]、無ければ + * GroundImage のアンカーの直後)、map item の下。 + * + * HERE の map item(ポリゴン・サークル・ポリライン)は 1 枚の層にまとめて描かれ、 + * MapLayer をサークルとポリラインの間に挟めない。map item の下に置くので、ネイティブの + * ポリゴン・サークルもこのタイルの上に来る(帯の決まりからの、HERE だけの差)。 + * マーカーとマーカーのタイルより下、ポリゴンのタイルより上は守る。 + */ + fun polylineTilePriority(afterLayer: String?): MapLayerPriority = + MapLayerPriorityBuilder().renderedAfterLayer(afterLayer ?: GROUND_IMAGE_ANCHOR).build() private const val RASTER_ANCHOR = "route" private const val GROUND_IMAGE_ANCHOR = "traffic_on_route" diff --git a/src/main/java/com/mapconductor/here/raster/HereRasterLayerOverlayRenderer.kt b/src/main/java/com/mapconductor/here/raster/HereRasterLayerOverlayRenderer.kt index 53638d3..99b0943 100644 --- a/src/main/java/com/mapconductor/here/raster/HereRasterLayerOverlayRenderer.kt +++ b/src/main/java/com/mapconductor/here/raster/HereRasterLayerOverlayRenderer.kt @@ -14,6 +14,7 @@ import com.here.sdk.mapview.datasource.TileUrlProviderCallback import com.here.sdk.mapview.datasource.TileUrlProviderFactory import com.here.sdk.mapview.datasource.TilingScheme import com.mapconductor.core.polygon.POLYGON_TILE_LAYER_ID +import com.mapconductor.core.polyline.POLYLINE_TILE_LAYER_ID import com.mapconductor.core.raster.RasterLayerEntityInterface import com.mapconductor.core.raster.RasterLayerOverlayRendererInterface import com.mapconductor.core.raster.RasterLayerSource @@ -140,6 +141,7 @@ class HereRasterLayerOverlayRenderer( .forMap(holder.mapView.hereMap) .build() layer.setEnabled(state.visible) + if (isShapeTileLayer(state.id)) shapeTileLayers.add(state.id) HereRasterLayerHandle( dataSource = dataSource, layer = layer, @@ -155,20 +157,35 @@ class HereRasterLayerOverlayRenderer( } } + /** The SDK's shape tile layers on the map now (their ids), so each can be placed against the other. */ + private val shapeTileLayers = java.util.Collections.synchronizedSet(HashSet()) + /** * アプリのラスターはラスターの帯(GroundImage・map item の下)。マーカーのタイルは * マーカーの帯なので、ポリゴン等の map item より上(最後に描く)。ポリゴンのタイルは - * ポリゴンの帯の一番下(GroundImage の上、map item の下)。 + * ポリゴンの帯の一番下(GroundImage の上、map item の下)。ポリラインのタイルはその上 + * ([HereOverlayStacking.polylineTilePriority])。どちらも版が変わるたびに作り直すので、 + * もう片方があればそれを基準に置き、作った順に左右されないようにする。 */ private fun priorityFor(state: RasterLayerState): MapLayerPriority = if (state.id.startsWith("marker-tile-")) { MapLayerPriorityBuilder().renderedLast().build() } else if (state.id == POLYGON_TILE_LAYER_ID) { - HereOverlayStacking.polygonTilePriority() + HereOverlayStacking.polygonTilePriority( + beforeLayer = layerNameOf(POLYLINE_TILE_LAYER_ID).takeIf { POLYLINE_TILE_LAYER_ID in shapeTileLayers }, + ) + } else if (state.id == POLYLINE_TILE_LAYER_ID) { + HereOverlayStacking.polylineTilePriority( + afterLayer = layerNameOf(POLYGON_TILE_LAYER_ID).takeIf { POLYGON_TILE_LAYER_ID in shapeTileLayers }, + ) } else { HereOverlayStacking.rasterPriority() } + private fun layerNameOf(id: String) = "raster-layer-$id" + + private fun isShapeTileLayer(id: String) = id == POLYGON_TILE_LAYER_ID || id == POLYLINE_TILE_LAYER_ID + private fun updateLayer( handle: HereRasterLayerHandle, state: RasterLayerState, @@ -178,6 +195,7 @@ class HereRasterLayerOverlayRenderer( private fun removeLayer(entity: RasterLayerEntityInterface) { val handle = entity.layer + if (isShapeTileLayer(entity.state.id)) shapeTileLayers.remove(entity.state.id) handle.routeId?.let { tileServer.unregister(it) } handle.layer.destroy() handle.dataSource.destroy() From ce49fb2f28d610449fb6bc3b81604a964d44a12d Mon Sep 17 00:00:00 2001 From: Masashi Katsumata Date: Tue, 10 Nov 2026 16:16:50 -0800 Subject: [PATCH 19/23] Support bulk Circles with raster tiles --- .../com/mapconductor/here/HereMapViewController.kt | 13 +++++++++++++ .../here/raster/HereRasterLayerOverlayRenderer.kt | 11 +++++++++-- 2 files changed, 22 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/mapconductor/here/HereMapViewController.kt b/src/main/java/com/mapconductor/here/HereMapViewController.kt index 4f18cf1..7e96fcf 100644 --- a/src/main/java/com/mapconductor/here/HereMapViewController.kt +++ b/src/main/java/com/mapconductor/here/HereMapViewController.kt @@ -1,5 +1,8 @@ package com.mapconductor.here +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.polygon.POLYGON_TILE_LAYER_ID import com.mapconductor.core.polygon.PolygonTiler import com.mapconductor.core.polygon.polygonTileRasterLayerState @@ -200,6 +203,16 @@ class HereMapViewController( } } } + circleController.tiler = + CircleTiler().apply { + onTemplate = { template, tileSize -> + if (template != null) { + rasterLayerController.upsert(circleTileRasterLayerState(template, tileSize)) + } else { + rasterLayerController.removeById(CIRCLE_TILE_LAYER_ID) + } + } + } } override fun moveCamera(position: MapCameraPosition) = handleMoveCamera(position) diff --git a/src/main/java/com/mapconductor/here/raster/HereRasterLayerOverlayRenderer.kt b/src/main/java/com/mapconductor/here/raster/HereRasterLayerOverlayRenderer.kt index 99b0943..4b15c86 100644 --- a/src/main/java/com/mapconductor/here/raster/HereRasterLayerOverlayRenderer.kt +++ b/src/main/java/com/mapconductor/here/raster/HereRasterLayerOverlayRenderer.kt @@ -14,6 +14,7 @@ import com.here.sdk.mapview.datasource.TileUrlProviderCallback import com.here.sdk.mapview.datasource.TileUrlProviderFactory import com.here.sdk.mapview.datasource.TilingScheme import com.mapconductor.core.polygon.POLYGON_TILE_LAYER_ID +import com.mapconductor.core.circle.CIRCLE_TILE_LAYER_ID import com.mapconductor.core.polyline.POLYLINE_TILE_LAYER_ID import com.mapconductor.core.raster.RasterLayerEntityInterface import com.mapconductor.core.raster.RasterLayerOverlayRendererInterface @@ -171,12 +172,18 @@ class HereRasterLayerOverlayRenderer( if (state.id.startsWith("marker-tile-")) { MapLayerPriorityBuilder().renderedLast().build() } else if (state.id == POLYGON_TILE_LAYER_ID) { + HereOverlayStacking.polygonTilePriority( + beforeLayer = layerNameOf(CIRCLE_TILE_LAYER_ID).takeIf { CIRCLE_TILE_LAYER_ID in shapeTileLayers } + ?: layerNameOf(POLYLINE_TILE_LAYER_ID).takeIf { POLYLINE_TILE_LAYER_ID in shapeTileLayers }, + ) + } else if (state.id == CIRCLE_TILE_LAYER_ID) { HereOverlayStacking.polygonTilePriority( beforeLayer = layerNameOf(POLYLINE_TILE_LAYER_ID).takeIf { POLYLINE_TILE_LAYER_ID in shapeTileLayers }, ) } else if (state.id == POLYLINE_TILE_LAYER_ID) { HereOverlayStacking.polylineTilePriority( - afterLayer = layerNameOf(POLYGON_TILE_LAYER_ID).takeIf { POLYGON_TILE_LAYER_ID in shapeTileLayers }, + afterLayer = layerNameOf(CIRCLE_TILE_LAYER_ID).takeIf { CIRCLE_TILE_LAYER_ID in shapeTileLayers } + ?: layerNameOf(POLYGON_TILE_LAYER_ID).takeIf { POLYGON_TILE_LAYER_ID in shapeTileLayers }, ) } else { HereOverlayStacking.rasterPriority() @@ -184,7 +191,7 @@ class HereRasterLayerOverlayRenderer( private fun layerNameOf(id: String) = "raster-layer-$id" - private fun isShapeTileLayer(id: String) = id == POLYGON_TILE_LAYER_ID || id == POLYLINE_TILE_LAYER_ID + private fun isShapeTileLayer(id: String) = id == POLYGON_TILE_LAYER_ID || id == CIRCLE_TILE_LAYER_ID || id == POLYLINE_TILE_LAYER_ID private fun updateLayer( handle: HereRasterLayerHandle, From 472aa67e16c92c81b17b9e94bfdcbb60922791d0 Mon Sep 17 00:00:00 2001 From: Masashi Katsumata Date: Wed, 11 Nov 2026 11:41:04 -0800 Subject: [PATCH 20/23] Order markers with MarkerDrawOrder drawOrder is an integer, so it uses MarkerDrawOrder.ofInt: zIndex first, then south and west. Unspecified markers in the southern hemisphere no longer outrank an explicit zIndex. --- .../java/com/mapconductor/here/marker/HereMarkerRenderer.kt | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/mapconductor/here/marker/HereMarkerRenderer.kt b/src/main/java/com/mapconductor/here/marker/HereMarkerRenderer.kt index 92a8e4d..e1f2f72 100644 --- a/src/main/java/com/mapconductor/here/marker/HereMarkerRenderer.kt +++ b/src/main/java/com/mapconductor/here/marker/HereMarkerRenderer.kt @@ -2,9 +2,9 @@ package com.mapconductor.here.marker import com.here.sdk.core.Metadata import com.here.sdk.mapview.MapMarker -import com.mapconductor.core.calculateZIndex import com.mapconductor.core.features.GeoPoint import com.mapconductor.core.marker.AbstractMarkerOverlayRenderer +import com.mapconductor.core.marker.MarkerDrawOrder import com.mapconductor.core.marker.MarkerEntityInterface import com.mapconductor.core.marker.MarkerOverlayRendererInterface import com.mapconductor.here.HereActualMarker @@ -27,8 +27,9 @@ class HereMarkerRenderer( holder = holder, coroutine = coroutine, ) { + // HERE の drawOrder は整数。zIndex が第 1 キー、同じなら南(さらに西)が手前。 private fun resolveDrawOrder(state: com.mapconductor.core.marker.MarkerState): Int = - state.zIndex ?: calculateZIndex(state.position) + MarkerDrawOrder.ofInt(state.zIndex, state.position) override val supportsAnimationOverlay: Boolean = true From 678d9363502b805724d840035d49ac103d09381d Mon Sep 17 00:00:00 2001 From: Masashi Katsumata Date: Wed, 11 Nov 2026 15:00:56 -0800 Subject: [PATCH 21/23] Rank markers into HERE's usable drawOrder range HERE ignores large drawOrder values: on the TB520FU 2849 worked and 4274 fell back to add order, so the old zIndex * 1e6 encoding let an unspecified marker cover zIndex 1. Markers are now ranked by MarkerDrawOrder and given 0..2047, re-ranked on add, change and rotation. --- api/android-for-here.api | 1 + .../here/marker/HereMarkerRenderer.kt | 42 +++++++++++++++---- 2 files changed, 36 insertions(+), 7 deletions(-) diff --git a/api/android-for-here.api b/api/android-for-here.api index e2b5f04..500f5d5 100644 --- a/api/android-for-here.api +++ b/api/android-for-here.api @@ -322,6 +322,7 @@ public final class com.mapconductor.here.marker.HereMarkerController$Companion { public final class com.mapconductor.here.marker.HereMarkerRenderer extends com.mapconductor.core.marker.AbstractMarkerOverlayRenderer { public com.mapconductor.here.marker.HereMarkerRenderer(com.mapconductor.here.HereViewHolder, kotlinx.coroutines.CoroutineScope); public com.mapconductor.here.marker.HereMarkerRenderer(com.mapconductor.here.HereViewHolder, kotlinx.coroutines.CoroutineScope, int, kotlin.jvm.internal.DefaultConstructorMarker); + protected java.lang.Object applyDrawOrder(java.util.List>, kotlin.coroutines.Continuation); public boolean getSupportsAnimationOverlay(); public void setMarkerVisible(com.mapconductor.core.marker.MarkerEntityInterface, boolean); public void setMarkerPosition(com.mapconductor.core.marker.MarkerEntityInterface, com.mapconductor.core.features.GeoPoint); diff --git a/src/main/java/com/mapconductor/here/marker/HereMarkerRenderer.kt b/src/main/java/com/mapconductor/here/marker/HereMarkerRenderer.kt index e1f2f72..d9c393f 100644 --- a/src/main/java/com/mapconductor/here/marker/HereMarkerRenderer.kt +++ b/src/main/java/com/mapconductor/here/marker/HereMarkerRenderer.kt @@ -4,9 +4,9 @@ import com.here.sdk.core.Metadata import com.here.sdk.mapview.MapMarker import com.mapconductor.core.features.GeoPoint import com.mapconductor.core.marker.AbstractMarkerOverlayRenderer -import com.mapconductor.core.marker.MarkerDrawOrder import com.mapconductor.core.marker.MarkerEntityInterface import com.mapconductor.core.marker.MarkerOverlayRendererInterface +import com.mapconductor.core.marker.MarkerState import com.mapconductor.here.HereActualMarker import com.mapconductor.here.HereViewHolder import com.mapconductor.here.toAnchor2D @@ -16,6 +16,7 @@ import java.io.Serializable import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext class HereMarkerRenderer( holder: HereViewHolder, @@ -27,9 +28,32 @@ class HereMarkerRenderer( holder = holder, coroutine = coroutine, ) { - // HERE の drawOrder は整数。zIndex が第 1 キー、同じなら南(さらに西)が手前。 - private fun resolveDrawOrder(state: com.mapconductor.core.marker.MarkerState): Int = - MarkerDrawOrder.ofInt(state.zIndex, state.position) + // HERE の drawOrder は整数で、しかも小さい値でしか効かない(タブレットの実機で 2849 は + // 効き、4274 以上は無視されて足した順になった)。zIndex と位置を 1 つの値に詰める余地が + // 無いので、全マーカーを [drawOrderOf](zIndex が第 1 キー、同じなら画面で下が手前)で + // 並べた順位を 0..[MAX_DRAW_ORDER] に割り振る。足す・変える・地図が回るたびに振り直す。 + private val live = LinkedHashMap>() + + private fun track( + marker: MapMarker, + state: MarkerState, + ) = synchronized(live) { live[state.id] = marker to state } + + private suspend fun assignDrawOrders() { + val sorted = synchronized(live) { live.values.toList() }.sortedBy { (_, state) -> drawOrderOf(state) } + if (sorted.isEmpty()) return + val last = (sorted.size - 1).coerceAtLeast(1).toLong() + withContext(coroutine.coroutineContext) { + sorted.forEachIndexed { i, (marker, _) -> + // 数が多いと順位を間引く(隣どうしが同じ値になり、その間だけ足した順になる)。 + val order = if (sorted.size <= MAX_DRAW_ORDER + 1) i else (i * MAX_DRAW_ORDER / last).toInt() + if (marker.drawOrder != order) marker.drawOrder = order + } + } + } + + // 地図が回ったら、今の向きで順位を振り直す。 + override suspend fun applyDrawOrder(entities: List>) = assignDrawOrders() override val supportsAnimationOverlay: Boolean = true @@ -66,7 +90,6 @@ class HereMarkerRenderer( params.bitmapIcon.toMapImage(), params.bitmapIcon.toAnchor2D(), ).apply { - drawOrder = resolveDrawOrder(params.state) metadata = Metadata().apply { // Always include MapConductor marker id @@ -75,6 +98,7 @@ class HereMarkerRenderer( putExtras(params.state.extra) } } + track(marker, params.state) return@map marker } @@ -85,6 +109,7 @@ class HereMarkerRenderer( } override suspend fun onRemove(data: List>) { + synchronized(live) { data.forEach { live.remove(it.state.id) } } coroutine.launch { val markers: List = data.mapNotNull { params -> params.marker } if (markers.isNotEmpty()) { @@ -94,7 +119,7 @@ class HereMarkerRenderer( } override suspend fun onPostProcess() { - // Do nothing here + assignDrawOrders() } override suspend fun onChange( @@ -112,13 +137,16 @@ class HereMarkerRenderer( } marker.coordinates = GeoPoint.from(params.current.state.position).toGeoCoordinates() - marker.drawOrder = resolveDrawOrder(params.current.state) + track(marker, params.current.state) // Hereはマーカーを再作成しなくてよいので、同じマーカーのインスタンスを返す marker } } +/** マーカーの drawOrder に使う上限。実機で効いた最大(2849)より小さく取る。 */ +private const val MAX_DRAW_ORDER = 2047 + // Convert MarkerState.extra into HERE Metadata entries. // Supports Map by best-effort type mapping; otherwise stores value as string under key "mc:extra". private fun Metadata.putExtras(extra: Serializable?) { From 73eb4604f98ebe267c4e442347c5ab9122e81c4f Mon Sep 17 00:00:00 2001 From: Masashi Katsumata Date: Wed, 11 Nov 2026 22:29:04 -0800 Subject: [PATCH 22/23] Apply camera paddings and report fov on HERE The principal point is not used: it is not part of the flyTo animation and jumps when set. Paddings are emulated by moving the camera center and undone on read. HERE has no fov getter, so it is measured from the live camera: distanceToTarget times the px a sideways metre moves at the target gives the focal length (about 3550 px on TB520FU regardless of map size, orientation or density), and fov follows from the map height (44.6 in full-screen portrait, 28.6 in landscape). --- api/android-for-here.api | 3 + .../here/HereMapViewController.kt | 15 +++++ .../here/HereMapViewControllerCamera.kt | 56 ++++++++++++++++++- .../mapconductor/here/MapCameraPosition.kt | 1 + 4 files changed, 72 insertions(+), 3 deletions(-) diff --git a/api/android-for-here.api b/api/android-for-here.api index e2b5f04..309e9fb 100644 --- a/api/android-for-here.api +++ b/api/android-for-here.api @@ -156,6 +156,9 @@ public final class com.mapconductor.here.HereMapViewController extends com.mapco public final class com.mapconductor.here.HereMapViewController$Companion { } public final class com.mapconductor.here.HereMapViewControllerCameraKt { + public static final double viewportHeightDp(com.mapconductor.here.HereMapViewController); + public static final java.lang.Double verticalFov(com.mapconductor.here.HereMapViewController); + public static final com.mapconductor.core.map.MapCameraPosition toNativeCamera(com.mapconductor.here.HereMapViewController, com.mapconductor.core.map.MapCameraPosition); public static final void handleMoveCamera(com.mapconductor.here.HereMapViewController, com.mapconductor.core.map.MapCameraPosition); public static final void handleAnimateCamera(com.mapconductor.here.HereMapViewController, com.mapconductor.core.map.MapCameraPosition, long); public static final void handleFitBounds(com.mapconductor.here.HereMapViewController, com.mapconductor.core.features.GeoRectBounds, int); diff --git a/src/main/java/com/mapconductor/here/HereMapViewController.kt b/src/main/java/com/mapconductor/here/HereMapViewController.kt index 7e96fcf..e2e5d8d 100644 --- a/src/main/java/com/mapconductor/here/HereMapViewController.kt +++ b/src/main/java/com/mapconductor/here/HereMapViewController.kt @@ -1,6 +1,9 @@ package com.mapconductor.here import com.mapconductor.core.circle.CIRCLE_TILE_LAYER_ID +import com.mapconductor.core.map.CameraPaddingEmulation +import com.mapconductor.core.map.MapPaddings +import com.mapconductor.core.map.MapPaddingsInterface import com.mapconductor.core.circle.CircleTiler import com.mapconductor.core.circle.circleTileRasterLayerState import com.mapconductor.core.polygon.POLYGON_TILE_LAYER_ID @@ -77,6 +80,18 @@ class HereMapViewController( internal var markerAnimateStartListener: OnMarkerEventHandler? = null internal var markerAnimateEndListener: OnMarkerEventHandler? = null internal var lastRequestedCameraPosition: MapCameraPosition? = null + + /** + * 今カメラに付いているパディング(dp)。 + * + * HERE の principal point は使わない。flyTo のアニメーションに載らず、付けた瞬間に + * 画面が跳ぶため。代わりにカメラ中心をずらして再現し([CameraPaddingEmulation])、 + * 読むときに元へ戻すためにここで覚えておく。 + */ + internal var cameraPaddings: MapPaddingsInterface = MapPaddings.Zeros + + /** 最後に測れたカメラの焦点距離(px)。HERE は地図の大きさによらず一定。 */ + internal var focalLengthPx: Double? = null internal val cameraRequestGeneration = AtomicLong(0L) // HERE's MapCameraListener provides only continuous updates. Synthesize a "move end" after an idle window diff --git a/src/main/java/com/mapconductor/here/HereMapViewControllerCamera.kt b/src/main/java/com/mapconductor/here/HereMapViewControllerCamera.kt index 805c619..f90343c 100644 --- a/src/main/java/com/mapconductor/here/HereMapViewControllerCamera.kt +++ b/src/main/java/com/mapconductor/here/HereMapViewControllerCamera.kt @@ -11,8 +11,12 @@ import com.here.sdk.mapview.MapCameraAnimationFactory import com.here.sdk.mapview.MapMeasure import com.here.time.Duration import com.mapconductor.core.features.GeoRectBounds +import com.mapconductor.core.map.CameraPaddingEmulation import com.mapconductor.core.map.MapCameraPosition import com.mapconductor.core.map.VisibleRegion +import com.mapconductor.core.spherical.Spherical +import kotlin.math.atan +import kotlin.math.hypot import kotlin.time.Duration.Companion.milliseconds import kotlinx.coroutines.delay import kotlinx.coroutines.launch @@ -21,11 +25,52 @@ import kotlinx.coroutines.launch // HERE は「動き終わった」を通知しないので、更新が止まったところを // デバウンスで作っている。範囲制限もネイティブ API が無く、停止時に // 矩形内へクランプして再適用する。 + +/** 地図の高さ(dp)。パディングのエミュレーションで遠近を解くのに使う。 */ +internal fun HereMapViewController.viewportHeightDp(): Double { + val density = holder.mapView.resources.displayMetrics.density + return holder.mapView.height / density.toDouble() +} + +/** + * HERE のカメラの縦方向の視野角(度)。SDK に取得 API が無いので、今のカメラから測る。 + * + * ピンホールカメラでは、注視点で横に 1 m ずらすと `焦点距離 / 注視点までの距離` px 動く。 + * HERE は注視点までの距離([MapCamera.State.distanceToTargetInMeters])を返すので、 + * 横の 1 m が何 px かを投影で測れば焦点距離が出る。TB520FU では地図の大きさ・向き・ + * 画面密度によらず約 3550 px で、縦の視野角は縦長の全画面で約 45°、横長で約 29°。 + */ +internal fun HereMapViewController.verticalFov(): Double? { + val height = holder.mapView.height + if (height <= 0) return null + val state = holder.mapView.camera.state + val target = state.targetCoordinates.toGeoPoint() + val sideways = Spherical.computeOffset(target, 100.0, state.orientationAtTarget.bearing + 90.0) + val a = holder.mapView.geoToViewCoordinates(target.toGeoCoordinates()) + val b = holder.mapView.geoToViewCoordinates(sideways.toGeoCoordinates()) + if (a != null && b != null && state.distanceToTargetInMeters > 0) { + val pxPerMeter = hypot(b.x - a.x, b.y - a.y) / 100.0 + if (pxPerMeter > 0) focalLengthPx = state.distanceToTargetInMeters * pxPerMeter + } + val f = focalLengthPx ?: return null + return Math.toDegrees(2 * atan((height / 2.0) / f)) +} + +/** パディングを中心のずらしに置き換えたカメラ。paddings が null なら今のパディングを使い続ける。 */ +internal fun HereMapViewController.toNativeCamera(position: MapCameraPosition): MapCameraPosition { + position.paddings?.let { cameraPaddings = it } + return CameraPaddingEmulation.toNativeCamera( + position.copy(paddings = cameraPaddings), + verticalFov(), + viewportHeightDp(), + ) +} + internal fun HereMapViewController.handleMoveCamera(position: MapCameraPosition) { lastRequestedCameraPosition = position val request = cameraRequestGeneration.incrementAndGet() val camera = this.holder.mapView.camera - val adjustCameraUpdate = position.toMapCameraUpdate() + val adjustCameraUpdate = toNativeCamera(position).toMapCameraUpdate() camera.applyUpdate(adjustCameraUpdate) @@ -47,7 +92,7 @@ internal fun HereMapViewController.handleAnimateCamera( cameraRequestGeneration.incrementAndGet() val camera = this.holder.mapView.camera - val display = position.toHereDisplayCamera() + val display = toNativeCamera(position).toHereDisplayCamera() // bowFactor > 0: 最初にズームアウト → 到達時にズームイン // bowFactor < 0: 最初にズームイン → 到達時にズームアウト(ややレア) @@ -180,7 +225,12 @@ internal fun HereMapViewController.getMapCameraPosition(cameraState: MapCamera.S farRight = holder.fromScreenOffsetSync(Offset(mapWidth, 0.0f)), ) val logicalCamera = - HereCameraStateSnapshot(cameraState, lastRequestedCameraPosition?.tilt).toMapCameraPosition() + CameraPaddingEmulation.fromNativeCamera( + HereCameraStateSnapshot(cameraState, lastRequestedCameraPosition?.tilt).toMapCameraPosition(), + cameraPaddings, + verticalFov(), + viewportHeightDp(), + ) return@let logicalCamera.copy(visibleRegion = visibleRegion) } } diff --git a/src/main/java/com/mapconductor/here/MapCameraPosition.kt b/src/main/java/com/mapconductor/here/MapCameraPosition.kt index 94e9ead..395f9a1 100644 --- a/src/main/java/com/mapconductor/here/MapCameraPosition.kt +++ b/src/main/java/com/mapconductor/here/MapCameraPosition.kt @@ -72,6 +72,7 @@ fun MapCameraPosition.Companion.from(position: MapCameraPositionInterface): MapC tilt = position.tilt, paddings = position.paddings, visibleRegion = position.visibleRegion, + fov = position.fov, ) } From 808e5f14187867041ef20b2ef8d6d669adab6456 Mon Sep 17 00:00:00 2001 From: Masashi Katsumata Date: Fri, 13 Nov 2026 03:40:26 -0800 Subject: [PATCH 23/23] Release 1.4.0 --- api/android-for-here.api | 3 +++ gradle.properties | 2 +- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/api/android-for-here.api b/api/android-for-here.api index 9d82795..9bf0e09 100644 --- a/api/android-for-here.api +++ b/api/android-for-here.api @@ -211,6 +211,9 @@ public final class com.mapconductor.here.HereViewHolder implements com.mapconduc public androidx.compose.ui.geometry.Offset toScreenOffset-x-9fifI(com.mapconductor.core.features.GeoPointInterface); public java.lang.Object fromScreenOffset-3MmeM6k(long, kotlin.coroutines.Continuation); public com.mapconductor.core.features.GeoPoint fromScreenOffsetSync-k-4lQ0M(long); + 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(); } diff --git a/gradle.properties b/gradle.properties index c018eb9..8b1a332 100644 --- a/gradle.properties +++ b/gradle.properties @@ -8,5 +8,5 @@ minSdk=26 javaVersion=17 jvmTarget=17 -libraryVersion=1.3.1 +libraryVersion=1.4.0 android.generateSyncIssueWhenLibraryConstraintsAreEnabled=false