From 92b1568522ed89d623bd0eea8dab3a1e5e7affe6 Mon Sep 17 00:00:00 2001 From: Masashi Katsumata Date: Sat, 12 Sep 2026 15:13:23 +0900 Subject: [PATCH 01/23] Make bearing a clockwise map rotation (#6) 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 MapConductorCore from the matching branch コアの未リリースな変更に追随する PR を、コアのリリースを待たずに検証できるようにする。Package.swift が元から持っている「隣に ios-sdk-core があればそれを使う」経路に乗せるだけ。 * fix: make the CGFloat pitch conversion explicit MKMapCamera.pitch は CGFloat。暗黙変換に任せると CoreGraphics の cos(CGFloat) と Foundation の cos(Double) が両方候補になり、ツールチェーンによっては ambiguous use of 'cos' で落ちる。 --- .github/workflows/build.yml | 19 ++++++++++++++++++ .../MapCameraPositionExtensions.swift | 20 +++++++++++++------ .../controller/MapKitViewController.swift | 6 +++--- 3 files changed, 36 insertions(+), 9 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 19fd7f2..875c12a 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -32,6 +32,25 @@ jobs: - name: Show toolchain run: xcodebuild -version && swift --version + # Package.swift は `../ios-sdk-core` があればそれを使い、無ければ released 版 + # (`from: "1.1.4"`)へ解決する。CI はこのリポジトリしか checkout しないので + # 常に released 版になり、**コアの未リリースな変更に追随する PR は永久に赤いまま** + # になっていた(CameraBearing をコアへ足したときに踏んだ)。 + # 隣に置いてローカル開発と同じ経路に乗せる。同名ブランチがあればそちらを使う。 + - name: Check out MapConductorCore next to this package + env: + HEAD_REF: ${{ github.head_ref }} + run: | + url=https://github.com/MapConductor/ios-sdk-core.git + if [ -n "$HEAD_REF" ] && git ls-remote --exit-code --heads "$url" "$HEAD_REF" >/dev/null 2>&1; then + echo "ios-sdk-core: matching branch $HEAD_REF" + git clone --depth 1 --branch "$HEAD_REF" "$url" ../ios-sdk-core + else + echo "ios-sdk-core: default branch" + git clone --depth 1 "$url" ../ios-sdk-core + fi + test -f ../ios-sdk-core/Package.swift + - name: Build run: | scheme=$(sed -n 's/^[[:space:]]*name: "\([^"]*\)".*/\1/p' Package.swift | head -1) diff --git a/Sources/MapConductorForMapKit/MapCameraPositionExtensions.swift b/Sources/MapConductorForMapKit/MapCameraPositionExtensions.swift index e39a96c..b740503 100644 --- a/Sources/MapConductorForMapKit/MapCameraPositionExtensions.swift +++ b/Sources/MapConductorForMapKit/MapCameraPositionExtensions.swift @@ -1,6 +1,6 @@ import Foundation import MapKit -import MapConductorCore +@_spi(MapConductorDriver) import MapConductorCore private let converter = MapKitZoomAltitudeConverter(zoom0Altitude: 171_319_879.0) private let mapKitMaxPitch: Double = 80.9 @@ -30,7 +30,7 @@ public extension MapCameraPosition { ? Spherical.computeOffset( origin: position, distance: distance * tan(pitchRadians), - heading: bearing + heading: CameraBearing.toNativeHeading(bearing) ) : position @@ -42,7 +42,7 @@ public extension MapCameraPosition { ), fromDistance: distance, pitch: nativePitch, - heading: bearing + heading: CameraBearing.toNativeHeading(bearing) ) } } @@ -54,7 +54,11 @@ public extension MKMapView { visibleRegion: VisibleRegion? = nil ) -> MapCameraPosition { let cameraAltitude = camera.altitude - let pitchRadians = camera.pitch * .pi / 180.0 + // `MKMapCamera.pitch` は CGFloat。CGFloat と Double の暗黙変換に任せると + // CoreGraphics の `cos(CGFloat)` と Foundation の `cos(Double)` が両方候補になり、 + // ツールチェーンによっては `ambiguous use of 'cos'` で落ちる(CI の macos-15 で踏んだ)。 + // 手元の Xcode では通ってしまうので、Double へ明示的に寄せておく。 + let pitchRadians = Double(camera.pitch) * .pi / 180.0 // Recover the slant distance set via MKMapCamera(fromDistance:) — the inverse of toMKMapCamera(). let slantDistance = cameraAltitude / max(cos(pitchRadians), minCosTilt) var position = GeoPoint( @@ -95,7 +99,7 @@ public extension MKMapView { return MapCameraPosition( position: position, zoom: zoom, - bearing: camera.heading, + bearing: CameraBearing.bearingFromNativeHeading(camera.heading), tilt: logicalTilt, visibleRegion: visibleRegion ) @@ -154,7 +158,11 @@ private extension MKMapView { /// from whatever camera happens to be set and reused to place the next one. func metersPerPointPerDistance() -> Double? { guard let metersPerPoint = measuredMetersPerPointAtCenter() else { return nil } - let pitchRadians = camera.pitch * .pi / 180.0 + // `MKMapCamera.pitch` は CGFloat。CGFloat と Double の暗黙変換に任せると + // CoreGraphics の `cos(CGFloat)` と Foundation の `cos(Double)` が両方候補になり、 + // ツールチェーンによっては `ambiguous use of 'cos'` で落ちる(CI の macos-15 で踏んだ)。 + // 手元の Xcode では通ってしまうので、Double へ明示的に寄せておく。 + let pitchRadians = Double(camera.pitch) * .pi / 180.0 let slantDistance = camera.altitude / max(cos(pitchRadians), minCosTilt) guard slantDistance > 0 else { return nil } let factor = metersPerPoint / slantDistance diff --git a/Sources/MapConductorForMapKit/controller/MapKitViewController.swift b/Sources/MapConductorForMapKit/controller/MapKitViewController.swift index dbb0f02..02bdbea 100644 --- a/Sources/MapConductorForMapKit/controller/MapKitViewController.swift +++ b/Sources/MapConductorForMapKit/controller/MapKitViewController.swift @@ -1,7 +1,7 @@ import Foundation import CoreLocation import MapKit -import MapConductorCore +@_spi(MapConductorDriver) import MapConductorCore import QuartzCore import UIKit @@ -228,12 +228,12 @@ final class MapKitViewController: MapViewControllerProtocol { // Use UIView.animate to respect the specified duration UIView.animate(withDuration: duration) { mapView.setVisibleMapRect(rect, edgePadding: .zero, animated: false) - Self.applyHeading(position.bearing, center: centerCoordinate, to: mapView, animated: false) + Self.applyHeading(CameraBearing.toNativeHeading(position.bearing), center: centerCoordinate, to: mapView, animated: false) } } else { // Use MapKit's default animation or no animation mapView.setVisibleMapRect(rect, edgePadding: .zero, animated: animated) - Self.applyHeading(position.bearing, center: centerCoordinate, to: mapView, animated: animated) + Self.applyHeading(CameraBearing.toNativeHeading(position.bearing), center: centerCoordinate, to: mapView, animated: animated) } return true From 5cbe674c6524e0caaf6d3834a2a9f12de415da4a Mon Sep 17 00:00:00 2001 From: Masashi Katsumata Date: Mon, 5 Oct 2026 12:15:07 -0700 Subject: [PATCH 02/23] update dependencies (#7) --- Package.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Package.swift b/Package.swift index 4114edf..f68cd04 100644 --- a/Package.swift +++ b/Package.swift @@ -7,7 +7,7 @@ let frameworkLibraryType: Product.Library.LibraryType? = let usingLocalCore = FileManager.default.fileExists(atPath: "../ios-sdk-core/Package.swift") let coreDependency: Package.Dependency = usingLocalCore ? .package(path: "../ios-sdk-core") - : .package(url: "https://github.com/MapConductor/ios-sdk-core", from: "1.1.4") + : .package(url: "https://github.com/MapConductor/ios-sdk-core", from: "1.3.1") let package = Package( name: "mapconductor-for-mapkit", From 2ce4ab853337950879c01e871c9c74db0f811b5a Mon Sep 17 00:00:00 2001 From: Masashi Katsumata Date: Thu, 22 Oct 2026 21:02:51 -0700 Subject: [PATCH 03/23] Pick the marker drawn under the tap, label included (#8) --- .../marker/MapKitMarkerController.swift | 41 +++++++------------ 1 file changed, 15 insertions(+), 26 deletions(-) diff --git a/Sources/MapConductorForMapKit/marker/MapKitMarkerController.swift b/Sources/MapConductorForMapKit/marker/MapKitMarkerController.swift index c5d5d3b..6c306b8 100644 --- a/Sources/MapConductorForMapKit/marker/MapKitMarkerController.swift +++ b/Sources/MapConductorForMapKit/marker/MapKitMarkerController.swift @@ -1,7 +1,7 @@ import Combine import CoreLocation import MapKit -import MapConductorCore +@_spi(MapConductorDriver) import MapConductorCore @MainActor final class MapKitMarkerController: AbstractMarkerController { @@ -196,34 +196,23 @@ final class MapKitMarkerController: AbstractMarkerController Bool { MCLog.marker("MapKitMarkerController.handleTiledMarkerTap point=\(screenPoint) tiledCount=\(tiledMarkerIds.count)") guard !tiledMarkerIds.isEmpty, let mapView else { return false } - var bestState: MarkerState? = nil - var bestDist = CGFloat.infinity - - for id in tiledMarkerIds { - guard let entity = markerManager.getEntity(id), entity.state.clickable else { continue } - let coord = CLLocationCoordinate2D( - latitude: entity.state.position.latitude, - longitude: entity.state.position.longitude - ) - let markerPoint = mapView.convert(coord, toPointTo: mapView) - // アイコン矩形 + tapTolerance で判定する(android の `find()` と同じ)。 - // 以前は 44pt の固定半径で、アイコンの大きさを一切見ていなかったため、 - // 大きいアイコンは端をタップしても反応せず、小さいアイコンは離れていても反応していた。 - guard MarkerHitTest.hitsIcon( - touchScreen: screenPoint, - markerScreen: markerPoint, - state: entity.state - ) else { continue } - // 重なったマーカー同士は、アンカーがタップに近い方を優先する。 - let dist = hypot(screenPoint.x - markerPoint.x, screenPoint.y - markerPoint.y) - if dist < bestDist { - bestDist = dist - bestState = entity.state + // 選び方はコアの MarkerHitTest.pick と同じ。指の下にアイコン(ラベル込み)が描かれている + // マーカーを、アンカーの近い別のマーカーより優先する。 + let candidates = tiledMarkerIds.compactMap { markerManager.getEntity($0)?.state }.filter(\.clickable) + let bestState = MarkerHitTest.pick( + touchScreen: screenPoint, + candidates: candidates, + state: { $0 }, + project: { + mapView.convert( + CLLocationCoordinate2D(latitude: $0.latitude, longitude: $0.longitude), + toPointTo: mapView + ) } - } + ) if let state = bestState { - MCLog.marker("MapKitMarkerController.handleTiledMarkerTap hit id=\(state.id) dist=\(bestDist)") + MCLog.marker("MapKitMarkerController.handleTiledMarkerTap hit id=\(state.id)") dispatchClick(state: state) return true } From 24ee69ce214ad620ca0b7d20de31ac90a17f09a6 Mon Sep 17 00:00:00 2001 From: Masashi Katsumata Date: Fri, 23 Oct 2026 12:31:00 -0700 Subject: [PATCH 04/23] Require ios-sdk-core 1.3.2 (#9) --- Package.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Package.swift b/Package.swift index f68cd04..3b0a8c9 100644 --- a/Package.swift +++ b/Package.swift @@ -7,7 +7,7 @@ let frameworkLibraryType: Product.Library.LibraryType? = let usingLocalCore = FileManager.default.fileExists(atPath: "../ios-sdk-core/Package.swift") let coreDependency: Package.Dependency = usingLocalCore ? .package(path: "../ios-sdk-core") - : .package(url: "https://github.com/MapConductor/ios-sdk-core", from: "1.3.1") + : .package(url: "https://github.com/MapConductor/ios-sdk-core", from: "1.3.2") let package = Package( name: "mapconductor-for-mapkit", From a37de44b98556fb6f10614f853e63ec5503ab482 Mon Sep 17 00:00:00 2001 From: Masashi Katsumata Date: Sat, 24 Oct 2026 02:42:01 -0700 Subject: [PATCH 05/23] Fix Retina raster tiles and skip unchanged marker lists (#10) 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 MapConductorCore from the matching branch コアの未リリースな変更に追随する PR を、コアのリリースを待たずに検証できるようにする。Package.swift が元から持っている「隣に ios-sdk-core があればそれを使う」経路に乗せるだけ。 * fix: make the CGFloat pitch conversion explicit MKMapCamera.pitch は CGFloat。暗黙変換に任せると CoreGraphics の cos(CGFloat) と Foundation の cos(Double) が両方候補になり、ツールチェーンによっては ambiguous use of 'cos' で落ちる。 * Reject a re-sent identical marker list at the door SwiftUI re-evaluates map content on every camera change and hands the full marker list back to syncMarkers each time. For 144k markers the per-pass sets, dictionaries and hasEntity locks ran on the main thread for hundreds of milliseconds -- the 'pinch feels heavy on iOS' report. MarkerListIdentity (core) compares the list by reference and lets an unchanged list return in under a millisecond. Applied to every provider because fixing one just moves the report to the next one. Also pass declutterPx through to the tile renderer -- the option was silently ignored here while MapLibre honoured it -- and drop the per-subscription log line, which emitted 144k lines on first sync. * fix: account for Retina scale in MapKit raster tiles * feat: integrate vector style support and pending map fixes --------- Co-authored-by: masashi --- .../MapConductorForMapKit/MapKitMapView.swift | 18 ++++ .../marker/MapKitMarkerController.swift | 17 +++- .../MapKitRasterLayerOverlayRenderer.swift | 10 +- api/MapConductorForMapKit.api.swift | 92 +++++++++---------- 4 files changed, 86 insertions(+), 51 deletions(-) diff --git a/Sources/MapConductorForMapKit/MapKitMapView.swift b/Sources/MapConductorForMapKit/MapKitMapView.swift index a5772cf..2461e97 100644 --- a/Sources/MapConductorForMapKit/MapKitMapView.swift +++ b/Sources/MapConductorForMapKit/MapKitMapView.swift @@ -9,6 +9,8 @@ public struct MapKitMapView: View { @ObservedObject private var state: MapKitViewState private let handlers: MapViewHandlers private let cameraRestriction: CameraRestriction? + private let style: MapViewStyle? + private let onStyleDiagnostics: (([String]) -> Void)? private let content: () -> MapViewContent public init( @@ -21,10 +23,18 @@ public struct MapKitMapView: View { onCameraMove: OnCameraMoveHandler? = nil, onCameraMoveEnd: OnCameraMoveHandler? = nil, sdkInitialize: (() -> Void)? = nil, + /// How the map looks, when the app states it rather than naming a + /// design. `MapConductorVectorStyle` builds one; what happens + /// underneath depends on this backend and the app does not have to + /// know. + style: MapViewStyle? = nil, + onStyleDiagnostics: (([String]) -> Void)? = nil, @MapViewContentBuilder content: @escaping () -> MapViewContent = { MapViewContent() } ) { self.state = state self.cameraRestriction = cameraRestriction + self.style = style + self.onStyleDiagnostics = onStyleDiagnostics self.handlers = MapViewHandlers( onMapLoaded: onMapLoaded, onMapClick: onMapClick, @@ -54,6 +64,8 @@ public struct MapKitMapView: View { state: state, cameraRestriction: cameraRestriction, handlers: handlers, + style: style, + onStyleDiagnostics: onStyleDiagnostics, content: mapContent ) } @@ -64,6 +76,8 @@ private struct MapKitMapViewRepresentable: UIViewRepresentable { @ObservedObject var state: MapKitViewState let cameraRestriction: CameraRestriction? let handlers: MapViewHandlers + let style: MapViewStyle? + let onStyleDiagnostics: (([String]) -> Void)? let content: MapViewContent func makeCoordinator() -> Coordinator { @@ -109,6 +123,9 @@ private struct MapKitMapViewRepresentable: UIViewRepresentable { } func updateUIView(_ uiView: MKMapView, context: Context) { + // Every evaluation of the app's `body` lands here; most calls do + // nothing. See `MapViewStyleHost.apply`. + context.coordinator.applyStyle(style, onDiagnostics: onStyleDiagnostics) // 制限値が変わったときだけ再適用する。 context.coordinator.applyCameraRestriction(cameraRestriction) uiView.mapType = state.mapDesignType.getValue() @@ -128,6 +145,7 @@ private struct MapKitMapViewRepresentable: UIViewRepresentable { } static func dismantleUIView(_ uiView: MKMapView, coordinator: Coordinator) { + coordinator.disposeStyle() coordinator.unbind() uiView.delegate = nil } diff --git a/Sources/MapConductorForMapKit/marker/MapKitMarkerController.swift b/Sources/MapConductorForMapKit/marker/MapKitMarkerController.swift index 6c306b8..0ac85b0 100644 --- a/Sources/MapConductorForMapKit/marker/MapKitMarkerController.swift +++ b/Sources/MapConductorForMapKit/marker/MapKitMarkerController.swift @@ -21,8 +21,18 @@ final class MapKitMarkerController: AbstractMarkerController MKTileOverlay? { guard let mapView else { return nil } - guard let overlay = await makeTileOverlay(from: state) else { return nil } + guard let overlay = await makeTileOverlay(from: state, displayScale: mapView.traitCollection.displayScale) else { return nil } overlayStates[overlay] = state let renderer = MKTileOverlayRenderer(tileOverlay: overlay) @@ -97,14 +97,18 @@ final class MapKitRasterLayerOverlayRenderer: AbstractRasterLayerOverlayRenderer mapView = nil } - private func makeTileOverlay(from state: RasterLayerState) async -> MKTileOverlay? { + private func makeTileOverlay(from state: RasterLayerState, displayScale: CGFloat) async -> MKTileOverlay? { let source = await resolveSource(state: state) switch source { case let .urlTemplate(template, tileSize, minZoom, maxZoom, _, scheme): + // RasterLayerSource expresses display size in points; MKTileOverlay + // expects pixels. Without the screen scale, Retina maps select a + // finer tile level and shrink the style's labels and road widths. + let pixelSize = max(1, Int((CGFloat(tileSize) * max(1, displayScale)).rounded())) let overlay = CustomURLTileOverlay( urlTemplate: template, - tileSize: tileSize, + tileSize: pixelSize, minZoom: minZoom, maxZoom: maxZoom, scheme: scheme, diff --git a/api/MapConductorForMapKit.api.swift b/api/MapConductorForMapKit.api.swift index 2dfbbb1..b909ad1 100644 --- a/api/MapConductorForMapKit.api.swift +++ b/api/MapConductorForMapKit.api.swift @@ -12,70 +12,70 @@ import _Concurrency import _MapKit_SwiftUI import _StringProcessing import _SwiftConcurrencyShims -extension MapConductorCore.MapCameraPosition { - final public func toMKMapCamera(on mapView: MapKit.MKMapView? = nil) -> MapKit.MKMapCamera +extension MapConductorCore::MapCameraPosition { + final public func toMKMapCamera(on mapView: MapKit::MKMapView? = nil) -> MapKit::MKMapCamera } -extension MapKit.MKMapView { - @_Concurrency.MainActor @preconcurrency public func toMapCameraPosition(logicalTiltHint: Swift.Double? = nil, visibleRegion: MapConductorCore.VisibleRegion? = nil) -> MapConductorCore.MapCameraPosition +extension MapKit::MKMapView { + @_Concurrency::MainActor @preconcurrency public func toMapCameraPosition(logicalTiltHint: Swift::Double? = nil, visibleRegion: MapConductorCore::VisibleRegion? = nil) -> MapConductorCore::MapCameraPosition } -public protocol MapKitMapDesignTypeProtocol : MapConductorCore.MapDesignTypeProtocol where Self.Identifier == MapKit.MKMapType { +public protocol MapKitMapDesignTypeProtocol : MapConductorCore::MapDesignTypeProtocol where Self.Identifier == MapKit::MKMapType { } -public typealias MapKitMapDesignType = any MapConductorForMapKit.MapKitMapDesignTypeProtocol -public struct MapKitMapDesign : MapConductorForMapKit.MapKitMapDesignTypeProtocol, Swift.Hashable { - public let id: MapKit.MKMapType - public let attributionRules: [MapConductorCore.AttributionRule] - public init(id: MapKit.MKMapType, attributionRules: [MapConductorCore.AttributionRule] = []) - public func getValue() -> MapKit.MKMapType - public static let Standard: MapConductorForMapKit.MapKitMapDesign - public static let Satellite: MapConductorForMapKit.MapKitMapDesign - public static let Hybrid: MapConductorForMapKit.MapKitMapDesign - public static let SatelliteFlyover: MapConductorForMapKit.MapKitMapDesign - public static let HybridFlyover: MapConductorForMapKit.MapKitMapDesign - public static let MutedStandard: MapConductorForMapKit.MapKitMapDesign - public static func Create(id: MapKit.MKMapType) -> MapConductorForMapKit.MapKitMapDesign - public static func toMapDesignType(id: MapKit.MKMapType) -> MapConductorForMapKit.MapKitMapDesignType - public static func == (a: MapConductorForMapKit.MapKitMapDesign, b: MapConductorForMapKit.MapKitMapDesign) -> Swift.Bool - public typealias Identifier = MapKit.MKMapType - public func hash(into hasher: inout Swift.Hasher) - public var hashValue: Swift.Int { +public typealias MapKitMapDesignType = any MapConductorForMapKit::MapKitMapDesignTypeProtocol +public struct MapKitMapDesign : MapConductorForMapKit::MapKitMapDesignTypeProtocol, Swift::Hashable { + public let id: MapKit::MKMapType + public let attributionRules: [MapConductorCore::AttributionRule] + public init(id: MapKit::MKMapType, attributionRules: [MapConductorCore::AttributionRule] = []) + public func getValue() -> MapKit::MKMapType + public static let Standard: MapConductorForMapKit::MapKitMapDesign + public static let Satellite: MapConductorForMapKit::MapKitMapDesign + public static let Hybrid: MapConductorForMapKit::MapKitMapDesign + public static let SatelliteFlyover: MapConductorForMapKit::MapKitMapDesign + public static let HybridFlyover: MapConductorForMapKit::MapKitMapDesign + public static let MutedStandard: MapConductorForMapKit::MapKitMapDesign + public static func Create(id: MapKit::MKMapType) -> MapConductorForMapKit::MapKitMapDesign + public static func toMapDesignType(id: MapKit::MKMapType) -> MapConductorForMapKit::MapKitMapDesignType + public static func == (a: MapConductorForMapKit::MapKitMapDesign, b: MapConductorForMapKit::MapKitMapDesign) -> Swift::Bool + public typealias Identifier = MapKit::MKMapType + public func hash(into hasher: inout Swift::Hasher) + public var hashValue: Swift::Int { get } } -@_Concurrency.MainActor @preconcurrency public struct MapKitMapView : SwiftUICore.View { - @_Concurrency.MainActor @preconcurrency public init(state: MapConductorForMapKit.MapKitViewState, cameraRestriction: MapConductorCore.CameraRestriction? = nil, onMapLoaded: MapConductorCore.OnMapLoadedHandler? = nil, onMapClick: MapConductorCore.OnMapEventHandler? = nil, onMapLongClick: MapConductorCore.OnMapEventHandler? = nil, onCameraMoveStart: MapConductorCore.OnCameraMoveHandler? = nil, onCameraMove: MapConductorCore.OnCameraMoveHandler? = nil, onCameraMoveEnd: MapConductorCore.OnCameraMoveHandler? = nil, sdkInitialize: (() -> Swift.Void)? = nil, @MapConductorCore.MapViewContentBuilder content: @escaping () -> MapConductorCore.MapViewContent = { MapViewContent() }) - @_Concurrency.MainActor @preconcurrency public var body: some SwiftUICore.View { +@_Concurrency::MainActor @preconcurrency public struct MapKitMapView : SwiftUICore::View { + @_Concurrency::MainActor @preconcurrency public init(state: MapConductorForMapKit::MapKitViewState, cameraRestriction: MapConductorCore::CameraRestriction? = nil, onMapLoaded: MapConductorCore::OnMapLoadedHandler? = nil, onMapClick: MapConductorCore::OnMapEventHandler? = nil, onMapLongClick: MapConductorCore::OnMapEventHandler? = nil, onCameraMoveStart: MapConductorCore::OnCameraMoveHandler? = nil, onCameraMove: MapConductorCore::OnCameraMoveHandler? = nil, onCameraMoveEnd: MapConductorCore::OnCameraMoveHandler? = nil, sdkInitialize: (() -> Swift::Void)? = nil, style: (any MapConductorCore::MapViewStyle)? = nil, onStyleDiagnostics: (([Swift::String]) -> Swift::Void)? = nil, @MapConductorCore::MapViewContentBuilder content: @escaping () -> MapConductorCore::MapViewContent = { MapViewContent() }) + @_Concurrency::MainActor @preconcurrency public var body: some SwiftUICore::View { get } public typealias Body = @_opaqueReturnTypeOf("$s015MapConductorForA3Kit0adA4ViewV4bodyQrvp", 0) __ } -public typealias MapKitActualMarker = MapKit.MKPointAnnotation -public typealias MapKitActualPolyline = MapKit.MKPolyline -public typealias MapKitActualCircle = MapKit.MKCircle -public typealias MapKitActualPolygon = MapKit.MKPolygon -final public class MapKitViewState : MapConductorCore.MapViewState { - final public var mapViewHolder: MapConductorForMapKit.MapKitViewHolder? { +public typealias MapKitActualMarker = MapKit::MKPointAnnotation +public typealias MapKitActualPolyline = MapKit::MKPolyline +public typealias MapKitActualCircle = MapKit::MKCircle +public typealias MapKitActualPolygon = MapKit::MKPolygon +final public class MapKitViewState : MapConductorCore::MapViewState { + final public var mapViewHolder: MapConductorForMapKit::MapKitViewHolder? { get } - override final public var mapDesignType: MapConductorForMapKit.MapKitMapDesignType { + override final public var mapDesignType: MapConductorForMapKit::MapKitMapDesignType { get set } - public init(id: Swift.String, mapDesignType: MapConductorForMapKit.MapKitMapDesignType = MapKitMapDesign.Standard, cameraPosition: MapConductorCore.MapCameraPosition = .Default, uiSettings: MapConductorCore.MapUISettings = MapUISettings()) - convenience public init(mapDesignType: MapConductorForMapKit.MapKitMapDesignType = MapKitMapDesign.Standard, cameraPosition: MapConductorCore.MapCameraPosition = .Default, uiSettings: MapConductorCore.MapUISettings = MapUISettings()) - override final public func getMapViewHolder() -> MapConductorCore.AnyMapViewHolder? + public init(id: Swift::String, mapDesignType: MapConductorForMapKit::MapKitMapDesignType = MapKitMapDesign.Standard, cameraPosition: MapConductorCore::MapCameraPosition = .Default, uiSettings: MapConductorCore::MapUISettings = MapUISettings()) + convenience public init(mapDesignType: MapConductorForMapKit::MapKitMapDesignType = MapKitMapDesign.Standard, cameraPosition: MapConductorCore::MapCameraPosition = .Default, uiSettings: MapConductorCore::MapUISettings = MapUISettings()) + override final public func getMapViewHolder() -> MapConductorCore::AnyMapViewHolder? @objc deinit } -public class MapKitZoomAltitudeConverter : MapConductorCore.WebMercatorZoomAltitudeConverter { - public init(zoom0Altitude: Swift.Double = AbstractZoomAltitudeConverter.defaultZoom0Altitude) +public class MapKitZoomAltitudeConverter : MapConductorCore::WebMercatorZoomAltitudeConverter { + public init(zoom0Altitude: Swift::Double = AbstractZoomAltitudeConverter.defaultZoom0Altitude) @objc deinit } -@_hasMissingDesignatedInitializers final public class MapKitViewHolder : MapConductorCore.MapViewHolderProtocol { - final public let mapView: MapKit.MKMapView - final public let map: MapKit.MKMapView - final public func toScreenOffset(position: any MapConductorCore.GeoPointProtocol) -> CoreFoundation.CGPoint? - final public func fromScreenOffsetSync(offset: CoreFoundation.CGPoint) -> MapConductorCore.GeoPoint? - public typealias ActualMap = MapKit.MKMapView - public typealias ActualMapView = MapKit.MKMapView +@_hasMissingDesignatedInitializers final public class MapKitViewHolder : MapConductorCore::MapViewHolderProtocol { + final public let mapView: MapKit::MKMapView + final public let map: MapKit::MKMapView + final public func toScreenOffset(position: any MapConductorCore::GeoPointProtocol) -> CoreFoundation::CGPoint? + final public func fromScreenOffsetSync(offset: CoreFoundation::CGPoint) -> MapConductorCore::GeoPoint? + public typealias ActualMap = MapKit::MKMapView + public typealias ActualMapView = MapKit::MKMapView @objc deinit } -extension MapConductorForMapKit.MapKitMapView : Swift.Sendable {} +extension MapConductorForMapKit::MapKitMapView : Swift::Sendable {} From 6fc05bc892025fa631f837f4471b5185d0b7b6c7 Mon Sep 17 00:00:00 2001 From: Masashi Katsumata Date: Wed, 28 Oct 2026 13:47:20 -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 a63de2205cc773a2d796cd200e838d47fbd6214f Mon Sep 17 00:00:00 2001 From: Masashi Katsumata Date: Wed, 4 Nov 2026 23:33:29 -0800 Subject: [PATCH 07/23] Redraw tiles when a tiled marker changes A tiled marker has no native marker, so the base update() only rewrote the manager and nothing reached the map: changing an icon or position in place left the drawn tiles as they were. Invalidate the tiles and rebuild the layer with a versioned URL, once per burst of updates. --- .../marker/MapKitMarkerController.swift | 37 ++++++++++++++++++- 1 file changed, 36 insertions(+), 1 deletion(-) diff --git a/Sources/MapConductorForMapKit/marker/MapKitMarkerController.swift b/Sources/MapConductorForMapKit/marker/MapKitMarkerController.swift index 0ac85b0..9995443 100644 --- a/Sources/MapConductorForMapKit/marker/MapKitMarkerController.swift +++ b/Sources/MapConductorForMapKit/marker/MapKitMarkerController.swift @@ -116,6 +116,9 @@ final class MapKitMarkerController: AbstractMarkerController? private var tileRouteId: String? private var tiledMarkerIds: Set = [] + /// タイル URL の版。マーカーが変わるたびに上げ、地図に描画済みのタイルを取り直させる。 + private var tileVersion: Int64 = 0 + private var tileRefreshScheduled = false private var tileOverlay: MKTileOverlay? private var lastServerBaseUrl: String = "" private let defaultMarkerIconForTiling: BitmapIcon = DefaultMarkerIcon().toBitmapIcon() @@ -148,6 +151,32 @@ final class MapKitMarkerController: AbstractMarkerController Date: Sat, 7 Nov 2026 06:07:50 -0800 Subject: [PATCH 08/23] Draw large polygon sets as raster tiles (PolygonTiler) The polygon controller gets ios-sdk-core's PolygonTiler: from 2,000 polygons or 50,000 vertices they are drawn into raster tiles on the local tile server and shown as one raster layer (mc-polygon-tiles), upserted into the raster layer controller so the app's raster layers and the marker tiles are left alone. Taps still resolve against the original shapes. The content update asks the tiler to show the tiles again when the tile server has moved. --- Sources/MapConductorForMapKit/MapKitMapView.swift | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/Sources/MapConductorForMapKit/MapKitMapView.swift b/Sources/MapConductorForMapKit/MapKitMapView.swift index 2461e97..ac275b5 100644 --- a/Sources/MapConductorForMapKit/MapKitMapView.swift +++ b/Sources/MapConductorForMapKit/MapKitMapView.swift @@ -1,6 +1,6 @@ import Combine import MapKit -import MapConductorCore +@_spi(MapConductorDriver) import MapConductorCore import QuartzCore import SwiftUI import UIKit @@ -271,6 +271,17 @@ private struct MapKitMapViewRepresentable: UIViewRepresentable { let rasterLayerController = MapKitRasterLayerController(mapView: mapView) self.rasterLayerController = rasterLayerController + // Many polygons are drawn into raster tiles and shown as one raster + // layer; taps still resolve against the original shapes. + let polygonTiler = PolygonTiler() + polygonTiler.onTemplate = { [weak rasterLayerController] template, tileSize in + if let template { + await rasterLayerController?.upsert(state: PolygonTiler.rasterLayerState(template: template, tileSize: tileSize)) + } else { + await rasterLayerController?.removeById(PolygonTiler.layerId) + } + } + polygonController.tiler = polygonTiler let groundImageController = MapKitGroundImageController(mapView: mapView) self.groundImageController = groundImageController @@ -376,6 +387,7 @@ private struct MapKitMapViewRepresentable: UIViewRepresentable { overlayScope?.circleCollector.sync(content.circles.map { $0.state }) overlayScope?.polylineCollector.sync(content.polylines.map { $0.state }) overlayScope?.polygonCollector.sync(content.polygons.map { $0.state }) + polygonController?.tiler?.refreshIfServerMoved() for handler in content.polygonSyncHandlers { let hullController = hullPolygonController handler.bindPolygonSync { [weak hullController] states in From 1979faf669faebcd891b817300c5af8f3b25a4de Mon Sep 17 00:00:00 2001 From: Masashi Katsumata Date: Sat, 7 Nov 2026 07:41:29 -0800 Subject: [PATCH 09/23] Call onAdded for markers Natively drawn markers are reported by MarkerIngestionEngine once the renderer has created them; markers that went into the tiles are reported after the tile layer has been handed to the map. --- .../MapConductorForMapKit/marker/MapKitMarkerController.swift | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/Sources/MapConductorForMapKit/marker/MapKitMarkerController.swift b/Sources/MapConductorForMapKit/marker/MapKitMarkerController.swift index 9995443..43b8620 100644 --- a/Sources/MapConductorForMapKit/marker/MapKitMarkerController.swift +++ b/Sources/MapConductorForMapKit/marker/MapKitMarkerController.swift @@ -195,6 +195,7 @@ final class MapKitMarkerController: AbstractMarkerController Date: Sat, 7 Nov 2026 18:53:23 -0800 Subject: [PATCH 10/23] Make clearOverlays() clear the overlay controllers clearOverlays() only removed native annotations (or map items, or did nothing at all), leaving every MapConductor overlay on the map and in its manager. It now calls clear() on the marker, polyline, polygon, ground image, circle and raster layer controllers, as android-sdk does. The controllers live in the host, so the host hands the view controller a handler when it creates them. --- Sources/MapConductorForMapKit/MapKitMapView.swift | 12 ++++++++++++ .../controller/MapKitViewController.swift | 8 +++++--- 2 files changed, 17 insertions(+), 3 deletions(-) diff --git a/Sources/MapConductorForMapKit/MapKitMapView.swift b/Sources/MapConductorForMapKit/MapKitMapView.swift index 2461e97..9b73bbe 100644 --- a/Sources/MapConductorForMapKit/MapKitMapView.swift +++ b/Sources/MapConductorForMapKit/MapKitMapView.swift @@ -286,6 +286,7 @@ private struct MapKitMapViewRepresentable: UIViewRepresentable { controller.registerOverlayController(polygonController) controller.registerOverlayController(groundImageController) controller.registerOverlayController(rasterLayerController) + controller.clearOverlaysHandler = { [weak self] in await self?.clearOverlays() } let overlayScope = MapOverlayScope() self.overlayScope = overlayScope @@ -316,6 +317,17 @@ private struct MapKitMapViewRepresentable: UIViewRepresentable { } } + /// android-sdk の `clearOverlays()` と同じく、各オーバーレイのコントローラを空にする。 + /// `controller.clearOverlaysHandler` から呼ばれる。 + func clearOverlays() async { + await markerController?.clear() + await polylineController?.clear() + await polygonController?.clear() + await groundImageController?.clear() + await circleController?.clear() + await rasterLayerController?.clear() + } + func unbind() { // 登録した capability を取り下げる。レジストリの持ち主は state で、ビューより長生きするため、 // ここで外さないと破棄済みのコントローラを掴んだまま残る。 diff --git a/Sources/MapConductorForMapKit/controller/MapKitViewController.swift b/Sources/MapConductorForMapKit/controller/MapKitViewController.swift index 02bdbea..c5e0f86 100644 --- a/Sources/MapConductorForMapKit/controller/MapKitViewController.swift +++ b/Sources/MapConductorForMapKit/controller/MapKitViewController.swift @@ -64,10 +64,12 @@ final class MapKitViewController: MapViewControllerProtocol { cancelCameraAnimation() } + /// ``clearOverlays()`` の中身。オーバーレイのコントローラはホストが持っているので、 + /// ホストが生成時に設定する(android-sdk と同じく、各コントローラの `clear()` を呼ぶ)。 + var clearOverlaysHandler: (@MainActor () async -> Void)? + func clearOverlays() async { - guard let mapView = mapView else { return } - mapView.removeAnnotations(mapView.annotations) - mapView.removeOverlays(mapView.overlays) + await clearOverlaysHandler?() } func setCameraMoveStartListener(listener: OnCameraMoveHandler?) { From c260d293acbddbc1ca6c4c1ac933c396ed34a045 Mon Sep 17 00:00:00 2001 From: Masashi Katsumata Date: Sat, 7 Nov 2026 21:47:37 -0800 Subject: [PATCH 11/23] Interpolate the closing edge of geodesic polygons ring(_:geodesic:) densified a geodesic ring with createInterpolatePoints, which only interpolates between neighbouring points. Rings arrive open, so the closing edge (last vertex -> first) stayed a straight chord in both fill and outline (Boston -> London -> Iceland: the Iceland -> Boston edge). Use ios-sdk-core's densifyGeodesicRing. geodesic=false is unchanged. Requires the ios-sdk-core release that adds densifyGeodesicRing. --- .../polygon/MapKitPolygonOverlayRenderer.swift | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Sources/MapConductorForMapKit/polygon/MapKitPolygonOverlayRenderer.swift b/Sources/MapConductorForMapKit/polygon/MapKitPolygonOverlayRenderer.swift index 65e4726..b8542e6 100644 --- a/Sources/MapConductorForMapKit/polygon/MapKitPolygonOverlayRenderer.swift +++ b/Sources/MapConductorForMapKit/polygon/MapKitPolygonOverlayRenderer.swift @@ -132,8 +132,9 @@ final class MapKitPolygonOverlayRenderer: AbstractPolygonOverlayRenderer [CLLocationCoordinate2D] { + // geodesic は閉じる辺(末尾 → 先頭)も大圏で補間する(塗りと輪郭が同じ MKPolygon)。 let geoPoints: [GeoPointProtocol] = geodesic - ? WGS84Geodesic.createInterpolatePoints(points) + ? densifyGeodesicRing(points) : Planar.createInterpolatePoints(points) return geoPoints.map { CLLocationCoordinate2D(latitude: $0.latitude, longitude: $0.longitude) } } From a195afa23c19a0766f2c6f31469daa0fc64b958b Mon Sep 17 00:00:00 2001 From: Masashi Katsumata Date: Sat, 7 Nov 2026 23:26:58 -0800 Subject: [PATCH 12/23] Densify the closing edge of non-geodesic polygons too A geodesic=false ring went through Planar.createInterpolatePoints, which only interpolates between neighbouring points, so the closing edge (last vertex -> first) stayed one straight Web Mercator segment while the other edges - and polylines with geodesic=false - follow linear lat/lng interpolation. Use ios-sdk-core's densifyPolygonRing for both modes (it replaces the unreleased densifyGeodesicRing). Requires the ios-sdk-core release that adds densifyPolygonRing. --- .../polygon/MapKitPolygonOverlayRenderer.swift | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/Sources/MapConductorForMapKit/polygon/MapKitPolygonOverlayRenderer.swift b/Sources/MapConductorForMapKit/polygon/MapKitPolygonOverlayRenderer.swift index b8542e6..414d807 100644 --- a/Sources/MapConductorForMapKit/polygon/MapKitPolygonOverlayRenderer.swift +++ b/Sources/MapConductorForMapKit/polygon/MapKitPolygonOverlayRenderer.swift @@ -132,11 +132,9 @@ final class MapKitPolygonOverlayRenderer: AbstractPolygonOverlayRenderer [CLLocationCoordinate2D] { - // geodesic は閉じる辺(末尾 → 先頭)も大圏で補間する(塗りと輪郭が同じ MKPolygon)。 - let geoPoints: [GeoPointProtocol] = geodesic - ? densifyGeodesicRing(points) - : Planar.createInterpolatePoints(points) - return geoPoints.map { CLLocationCoordinate2D(latitude: $0.latitude, longitude: $0.longitude) } + // 閉じる辺(末尾 → 先頭)も他の辺と同じく補間する(塗りと輪郭が同じ MKPolygon)。 + // geodesic は大圏、geodesic=false は緯度経度の線形補間(ポリラインの false と同じ線)。 + densifyPolygonRing(points, geodesic: geodesic).map { CLLocationCoordinate2D(latitude: $0.latitude, longitude: $0.longitude) } } } From fc1680013170203fbfd0c42890ac6411d2713444 Mon Sep 17 00:00:00 2001 From: Masashi Katsumata Date: Sat, 7 Nov 2026 23:10:49 -0800 Subject: [PATCH 13/23] Clear strategy-driven markers in clearOverlays() clearOverlays() cleared this provider's own overlay controllers but not the strategy controller behind MarkerRenderingSupport, so markers drawn by clustering (or any other marker-rendering plugin) stayed on the map. It now ends with MapServiceRegistry.clearMarkerRendering() (ios-sdk-core fix/clear-strategy), which reaches the registered support's clearMarkers(): StrategyMarkerController.clear() (onRemove -> strategy.clear() -> onPostProcess), and the next syncMarkers sends the markers again, as the overlay collectors do after a clear. Requires the ios-sdk-core change that adds clearMarkers() to MarkerRenderingSupport. --- Sources/MapConductorForMapKit/MapKitMapView.swift | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Sources/MapConductorForMapKit/MapKitMapView.swift b/Sources/MapConductorForMapKit/MapKitMapView.swift index 9b73bbe..763dedd 100644 --- a/Sources/MapConductorForMapKit/MapKitMapView.swift +++ b/Sources/MapConductorForMapKit/MapKitMapView.swift @@ -326,6 +326,8 @@ private struct MapKitMapViewRepresentable: UIViewRepresentable { await groundImageController?.clear() await circleController?.clear() await rasterLayerController?.clear() + // strategy(クラスタリングなど)が描いたマーカーも消す。 + await state.serviceRegistry.clearMarkerRendering() } func unbind() { From 68f332e9aac41402e937c37291d3012a78080701 Mon Sep 17 00:00:00 2001 From: Masashi Katsumata Date: Sat, 7 Nov 2026 23:35:42 -0800 Subject: [PATCH 14/23] Stack overlays in one band order, whatever order they arrive in MapKit stacks overlays by level, then by add order. Polygons, circles and polylines were added with addOverlay(_:) (level .aboveRoads, under the labels), but rasters, ground images and marker tiles with .aboveLabels, so a raster covered every polygon, circle and polyline; within a level the order followed add order. Overlays now go through MapKitOverlayStacking: everything but the marker band is placed in .aboveRoads at its band position (raster layers < ground images < polygons < circles < polylines, zIndex at add time within a band) with insertOverlay(_:at:level:); marker tiles go in .aboveLabels. Annotations stay above all overlays (MapKit). Label change this forces: rasters and ground images move under the labels (polygons, circles and polylines keep their place under the labels). The other way round - everything .aboveLabels - would instead move polygons, circles and polylines over the labels. Requires ios-sdk-core fix/overlay-stacking-order (OverlayStacking). --- .../MapKitOverlayStacking.swift | 62 +++++++++++++++++++ .../circle/MapKitCircleOverlayRenderer.swift | 4 +- .../MapKitGroundImageOverlayRenderer.swift | 4 +- .../marker/MapKitMarkerController.swift | 3 +- .../MapKitPolygonOverlayRenderer.swift | 4 +- .../MapKitPolylineOverlayRenderer.swift | 4 +- .../MapKitRasterLayerOverlayRenderer.swift | 6 +- 7 files changed, 75 insertions(+), 12 deletions(-) create mode 100644 Sources/MapConductorForMapKit/MapKitOverlayStacking.swift diff --git a/Sources/MapConductorForMapKit/MapKitOverlayStacking.swift b/Sources/MapConductorForMapKit/MapKitOverlayStacking.swift new file mode 100644 index 0000000..1b9a9ef --- /dev/null +++ b/Sources/MapConductorForMapKit/MapKitOverlayStacking.swift @@ -0,0 +1,62 @@ +import Foundation +import MapKit +@_spi(MapConductorDriver) import MapConductorCore + +/// オーバーレイを、重なり順の帯(``OverlayBand``)の位置へ差し込む。 +/// +/// 下から ラスター < グラウンドイメージ < ポリゴン < サークル < ポリライン < マーカーのタイル。 +/// MapKit は同じ level の中では足した順に重ねるので、以前は後から足したもの +/// (clearOverlays の後に送り直したグラウンドイメージなど)が上に来ていた。 +/// ここでは level の中の並びで帯の位置を計算して `insertOverlay(_:at:level:)` する。 +/// +/// ## level とラベル +/// +/// `addOverlay(_:)` の既定の level は `.aboveRoads`(ラベルの下)で、ポリゴン・サークル・ +/// ポリラインは以前からラベルの下にあった。一方ラスター・グラウンドイメージ・マーカーのタイルは +/// `.aboveLabels` で足していたので、**ラスターがポリゴン等より上**に描かれていた。 +/// 帯の順を守るには、ラスターとグラウンドイメージをポリゴン等と同じ level に置く必要がある。 +/// ここではポリゴン等のラベルとの関係を変えない方を選び、マーカーの帯以外はすべて +/// `.aboveRoads`、マーカーのタイルだけ `.aboveLabels` に置く。 +/// その結果ラスター(GL 系と同じくラベルの下になる)とグラウンドイメージ(以前はラベルの上)が +/// ラベルの下へ移る。 +/// +/// - マーカー(`MKAnnotation`)は MapKit が常にオーバーレイより上に描くので、帯の条件を満たす。 +/// - 帯の中の zIndex は足した時点の値で並べる(MapKit の描画担当は zIndex の変更を受けて +/// 並べ直さない。従来から未対応)。 +@MainActor +enum MapKitOverlayStacking { + static func level(for key: OverlayStackKey) -> MKOverlayLevel { + key.band == .marker ? .aboveLabels : .aboveRoads + } + + static func add(_ overlay: MKOverlay, _ key: OverlayStackKey, to mapView: MKMapView) { + let level = level(for: key) + let registry = keys(of: mapView) + registry.setObject(KeyBox(key), forKey: overlay) + let existing = mapView.overlays(in: level) + let keys = existing.map { (registry.object(forKey: $0) as KeyBox?)?.key } + let index = OverlayStacking.insertionIndex(for: key, among: keys) + if index >= existing.count { + mapView.addOverlay(overlay, level: level) + } else { + mapView.insertOverlay(overlay, at: index, level: level) + } + } + + private final class KeyBox: NSObject { + let key: OverlayStackKey + init(_ key: OverlayStackKey) { self.key = key } + } + + private static var registryKey: UInt8 = 0 + + /// 地図ごとの「オーバーレイ → 帯のキー」。オーバーレイは弱参照で持つので、外したものは自然に消える。 + private static func keys(of mapView: MKMapView) -> NSMapTable { + if let table = objc_getAssociatedObject(mapView, ®istryKey) as? NSMapTable { + return table + } + let table = NSMapTable.weakToStrongObjects() + objc_setAssociatedObject(mapView, ®istryKey, table, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) + return table + } +} diff --git a/Sources/MapConductorForMapKit/circle/MapKitCircleOverlayRenderer.swift b/Sources/MapConductorForMapKit/circle/MapKitCircleOverlayRenderer.swift index 6a253bb..fc96261 100644 --- a/Sources/MapConductorForMapKit/circle/MapKitCircleOverlayRenderer.swift +++ b/Sources/MapConductorForMapKit/circle/MapKitCircleOverlayRenderer.swift @@ -1,6 +1,6 @@ import CoreLocation import MapKit -import MapConductorCore +@_spi(MapConductorDriver) import MapConductorCore import UIKit @MainActor @@ -36,7 +36,7 @@ final class MapKitCircleOverlayRenderer: AbstractCircleOverlayRenderer { @@ -24,7 +24,7 @@ final class MapKitRasterLayerOverlayRenderer: AbstractRasterLayerOverlayRenderer // Important: MapKit may request a renderer immediately as part of addOverlay(). // Ensure we have the renderer registered before adding the overlay to the map. if state.visible { - mapView.addOverlay(overlay, level: .aboveLabels) + MapKitOverlayStacking.add(overlay, OverlayStacking.rasterKey(stateId: state.id, zIndex: state.zIndex), to: mapView) } return overlay @@ -56,7 +56,7 @@ final class MapKitRasterLayerOverlayRenderer: AbstractRasterLayerOverlayRenderer if finger.visible != prevFinger.visible { if current.state.visible { if layer.isKind(of: MKTileOverlay.self) && !mapView.overlays.contains(where: { $0 === layer }) { - mapView.addOverlay(layer, level: .aboveLabels) + MapKitOverlayStacking.add(layer, OverlayStacking.rasterKey(stateId: current.state.id, zIndex: current.state.zIndex), to: mapView) } } else { mapView.removeOverlay(layer) From 536051dbf10142aa262e754589078b613cf57542 Mon Sep 17 00:00:00 2001 From: Masashi Katsumata Date: Sun, 8 Nov 2026 12:53:45 -0800 Subject: [PATCH 15/23] Build no marker icons before the MarkerListIdentity gate on MapKit MapKitMapView.Coordinator.updateContent rebuilt two dictionaries over every marker on each call, before syncMarkers reached its MarkerListIdentity gate: one with each marker's state, and one with each marker's BitmapIcon, which read the @Published icon and, for markers with no icon, made a fresh DefaultMarkerIcon() and drew it again. SwiftUI calls updateContent on every body evaluation, camera moves included, so a resent identical list paid for all of it although the gate then threw the work away. Cost of one updateContent with the same content, 144,183 markers, simulator, best of 15: Debug Release 1 in 4 with no icon 2970 ms -> 12.6 ms 2608 ms -> 0.04 ms every marker an icon 111 ms -> 27.0 ms 61 ms -> 0.14 ms Neither dictionary is needed. The state cache duplicated what MapKitMarkerController already keeps from its last processed list (markerStatesById, filled synchronously when the gate lets a list through, before add() runs), now exposed as syncedMarkerState(for:). The icon cache is replaced by reading the icon off the state in mapView(_:viewFor:); toBitmapIcon() keeps the drawn image per icon, and the no-icon marker shares one default image. Reading the current state also means an annotation view recreated after an in-place icon change shows the new icon, rather than whatever the cache held at the last body evaluation. The other iOS providers already put the gate first. Checked on the iPad (Debug): the marker basic and street tree pages look the same as before, and on a check page a new marker state under the same id and an in-place icon change both show up as before. --- .../MapConductorForMapKit/MapKitMapView.swift | 44 +++++++++---------- .../marker/MapKitMarkerController.swift | 6 +++ 2 files changed, 26 insertions(+), 24 deletions(-) diff --git a/Sources/MapConductorForMapKit/MapKitMapView.swift b/Sources/MapConductorForMapKit/MapKitMapView.swift index 763dedd..a208aed 100644 --- a/Sources/MapConductorForMapKit/MapKitMapView.swift +++ b/Sources/MapConductorForMapKit/MapKitMapView.swift @@ -186,11 +186,9 @@ private struct MapKitMapViewRepresentable: UIViewRepresentable { private weak var draggingAnnotationView: MKAnnotationView? private var dragDisplayLink: CADisplayLink? - // Store icon for each marker state to provide to delegate (best-effort cache). - // `mapView(_:viewFor:)` should not depend on this cache because it can be called - // before `updateContent` finishes populating it. - private var markerIcons: [String: BitmapIcon] = [:] - private var markerStates: [String: MarkerState] = [:] + /// アイコンを持たないマーカーの絵。1 枚を使い回す(`DefaultMarkerIcon()` を毎回作ると + /// そのたびに描き直しになる)。 + private let defaultBitmapIcon = DefaultMarkerIcon().toBitmapIcon() private lazy var strategyManager = StrategyMarkerManager( makeRenderer: { [weak self] strategy in @@ -362,8 +360,6 @@ private struct MapKitMapViewRepresentable: UIViewRepresentable { groundImageController = nil overlayScope?.clear() overlayScope = nil - markerIcons.removeAll() - markerStates.removeAll() strategyMarkerIcons.removeAll() strategyManager.clear() @@ -376,15 +372,11 @@ private struct MapKitMapViewRepresentable: UIViewRepresentable { } infoBubbleCoordinator?.syncInfoBubbles(content.infoBubbles) - // Prime marker caches before triggering MKMapView annotation creation. - // (MapKit can ask for annotation views immediately after addAnnotation.) - markerIcons = content.markers.reduce(into: [:]) { dict, marker in - dict[marker.id] = (marker.state.icon ?? DefaultMarkerIcon()).toBitmapIcon() - } - markerStates = content.markers.reduce(into: [:]) { dict, marker in - dict[marker.id] = marker.state - } - + // マーカーは門番(MarkerListIdentity、syncMarkers の入口)を通るものだけを触る。 + // ここで全マーカーのアイコンや辞書を作ると、同じ一覧の再送でも body の評価ごとに + // 14.4 万本ぶん(@Published の icon の読み出しと、アイコンを持たないマーカーの + // 描き直し)が走り、門番が意味を失う。アイコンは `mapView(_:viewFor:)` が + // その場で state から引き、追加直後の state はコントローラが同期的に持っている。 markerController?.tilingOptions = content.markerTilingOptions markerController?.syncMarkers(content.markers) overlayScope?.circleCollector.sync(content.circles.map { $0.state }) @@ -513,17 +505,20 @@ private struct MapKitMapViewRepresentable: UIViewRepresentable { let mapConductorAnnotation = pointAnnotation as? MapConductorPointAnnotation let markerIdString = mapConductorAnnotation?.markerId ?? pointAnnotation.title ?? "" let markerState = markerController?.getMarkerState(for: markerIdString) - ?? markerStates[markerIdString] + ?? markerController?.syncedMarkerState(for: markerIdString) ?? strategyManager.controller?.markerManager.getEntity(markerIdString)?.state ?? mapConductorAnnotation?.markerState - let cachedIcon = markerIcons[markerIdString] ?? mapConductorAnnotation?.initialBitmapIcon - ?? strategyMarkerIcons[markerIdString] + // アイコンは state の今の値から引く(`toBitmapIcon()` はアイコンごとに描いた絵を + // 覚えているので軽い)。in-place で差し替えたアイコンも、ビューが作り直されたときに + // 古い絵へ戻らない。 + let stateIcon = markerState.map { $0.icon?.toBitmapIcon() ?? defaultBitmapIcon } + let fallbackIcon = mapConductorAnnotation?.initialBitmapIcon ?? strategyMarkerIcons[markerIdString] // If this isn't one of our markers, allow MapKit's default behavior. - if markerState == nil, cachedIcon == nil { return nil } + if markerState == nil, fallbackIcon == nil { return nil } // Avoid returning nil here; returning nil makes MapKit fall back to the default pin annotation. - let resolvedIcon = cachedIcon ?? (markerState?.icon ?? DefaultMarkerIcon()).toBitmapIcon() + let resolvedIcon = stateIcon ?? fallbackIcon ?? defaultBitmapIcon let identifier = "MapKitMarker" let annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: identifier) @@ -531,7 +526,8 @@ private struct MapKitMapViewRepresentable: UIViewRepresentable { annotationView.annotation = annotation if let markerState { - if markerController?.getMarkerState(for: markerIdString) != nil || markerStates[markerIdString] != nil { + if markerController?.getMarkerState(for: markerIdString) != nil + || markerController?.syncedMarkerState(for: markerIdString) != nil { markerController?.renderer.configureAnnotationView(annotationView, for: markerState, bitmapIcon: resolvedIcon) } else { strategyManager.renderer?.configureAnnotationView(annotationView, for: markerState, bitmapIcon: resolvedIcon) @@ -559,7 +555,7 @@ private struct MapKitMapViewRepresentable: UIViewRepresentable { guard let pointAnnotation = view.annotation as? MKPointAnnotation, let markerId = pointAnnotation.title, let markerState = markerController?.getMarkerState(for: markerId) - ?? markerStates[markerId] + ?? markerController?.syncedMarkerState(for: markerId) ?? strategyManager.controller?.markerManager.getEntity(markerId)?.state else { return } @@ -580,7 +576,7 @@ private struct MapKitMapViewRepresentable: UIViewRepresentable { guard let pointAnnotation = view.annotation as? MKPointAnnotation, let markerId = pointAnnotation.title, let markerState = markerController?.getMarkerState(for: markerId) - ?? markerStates[markerId] else { + ?? markerController?.syncedMarkerState(for: markerId) else { return } diff --git a/Sources/MapConductorForMapKit/marker/MapKitMarkerController.swift b/Sources/MapConductorForMapKit/marker/MapKitMarkerController.swift index 5833a1f..ba3fc19 100644 --- a/Sources/MapConductorForMapKit/marker/MapKitMarkerController.swift +++ b/Sources/MapConductorForMapKit/marker/MapKitMarkerController.swift @@ -105,6 +105,12 @@ final class MapKitMarkerController: AbstractMarkerController MarkerState? { + markerStatesById[id] + } + func getIcon(for state: MarkerState) -> BitmapIcon { let resolvedIcon = state.icon ?? DefaultMarkerIcon() return resolvedIcon.toBitmapIcon() From c40c51f405f8f3f80b77891a050417a179cc1464 Mon Sep 17 00:00:00 2001 From: Masashi Katsumata Date: Mon, 9 Nov 2026 10:35:33 -0800 Subject: [PATCH 16/23] Draw many polylines as raster tiles Give the polyline controller a PolylineTiler whose template is upserted as the "mc-polyline-tiles" raster layer (removed by id when nothing is tiled), as the polygon tiles are. The content's polylineTilingOptions reach the tiler on every content update; a change re-routes the current list. The tile layer stacks at the bottom of the polyline band (OverlayStacking.rasterKey). --- Sources/MapConductorForMapKit/MapKitMapView.swift | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/Sources/MapConductorForMapKit/MapKitMapView.swift b/Sources/MapConductorForMapKit/MapKitMapView.swift index 669b0b7..3d15c00 100644 --- a/Sources/MapConductorForMapKit/MapKitMapView.swift +++ b/Sources/MapConductorForMapKit/MapKitMapView.swift @@ -280,6 +280,17 @@ private struct MapKitMapViewRepresentable: UIViewRepresentable { } } polygonController.tiler = polygonTiler + // Many polylines likewise, in their own raster layer in the polyline band + // (under the natively drawn polylines); taps still resolve against the original lines. + let polylineTiler = PolylineTiler() + polylineTiler.onTemplate = { [weak rasterLayerController] template, tileSize in + if let template { + await rasterLayerController?.upsert(state: PolylineTiler.rasterLayerState(template: template, tileSize: tileSize)) + } else { + await rasterLayerController?.removeById(PolylineTiler.layerId) + } + } + polylineController.tiler = polylineTiler let groundImageController = MapKitGroundImageController(mapView: mapView) self.groundImageController = groundImageController @@ -394,6 +405,8 @@ private struct MapKitMapViewRepresentable: UIViewRepresentable { overlayScope?.polylineCollector.sync(content.polylines.map { $0.state }) overlayScope?.polygonCollector.sync(content.polygons.map { $0.state }) polygonController?.tiler?.refreshIfServerMoved() + if polylineController?.tiler?.setOptions(content.polylineTilingOptions) == true { overlayScope?.polylineCollector.flush() } + polylineController?.tiler?.refreshIfServerMoved() for handler in content.polygonSyncHandlers { let hullController = hullPolygonController handler.bindPolygonSync { [weak hullController] states in From e6644b1cc507a3d587a26d42523e5c5a371272f4 Mon Sep 17 00:00:00 2001 From: Masashi Katsumata Date: Tue, 10 Nov 2026 16:16:51 -0800 Subject: [PATCH 17/23] Support bulk Circles with raster tiles --- .../MapConductorForMapKit/MapKitMapView.swift | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/Sources/MapConductorForMapKit/MapKitMapView.swift b/Sources/MapConductorForMapKit/MapKitMapView.swift index 3d15c00..5f659cf 100644 --- a/Sources/MapConductorForMapKit/MapKitMapView.swift +++ b/Sources/MapConductorForMapKit/MapKitMapView.swift @@ -291,6 +291,15 @@ private struct MapKitMapViewRepresentable: UIViewRepresentable { } } polylineController.tiler = polylineTiler + let circleTiler = CircleTiler() + circleTiler.onTemplate = { [weak rasterLayerController] template, tileSize in + if let template { + await rasterLayerController?.upsert(state: CircleTiler.rasterLayerState(template: template, tileSize: tileSize)) + } else { + await rasterLayerController?.removeById(CircleTiler.layerId) + } + } + circleController.tiler = circleTiler let groundImageController = MapKitGroundImageController(mapView: mapView) self.groundImageController = groundImageController @@ -391,6 +400,7 @@ private struct MapKitMapViewRepresentable: UIViewRepresentable { MCLog.map("MapKitMapView.updateContent markers=\(content.markers.count) circles=\(content.circles.count) polylines=\(content.polylines.count) polygons=\(content.polygons.count)") if let mapView { polylineController?.setCurrentCameraPosition(currentCameraPosition(from: mapView)) + circleController?.setCurrentCameraPosition(currentCameraPosition(from: mapView)) } infoBubbleCoordinator?.syncInfoBubbles(content.infoBubbles) @@ -406,7 +416,9 @@ private struct MapKitMapViewRepresentable: UIViewRepresentable { overlayScope?.polygonCollector.sync(content.polygons.map { $0.state }) polygonController?.tiler?.refreshIfServerMoved() if polylineController?.tiler?.setOptions(content.polylineTilingOptions) == true { overlayScope?.polylineCollector.flush() } + if circleController?.tiler?.setOptions(content.circleTilingOptions) == true { overlayScope?.circleCollector.flush() } polylineController?.tiler?.refreshIfServerMoved() + circleController?.tiler?.refreshIfServerMoved() for handler in content.polygonSyncHandlers { let hullController = hullPolygonController handler.bindPolygonSync { [weak hullController] states in @@ -424,6 +436,7 @@ private struct MapKitMapViewRepresentable: UIViewRepresentable { isRegionChanging = true let camera = currentCameraPosition(from: mapView) polylineController?.setCurrentCameraPosition(camera) + circleController?.setCurrentCameraPosition(camera) controller?.notifyCameraMoveStart(camera) onCameraMoveStart?(camera) } @@ -433,6 +446,7 @@ private struct MapKitMapViewRepresentable: UIViewRepresentable { let camera = mapView.toMapCameraPosition(logicalTiltHint: controller?.lastLogicalTilt) state.updateCameraPosition(camera) polylineController?.setCurrentCameraPosition(camera) + circleController?.setCurrentCameraPosition(camera) controller?.notifyCameraMove(camera) onCameraMove?(camera) Task { [weak self] in @@ -451,6 +465,7 @@ private struct MapKitMapViewRepresentable: UIViewRepresentable { if controller?.applyCameraRestrictionCorrectionIfNeeded(camera) == true { return } state.updateCameraPosition(camera) polylineController?.setCurrentCameraPosition(camera) + circleController?.setCurrentCameraPosition(camera) controller?.notifyCameraMoveEnd(camera) onCameraMoveEnd?(camera) Task { [weak self] in @@ -473,6 +488,7 @@ private struct MapKitMapViewRepresentable: UIViewRepresentable { // Ensure polyline hit-testing uses the current zoom even if no region-change callbacks have fired yet. polylineController?.setCurrentCameraPosition(currentCameraPosition(from: mapView)) + circleController?.setCurrentCameraPosition(currentCameraPosition(from: mapView)) // If the user tapped a marker/annotation view, do not also fire map click. // (A tap gesture recognizer attached to MKMapView can still recognize taps on subviews.) From f93e02e3cc67efcd1220f3d60ac08ee227d3318c Mon Sep 17 00:00:00 2001 From: Masashi Katsumata Date: Wed, 11 Nov 2026 11:09:18 -0800 Subject: [PATCH 18/23] Apply marker zIndex through zPriority Annotation views had no zPriority, so MapKit chose the order and zIndex did nothing. Map MarkerDrawOrder onto zPriority (500 + 5 x key, zIndex clamped to +-99) and reset it on reused views. --- .../MapConductorForMapKit/MapKitMapView.swift | 2 ++ .../marker/MapKitMarkerRenderer.swift | 20 ++++++++++++++++++- 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/Sources/MapConductorForMapKit/MapKitMapView.swift b/Sources/MapConductorForMapKit/MapKitMapView.swift index 5f659cf..d714628 100644 --- a/Sources/MapConductorForMapKit/MapKitMapView.swift +++ b/Sources/MapConductorForMapKit/MapKitMapView.swift @@ -583,6 +583,8 @@ private struct MapKitMapViewRepresentable: UIViewRepresentable { y: -(resolvedIcon.anchor.y - 0.5) * resolvedIcon.bitmap.size.height ) annotationView.alpha = 1 + // 使い回したビューに前のマーカーの順位を残さない。 + annotationView.zPriority = .defaultUnselected } return annotationView diff --git a/Sources/MapConductorForMapKit/marker/MapKitMarkerRenderer.swift b/Sources/MapConductorForMapKit/marker/MapKitMarkerRenderer.swift index b325ab9..725321b 100644 --- a/Sources/MapConductorForMapKit/marker/MapKitMarkerRenderer.swift +++ b/Sources/MapConductorForMapKit/marker/MapKitMarkerRenderer.swift @@ -1,7 +1,7 @@ import CoreGraphics import CoreLocation import MapKit -import MapConductorCore +@_spi(MapConductorDriver) import MapConductorCore @MainActor final class MapKitMarkerRenderer: MarkerOverlayRendererProtocol { @@ -283,6 +283,21 @@ final class MapKitMarkerRenderer: MarkerOverlayRendererProtocol { mapView = nil } + /// ``MarkerDrawOrder`` を MapKit の `zPriority`(Float、0...1000、既定 500、大きいほど手前)へ写す。 + /// + /// `500 + 5 × key`。zIndex は ±``zPriorityZIndexSpan`` に丸める(それを超える zIndex どうしは + /// 区別しない)。1 段を 5 にするのは、同じ zIndex の中の南・西の順位(key の小数部)を + /// Float でも数百 m 程度まで区別できるようにするため。選択中のビューは MapKit が + /// `selectedZPriority`(1000)へ上げる。 + static func zPriority(for state: MarkerState) -> MKAnnotationViewZPriority { + let zIndex = state.zIndex.map { min(max($0, -zPriorityZIndexSpan), zPriorityZIndexSpan) } + let key = MarkerDrawOrder.key(zIndex: zIndex, position: state.position) + return MKAnnotationViewZPriority(rawValue: Float(500.0 + 5.0 * key)) + } + + /// ``zPriority(for:)`` が区別する zIndex の絶対値の上限。 + static let zPriorityZIndexSpan = 99 + func configureAnnotationView(_ view: MKAnnotationView, for state: MarkerState, bitmapIcon: BitmapIcon) { view.image = bitmapIcon.bitmap view.isDraggable = state.draggable @@ -294,6 +309,9 @@ final class MapKitMarkerRenderer: MarkerOverlayRendererProtocol { // Store for later reference markerAnnotationViews[state.id] = view + // 重なり順。ビューは使い回されるので、毎回書く(書かないと前のマーカーの値が残る)。 + view.zPriority = Self.zPriority(for: state) + // Set anchor point based on icon anchor // MapKit's centerOffset is from the annotation coordinate to the view center // So y-axis needs to be inverted From 5ec3e05c580a66b7d64b0a685863a93224769901 Mon Sep 17 00:00:00 2001 From: Masashi Katsumata Date: Wed, 11 Nov 2026 14:55:56 -0800 Subject: [PATCH 19/23] Re-key annotation zPriority when the map rotates Same-zIndex markers stack lower-on-screen in front. On a heading change the renderer rewrites zPriority on the visible annotation views; views created later pick up the current frame. --- .../marker/MapKitMarkerRenderer.swift | 27 +++++++++++++++---- 1 file changed, 22 insertions(+), 5 deletions(-) diff --git a/Sources/MapConductorForMapKit/marker/MapKitMarkerRenderer.swift b/Sources/MapConductorForMapKit/marker/MapKitMarkerRenderer.swift index 725321b..a1ad08f 100644 --- a/Sources/MapConductorForMapKit/marker/MapKitMarkerRenderer.swift +++ b/Sources/MapConductorForMapKit/marker/MapKitMarkerRenderer.swift @@ -4,13 +4,15 @@ import MapKit @_spi(MapConductorDriver) import MapConductorCore @MainActor -final class MapKitMarkerRenderer: MarkerOverlayRendererProtocol { +final class MapKitMarkerRenderer: MarkerOverlayRendererProtocol, MarkerDrawOrderFrameReceiver { typealias ActualMarker = MKPointAnnotation private static let maxConcurrentAnimations = 30 private static let minAnimationUpdateInterval: CFTimeInterval = 1.0 / 4.0 weak var mapView: MKMapView? + /// 重なり順を出すときの地図の向き(``MarkerDrawOrder``)。回すとコントローラが差し替える。 + private var drawOrderFrame: MarkerDrawOrder.Frame = .northUp private let markerManager: MarkerManager private var markerAnnotationViews: [String: MKAnnotationView] = [:] private var markerAnimationRunners: [String: MarkerAnimationRunner] = [:] @@ -286,15 +288,30 @@ final class MapKitMarkerRenderer: MarkerOverlayRendererProtocol { /// ``MarkerDrawOrder`` を MapKit の `zPriority`(Float、0...1000、既定 500、大きいほど手前)へ写す。 /// /// `500 + 5 × key`。zIndex は ±``zPriorityZIndexSpan`` に丸める(それを超える zIndex どうしは - /// 区別しない)。1 段を 5 にするのは、同じ zIndex の中の南・西の順位(key の小数部)を + /// 区別しない)。1 段を 5 にするのは、同じ zIndex の中の画面上の順位(key の小数部)を /// Float でも数百 m 程度まで区別できるようにするため。選択中のビューは MapKit が /// `selectedZPriority`(1000)へ上げる。 - static func zPriority(for state: MarkerState) -> MKAnnotationViewZPriority { + static func zPriority( + for state: MarkerState, + frame: MarkerDrawOrder.Frame = .northUp + ) -> MKAnnotationViewZPriority { let zIndex = state.zIndex.map { min(max($0, -zPriorityZIndexSpan), zPriorityZIndexSpan) } - let key = MarkerDrawOrder.key(zIndex: zIndex, position: state.position) + let key = MarkerDrawOrder.key(zIndex: zIndex, position: state.position, frame: frame) return MKAnnotationViewZPriority(rawValue: Float(500.0 + 5.0 * key)) } + /// 回したら、同じ zIndex の中の順位(画面で下ほど手前)を付け直す。画面外でビューの無い + /// マーカーは、ビューが付くときに ``configureAnnotationView(_:for:bitmapIcon:)`` が新しい向きで書く。 + func onDrawOrderFrameChanged(_ frame: MarkerDrawOrder.Frame, entities: [MarkerEntity]) async { + drawOrderFrame = frame + guard let mapView else { return } + for entity in entities { + guard let annotation = entity.marker, let view = mapView.view(for: annotation) else { continue } + let priority = Self.zPriority(for: entity.state, frame: frame) + if view.zPriority != priority { view.zPriority = priority } + } + } + /// ``zPriority(for:)`` が区別する zIndex の絶対値の上限。 static let zPriorityZIndexSpan = 99 @@ -310,7 +327,7 @@ final class MapKitMarkerRenderer: MarkerOverlayRendererProtocol { markerAnnotationViews[state.id] = view // 重なり順。ビューは使い回されるので、毎回書く(書かないと前のマーカーの値が残る)。 - view.zPriority = Self.zPriority(for: state) + view.zPriority = Self.zPriority(for: state, frame: drawOrderFrame) // Set anchor point based on icon anchor // MapKit's centerOffset is from the annotation coordinate to the view center From 155a46aa7d9df77ff5aac5dc1330b7e4ae197134 Mon Sep 17 00:00:00 2001 From: Masashi Katsumata Date: Wed, 11 Nov 2026 21:40:20 -0800 Subject: [PATCH 20/23] Apply camera paddings and report fov on MapKit MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit MKMapCamera has no padding, so the camera center is shifted with the core CameraPaddingEmulation (using MapKit's measured vertical fov, 30°) and shifted back on read; the read camera carries paddings and fov. --- .../MapCameraPositionExtensions.swift | 6 ++++ .../MapConductorForMapKit/MapKitMapView.swift | 6 ++-- .../controller/MapKitViewController.swift | 29 +++++++++++++++++-- 3 files changed, 36 insertions(+), 5 deletions(-) diff --git a/Sources/MapConductorForMapKit/MapCameraPositionExtensions.swift b/Sources/MapConductorForMapKit/MapCameraPositionExtensions.swift index b740503..1283bf7 100644 --- a/Sources/MapConductorForMapKit/MapCameraPositionExtensions.swift +++ b/Sources/MapConductorForMapKit/MapCameraPositionExtensions.swift @@ -8,6 +8,12 @@ private let mapConductorTileSizePoints: Double = 256.0 private let minCosLat: Double = 0.01 private let minCosTilt: Double = 0.05 +/// MapKit(iOS)のカメラの縦の視野角(度)。 +/// +/// MapKit は値を公開していない。iPad Pro 11 で、傾けた地図の中心と北の地点の画面位置から +/// 焦点距離を求めて実測した値(tilt 30°)。 +let mapKitVerticalFieldOfView: Double = 30.0 + // Convert from MapCameraPosition to MKMapCamera public extension MapCameraPosition { /// Pass the target map view so the camera distance is derived from the view's actual diff --git a/Sources/MapConductorForMapKit/MapKitMapView.swift b/Sources/MapConductorForMapKit/MapKitMapView.swift index 5f659cf..0430eab 100644 --- a/Sources/MapConductorForMapKit/MapKitMapView.swift +++ b/Sources/MapConductorForMapKit/MapKitMapView.swift @@ -443,7 +443,8 @@ private struct MapKitMapViewRepresentable: UIViewRepresentable { func mapViewDidChangeVisibleRegion(_ mapView: MKMapView) { guard isRegionChanging else { return } - let camera = mapView.toMapCameraPosition(logicalTiltHint: controller?.lastLogicalTilt) + let raw = mapView.toMapCameraPosition(logicalTiltHint: controller?.lastLogicalTilt) + let camera = controller?.reportedCamera(raw, mapView: mapView) ?? raw state.updateCameraPosition(camera) polylineController?.setCurrentCameraPosition(camera) circleController?.setCurrentCameraPosition(camera) @@ -765,10 +766,11 @@ private struct MapKitMapViewRepresentable: UIViewRepresentable { farRight: geoPoint(at: CGPoint(x: mapView.bounds.maxX, y: 0), mapView: mapView) ) - return mapView.toMapCameraPosition( + let raw = mapView.toMapCameraPosition( logicalTiltHint: controller?.lastLogicalTilt, visibleRegion: visibleRegion ) + return controller?.reportedCamera(raw, mapView: mapView) ?? raw } private func geoPoint(at point: CGPoint, mapView: MKMapView) -> GeoPoint? { diff --git a/Sources/MapConductorForMapKit/controller/MapKitViewController.swift b/Sources/MapConductorForMapKit/controller/MapKitViewController.swift index c5e0f86..105ba9a 100644 --- a/Sources/MapConductorForMapKit/controller/MapKitViewController.swift +++ b/Sources/MapConductorForMapKit/controller/MapKitViewController.swift @@ -16,6 +16,9 @@ final class MapKitViewController: MapViewControllerProtocol { let overlayControllers = OverlayControllerRegistry() private weak var mapView: MKMapView? private(set) var lastLogicalTilt: Double? + /// 直近の移動で要求されたパディング。MapKit のカメラはパディングを持たないので、中心をずらして + /// 再現し(``CameraPaddingEmulation``)、読み戻しで逆にずらすときに使う。 + private(set) var lastPaddings: MapPaddingsProtocol? private let tileSizePoints: Double = 256.0 private let minCosLat: Double = 0.01 @@ -96,9 +99,11 @@ final class MapKitViewController: MapViewControllerProtocol { mapInitializedListener = listener } - func moveCamera(position: MapCameraPosition) { + func moveCamera(position requested: MapCameraPosition) { cancelCameraAnimation() guard let mapView = mapView else { return } + lastPaddings = requested.paddings + let position = paddingApplied(requested, mapView: mapView) lastLogicalTilt = position.tilt if abs(position.tilt) < 0.01, mapView.bounds.isEmpty { DispatchQueue.main.async { [weak self, weak mapView] in @@ -113,14 +118,17 @@ final class MapKitViewController: MapViewControllerProtocol { mapView.setCamera(camera, animated: false) } - func animateCamera(position: MapCameraPosition, duration: Long) { + func animateCamera(position requested: MapCameraPosition, duration: Long) { cancelCameraAnimation() guard let mapView = mapView else { return } let durationSeconds = Double(duration) / 1000.0 guard durationSeconds > 0 else { - moveCamera(position: position) + moveCamera(position: requested) return } + lastPaddings = requested.paddings + // 補間は「画面中心」の空間で行う(from も中心のまま読む)。 + let position = paddingApplied(requested, mapView: mapView) let from = mapView.toMapCameraPosition(logicalTiltHint: lastLogicalTilt) lastLogicalTilt = position.tilt @@ -301,6 +309,21 @@ final class MapKitViewController: MapViewControllerProtocol { } } + /// MapKit へ渡すカメラ。パディングの分だけ中心をずらす。 + private func paddingApplied(_ position: MapCameraPosition, mapView: MKMapView) -> MapCameraPosition { + CameraPaddingEmulation.applied(to: position, fov: mapKitVerticalFieldOfView, viewportSize: mapView.bounds.size) + } + + /// MapKit から読み戻したカメラ(画面中心)を、ターゲット・パディング・視野角を持つカメラへ戻す。 + func reportedCamera(_ camera: MapCameraPosition, mapView: MKMapView) -> MapCameraPosition { + CameraPaddingEmulation.restored( + camera, + paddings: lastPaddings, + fov: mapKitVerticalFieldOfView, + viewportSize: mapView.bounds.size + ) + } + private func applyCameraFrame(_ position: MapCameraPosition, mapView: MKMapView) { lastLogicalTilt = position.tilt // One-step move (no MapKit internal animation). This is the basis for our custom duration-controlled animation. From 9ea8fe3ec276cd5f5c74e38186180252b6711c42 Mon Sep 17 00:00:00 2001 From: Masashi Katsumata Date: Wed, 11 Nov 2026 21:59:17 -0800 Subject: [PATCH 21/23] Measure the padded target with MapKit's projection MapKit's scale differs slightly from the model and its pitch limit depends on altitude, so after each move (and at the end of an animation) the camera center is corrected with the map's projection, and the target is read back from the padded center. --- .../controller/MapKitViewController.swift | 39 ++++++++++++++++++- 1 file changed, 38 insertions(+), 1 deletion(-) diff --git a/Sources/MapConductorForMapKit/controller/MapKitViewController.swift b/Sources/MapConductorForMapKit/controller/MapKitViewController.swift index 105ba9a..904d276 100644 --- a/Sources/MapConductorForMapKit/controller/MapKitViewController.swift +++ b/Sources/MapConductorForMapKit/controller/MapKitViewController.swift @@ -19,6 +19,8 @@ final class MapKitViewController: MapViewControllerProtocol { /// 直近の移動で要求されたパディング。MapKit のカメラはパディングを持たないので、中心をずらして /// 再現し(``CameraPaddingEmulation``)、読み戻しで逆にずらすときに使う。 private(set) var lastPaddings: MapPaddingsProtocol? + /// アニメーションの終わりに、ターゲットの位置を投影で詰め直すための要求。 + private var cameraAnimationRequested: MapCameraPosition? private let tileSizePoints: Double = 256.0 private let minCosLat: Double = 0.01 @@ -112,10 +114,12 @@ final class MapKitViewController: MapViewControllerProtocol { } } if applyTopDownZoom(position: position, mapView: mapView, animated: false) { + correctPaddedTarget(requested, mapView: mapView) return } let camera = position.toMKMapCamera(on: mapView) mapView.setCamera(camera, animated: false) + correctPaddedTarget(requested, mapView: mapView) } func animateCamera(position requested: MapCameraPosition, duration: Long) { @@ -129,6 +133,7 @@ final class MapKitViewController: MapViewControllerProtocol { lastPaddings = requested.paddings // 補間は「画面中心」の空間で行う(from も中心のまま読む)。 let position = paddingApplied(requested, mapView: mapView) + cameraAnimationRequested = requested let from = mapView.toMapCameraPosition(logicalTiltHint: lastLogicalTilt) lastLogicalTilt = position.tilt @@ -273,6 +278,7 @@ final class MapKitViewController: MapViewControllerProtocol { } private func cancelCameraAnimation() { + cameraAnimationRequested = nil cameraAnimationDisplayLink?.invalidate() cameraAnimationDisplayLink = nil cameraAnimationFrames.removeAll() @@ -303,6 +309,10 @@ final class MapKitViewController: MapViewControllerProtocol { let frame = cameraAnimationFrames[targetIndex] applyCameraFrame(frame, mapView: mapView) } + if progress >= 1.0, let requested = cameraAnimationRequested { + cameraAnimationRequested = nil + correctPaddedTarget(requested, mapView: mapView) + } if progress >= 1.0 { cancelCameraAnimation() @@ -315,15 +325,42 @@ final class MapKitViewController: MapViewControllerProtocol { } /// MapKit から読み戻したカメラ(画面中心)を、ターゲット・パディング・視野角を持つカメラへ戻す。 + /// ターゲットはパディングの残りの中央にある地点を地図に直接聞く。 func reportedCamera(_ camera: MapCameraPosition, mapView: MKMapView) -> MapCameraPosition { CameraPaddingEmulation.restored( camera, paddings: lastPaddings, fov: mapKitVerticalFieldOfView, - viewportSize: mapView.bounds.size + viewportSize: mapView.bounds.size, + unproject: { [weak mapView] point in + guard let mapView else { return nil } + let coordinate = mapView.convert(point, toCoordinateFrom: mapView) + return GeoPoint(latitude: coordinate.latitude, longitude: coordinate.longitude) + } ) } + /// 計算で置いた中心だと、MapKit の縮尺のずれや pitch の上限(高度で変わる)でターゲットが + /// ずれる。地図の投影で実際の位置を測り、パディングの残りの中央に来るまで中心だけを動かし直す。 + private func correctPaddedTarget(_ requested: MapCameraPosition, mapView: MKMapView) { + let target = CLLocationCoordinate2D(latitude: requested.position.latitude, longitude: requested.position.longitude) + for _ in 0..<3 { + guard let center = CameraPaddingEmulation.correctedCenter( + target: requested.position, + paddings: requested.paddings, + viewportSize: mapView.bounds.size, + project: { _ in mapView.convert(target, toPointTo: mapView) }, + unproject: { point in + let coordinate = mapView.convert(point, toCoordinateFrom: mapView) + return GeoPoint(latitude: coordinate.latitude, longitude: coordinate.longitude) + } + ) else { return } + let camera = mapView.camera.copy() as! MKMapCamera + camera.centerCoordinate = CLLocationCoordinate2D(latitude: center.latitude, longitude: center.longitude) + mapView.setCamera(camera, animated: false) + } + } + private func applyCameraFrame(_ position: MapCameraPosition, mapView: MKMapView) { lastLogicalTilt = position.tilt // One-step move (no MapKit internal animation). This is the basis for our custom duration-controlled animation. From f5807f838e619f2496a4f017a11fafa9faaffc61 Mon Sep 17 00:00:00 2001 From: Masashi Katsumata Date: Wed, 11 Nov 2026 22:11:17 -0800 Subject: [PATCH 22/23] Apply MapKit padding corrections on separate run loop turns Back-to-back setCamera calls let MapKit fold the region-change notifications, so the state kept the camera from before the correction. --- .../controller/MapKitViewController.swift | 29 +++++++++++-------- 1 file changed, 17 insertions(+), 12 deletions(-) diff --git a/Sources/MapConductorForMapKit/controller/MapKitViewController.swift b/Sources/MapConductorForMapKit/controller/MapKitViewController.swift index 904d276..bd5dacd 100644 --- a/Sources/MapConductorForMapKit/controller/MapKitViewController.swift +++ b/Sources/MapConductorForMapKit/controller/MapKitViewController.swift @@ -342,22 +342,27 @@ final class MapKitViewController: MapViewControllerProtocol { /// 計算で置いた中心だと、MapKit の縮尺のずれや pitch の上限(高度で変わる)でターゲットが /// ずれる。地図の投影で実際の位置を測り、パディングの残りの中央に来るまで中心だけを動かし直す。 - private func correctPaddedTarget(_ requested: MapCameraPosition, mapView: MKMapView) { + private func correctPaddedTarget(_ requested: MapCameraPosition, mapView: MKMapView, remaining: Int = 3) { + guard remaining > 0 else { return } let target = CLLocationCoordinate2D(latitude: requested.position.latitude, longitude: requested.position.longitude) - for _ in 0..<3 { - guard let center = CameraPaddingEmulation.correctedCenter( - target: requested.position, - paddings: requested.paddings, - viewportSize: mapView.bounds.size, - project: { _ in mapView.convert(target, toPointTo: mapView) }, - unproject: { point in - let coordinate = mapView.convert(point, toCoordinateFrom: mapView) - return GeoPoint(latitude: coordinate.latitude, longitude: coordinate.longitude) - } - ) else { return } + guard let center = CameraPaddingEmulation.correctedCenter( + target: requested.position, + paddings: requested.paddings, + viewportSize: mapView.bounds.size, + project: { _ in mapView.convert(target, toPointTo: mapView) }, + unproject: { point in + let coordinate = mapView.convert(point, toCoordinateFrom: mapView) + return GeoPoint(latitude: coordinate.latitude, longitude: coordinate.longitude) + } + ) else { return } + // 1 回ずつ次のランループで当てる。同じランループで続けて setCamera すると MapKit は + // 領域変更の通知をまとめてしまい、state に途中のカメラが残る。 + DispatchQueue.main.async { [weak self, weak mapView] in + guard let self, let mapView else { return } let camera = mapView.camera.copy() as! MKMapCamera camera.centerCoordinate = CLLocationCoordinate2D(latitude: center.latitude, longitude: center.longitude) mapView.setCamera(camera, animated: false) + self.correctPaddedTarget(requested, mapView: mapView, remaining: remaining - 1) } } From 087674fca587107df9e971f54ba61894197a0d47 Mon Sep 17 00:00:00 2001 From: Masashi Katsumata Date: Fri, 13 Nov 2026 03:51:11 -0800 Subject: [PATCH 23/23] Release 1.4.0 --- Package.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Package.swift b/Package.swift index 3b0a8c9..1c60ce0 100644 --- a/Package.swift +++ b/Package.swift @@ -7,7 +7,7 @@ let frameworkLibraryType: Product.Library.LibraryType? = let usingLocalCore = FileManager.default.fileExists(atPath: "../ios-sdk-core/Package.swift") let coreDependency: Package.Dependency = usingLocalCore ? .package(path: "../ios-sdk-core") - : .package(url: "https://github.com/MapConductor/ios-sdk-core", from: "1.3.2") + : .package(url: "https://github.com/MapConductor/ios-sdk-core", from: "1.4.0") let package = Package( name: "mapconductor-for-mapkit",