diff --git a/android-sdk-core b/android-sdk-core index e72063ec..d67d7cf0 160000 --- a/android-sdk-core +++ b/android-sdk-core @@ -1 +1 @@ -Subproject commit e72063ecdfed7ac071890f727cf11f1808d85782 +Subproject commit d67d7cf0d1082b7fc0eca19901b7b27984aac63b diff --git a/example-app/src/main/java/com/mapconductor/example/DemoAppScreen.kt b/example-app/src/main/java/com/mapconductor/example/DemoAppScreen.kt index c98fe1fc..67337a6e 100644 --- a/example-app/src/main/java/com/mapconductor/example/DemoAppScreen.kt +++ b/example-app/src/main/java/com/mapconductor/example/DemoAppScreen.kt @@ -1,475 +1,476 @@ -package com.mapconductor.example - -import androidx.appcompat.content.res.AppCompatResources -import androidx.compose.foundation.layout.Box -import androidx.compose.foundation.layout.fillMaxSize -import androidx.compose.runtime.Composable -import androidx.compose.runtime.getValue -import androidx.compose.runtime.remember -import androidx.compose.ui.Modifier -import androidx.compose.ui.platform.LocalContext -import androidx.core.content.ContextCompat -import com.mapconductor.core.marker.ImageIcon -import com.mapconductor.example.navigation.NavigationViewModel -import com.mapconductor.example.pages.circle.AntennaHorizonsPage -import com.mapconductor.example.pages.circle.CircleMapPage -import com.mapconductor.example.pages.geojson.basic.BasicGeoJSONMapPage -import com.mapconductor.example.pages.geojson.layer.GeoJSONLayerMapPage -import com.mapconductor.example.pages.groundimage.GroundImageMapPage -import com.mapconductor.example.pages.groundimage.GroundImageResources -import com.mapconductor.example.pages.heatmaplayer.HeatmapLayerPage -import com.mapconductor.example.pages.infobubble.MultipleBubblesPage -import com.mapconductor.example.pages.infobubble.RichContentBubblePage -import com.mapconductor.example.pages.infobubble.SimpleTextBubblePage -import com.mapconductor.example.pages.infobubble.StyledInfoBubblePage -import com.mapconductor.example.pages.kml.KMLMapPage -import com.mapconductor.example.pages.map.basic.StoreMapPage -import com.mapconductor.example.pages.map.camerarestriction.CameraRestrictionMapPage -import com.mapconductor.example.pages.map.camerasync.CameraSyncPage -import com.mapconductor.example.pages.map.design.MapDesignMapPage -import com.mapconductor.example.pages.map.fitbounds.FitBoundsMapPage -import com.mapconductor.example.pages.map.flyto.FlyToMapIcons -import com.mapconductor.example.pages.map.flyto.FlyToMapPage -import com.mapconductor.example.pages.map.projected.ProjectedCoordinatesPage -import com.mapconductor.example.pages.map.tilt.TiltMapPage -import com.mapconductor.example.pages.map.uisettings.UISettingsMapPage -import com.mapconductor.example.pages.map.visibleregion.VisibleRegionPage -import com.mapconductor.example.pages.marker.animation.AnimationMapPage -import com.mapconductor.example.pages.marker.icons.MarkerBasicPage -import com.mapconductor.example.pages.marker.labelposition.MarkerLabelPositionPage -import com.mapconductor.example.pages.marker.postoffice.PostOfficePage -import com.mapconductor.example.pages.marker.postofficecluster.MarkerClusterMapPage as PostOfficeClusterMapPage -import com.mapconductor.example.pages.marker.streettree.StreetTreePage -import com.mapconductor.example.pages.offlinemap.OfflineMapPage -import com.mapconductor.example.pages.polygon.basic.PolygonMapPage -import com.mapconductor.example.pages.polygon.boston.BostonBuildingsPage -import com.mapconductor.example.pages.polygon.click.PolygonClickPage -import com.mapconductor.example.pages.polygon.collection.PolygonsMapPage -import com.mapconductor.example.pages.polygon.geodesic.PolygonGeodesicPage -import com.mapconductor.example.pages.polygon.hole.HolePolygonMapPage -import com.mapconductor.example.pages.polyline.PolylineClickMapPage -import com.mapconductor.example.pages.polyline.PolylineMapPage -import com.mapconductor.example.pages.polyline.boston.BostonRoadsPage -import com.mapconductor.example.pages.rasterlayer.RasterHeaderProbePage -import com.mapconductor.example.pages.rasterlayer.RasterLayerMapPage -import com.mapconductor.example.pages.startup.StartUpPage -import com.mapconductor.example.pages.vectorstyle.VectorStylePage -import com.mapconductor.example.pages.vectortile.VectorTilePage -import com.mapconductor.example.ui.sidebar.Sidebar -import com.mapconductor.example.ui.sidebar.SidebarItem -import com.mapconductor.example.ui.sidebar.SidebarSection -import com.mapconductor.example.ui.theme.AppTheme - -@Composable -fun DemoAppScreen(initPage: String = "map") { - val navigationViewModel: NavigationViewModel = remember { NavigationViewModel(initPage) } - - val currentPage by navigationViewModel.currentPage - val isSidebarExpanded by navigationViewModel.isSidebarExpanded - val context = LocalContext.current - val flyToMapPageIcons = - remember { - FlyToMapIcons( - honolulu = ContextCompat.getDrawable(context, R.drawable.honolulu)!!, - tokyo = ContextCompat.getDrawable(context, R.drawable.tokyo)!!, - london = ContextCompat.getDrawable(context, R.drawable.london)!!, - newYork = ContextCompat.getDrawable(context, R.drawable.newyork)!!, - sydney = ContextCompat.getDrawable(context, R.drawable.sydney)!!, - ) - } - - val groundImageResources = - remember { - GroundImageResources( - image = ContextCompat.getDrawable(context, R.drawable.university_of_eswatini)!!, - ) - } - val postOfficeIcon = - remember { - val baseicon = AppCompatResources.getDrawable(context, R.drawable.postoffice)!! - ImageIcon( - image = baseicon, - scale = 0.5f, - ) - } - - val sidebarSections = - listOf( - SidebarSection( - title = "Map", - items = - listOf( - SidebarItem(id = "map-basic", title = "Map"), - SidebarItem(id = "tilt-map", title = "Tilt Map"), - SidebarItem(id = "ui-settings", title = "UI Settings"), - SidebarItem(id = "map-flyTo", title = "Move Camera"), - SidebarItem(id = "map-fitBounds", title = "Fit Bounds"), - SidebarItem(id = "map-design", title = "Map Design"), - SidebarItem(id = "map-visibleregion", title = "Visible Region"), - SidebarItem(id = "map-projected", title = "Projected Coordinates"), - SidebarItem(id = "map-camerasync", title = "Camera Sync"), - SidebarItem(id = "camera-restriction", title = "Camera Restriction"), - ), - ), - SidebarSection( - title = "Info Bubble", - items = - listOf( - SidebarItem(id = "simple-info-bubble", title = "Simple Text Bubble"), - SidebarItem(id = "styled-info-bubble", title = "Custom Styled Bubble"), - SidebarItem(id = "rich-content-info-bubble", title = "Rich Content Bubble"), - SidebarItem(id = "multiple-info-bubbles", title = "Multiple Bubbles"), - ), - ), - SidebarSection( - title = "Marker", - items = - listOf( - SidebarItem(id = "marker-basic", title = "Marker"), - SidebarItem(id = "marker-label-position", title = "Marker Label Position"), - SidebarItem(id = "marker-animation", title = "Marker Animation"), - SidebarItem(id = "marker-postoffice", title = "Bunch of Markers"), - SidebarItem(id = "marker-postoffice-cluster", title = "Marker Clustering"), - SidebarItem(id = "marker-streettree", title = "Street Trees"), - ), - ), - SidebarSection( - title = "Circle", - items = listOf( - SidebarItem(id = "circle", title = "Circle"), - SidebarItem(id = "antenna-horizons", title = "US Antenna Horizons") - ), - ), - SidebarSection( - title = "Ground Image", - items = listOf(SidebarItem(id = "groundImage", title = "Ground Image")), - ), - SidebarSection( - title = "Polyline", - items = - listOf( - SidebarItem(id = "polyline", title = "Polyline"), - SidebarItem(id = "polyline-click", title = "Polyline Click"), - SidebarItem(id = "boston-roads", title = "Boston Roads"), - ), - ), - SidebarSection( - title = "Polygon", - items = - listOf( - SidebarItem(id = "polygon", title = "Polygon"), - SidebarItem(id = "polygon-click", title = "Polygon Click"), - SidebarItem(id = "polygon-geodesic", title = "Geodesic Polygons"), - SidebarItem(id = "polygon-hole", title = "Hole Polygon"), - SidebarItem(id = "polygons", title = "Polygons"), - SidebarItem(id = "boston-buildings", title = "Boston Buildings"), - ), - ), - SidebarSection( - title = "Raster Layer", - items = listOf(SidebarItem(id = "raster-layer", title = "Raster Layer")), - ), - SidebarSection( - title = "Heatmap Layer", - items = listOf(SidebarItem(id = "heatmap-overlay", title = "Heatmap Overlay")), - ), - SidebarSection( - title = "Vector Tile Layer", - items = - listOf( - SidebarItem(id = "vector-tile", title = "MapLibre Style"), - SidebarItem(id = "vector-style", title = "Style Adjustments"), - SidebarItem(id = "offline-map", title = "Offline Map"), - ), - ), - SidebarSection( - title = "GeoJSON", - items = - listOf( - SidebarItem(id = "geojson-basic", title = "Basic GeoJSON"), - SidebarItem(id = "geojson-layer", title = "GeoJSON Layer"), - ), - ), - SidebarSection( - title = "KML", - items = listOf(SidebarItem(id = "kml-layer", title = "KML Layer")), - ), - ) - - AppTheme { - Box(modifier = Modifier.fillMaxSize()) { - // Main content - Box(modifier = Modifier.fillMaxSize()) { - when (currentPage) { - "startup" -> { - StartUpPage( - onToggleSidebar = navigationViewModel::toggleSidebar, - ) - } - - "simple-info-bubble" -> { - SimpleTextBubblePage( - onToggleSidebar = navigationViewModel::toggleSidebar, - ) - } - - "styled-info-bubble" -> { - StyledInfoBubblePage( - onToggleSidebar = navigationViewModel::toggleSidebar, - ) - } - - "rich-content-info-bubble" -> { - RichContentBubblePage( - onToggleSidebar = navigationViewModel::toggleSidebar, - ) - } - - "multiple-info-bubbles" -> { - MultipleBubblesPage( - onToggleSidebar = navigationViewModel::toggleSidebar, - ) - } - - "camera-restriction" -> { - CameraRestrictionMapPage( - onToggleSidebar = navigationViewModel::toggleSidebar, - ) - } - - "ui-settings" -> { - UISettingsMapPage( - onToggleSidebar = navigationViewModel::toggleSidebar, - ) - } - - "map-basic" -> { - StoreMapPage( - onToggleSidebar = navigationViewModel::toggleSidebar, - ) - } - - "map-design" -> { - MapDesignMapPage( - onToggleSidebar = navigationViewModel::toggleSidebar, - ) - } - - "map-visibleregion" -> { - VisibleRegionPage( - onToggleSidebar = navigationViewModel::toggleSidebar, - ) -// ZoomCalibrationPage( -// onToggleSidebar = navigationViewModel::toggleSidebar, -// ) - } - - "map-projected" -> { - ProjectedCoordinatesPage( - onToggleSidebar = navigationViewModel::toggleSidebar, - ) - } - - "map-camerasync" -> { - CameraSyncPage( - onToggleSidebar = navigationViewModel::toggleSidebar, - ) - } - - "map-flyTo" -> { - FlyToMapPage( - icons = flyToMapPageIcons, - onToggleSidebar = navigationViewModel::toggleSidebar, - ) - } - - "map-fitBounds" -> { - FitBoundsMapPage( - onToggleSidebar = navigationViewModel::toggleSidebar, - ) - } - - "marker-basic" -> { - MarkerBasicPage( - onToggleSidebar = navigationViewModel::toggleSidebar, - ) - } - - "marker-label-position" -> { - MarkerLabelPositionPage( - onToggleSidebar = navigationViewModel::toggleSidebar, - ) - } - - "marker-animation" -> { - AnimationMapPage( - onToggleSidebar = navigationViewModel::toggleSidebar, - ) - } - - "marker-postoffice" -> { - PostOfficePage( - postOfficeIcon = postOfficeIcon, - onToggleSidebar = navigationViewModel::toggleSidebar, - ) - } - - "marker-postoffice-cluster" -> { - PostOfficeClusterMapPage( - postOfficeIcon = postOfficeIcon, - onToggleSidebar = navigationViewModel::toggleSidebar, - ) - } - - "marker-streettree" -> { - StreetTreePage( - onToggleSidebar = navigationViewModel::toggleSidebar, - ) - } - - "circle" -> { - CircleMapPage( - onToggleSidebar = navigationViewModel::toggleSidebar, - ) - } - - "polyline" -> { - PolylineMapPage( - onToggleSidebar = navigationViewModel::toggleSidebar, - ) - } - - "polyline-click" -> { - PolylineClickMapPage( - onToggleSidebar = navigationViewModel::toggleSidebar, - ) - } - - "polygon" -> { - PolygonMapPage( - onToggleSidebar = navigationViewModel::toggleSidebar, - ) - } - - "polygon-click" -> { - PolygonClickPage( - onToggleSidebar = navigationViewModel::toggleSidebar, - ) - } - - "polygon-geodesic" -> { - PolygonGeodesicPage( - onToggleSidebar = navigationViewModel::toggleSidebar, - ) - } - - "polygon-hole" -> { - HolePolygonMapPage( - onToggleSidebar = navigationViewModel::toggleSidebar, - ) - } - - "polygons" -> { - PolygonsMapPage( - onToggleSidebar = navigationViewModel::toggleSidebar, - ) - } - - "boston-buildings" -> { - BostonBuildingsPage( - onToggleSidebar = navigationViewModel::toggleSidebar, - ) - } - - "antenna-horizons" -> { - AntennaHorizonsPage(onToggleSidebar = navigationViewModel::toggleSidebar) - } - - "boston-roads" -> { - BostonRoadsPage( - onToggleSidebar = navigationViewModel::toggleSidebar, - ) - } - - "groundImage" -> { - GroundImageMapPage( - groundImageResources = groundImageResources, - onToggleSidebar = navigationViewModel::toggleSidebar, - ) - } - - "raster-layer" -> { - RasterLayerMapPage( - onToggleSidebar = navigationViewModel::toggleSidebar, - ) - } - // 計測専用。サイドバーには出さない(RasterHeaderInstrumentedTest が使う)。 - "raster-header" -> { - RasterHeaderProbePage( - onToggleSidebar = navigationViewModel::toggleSidebar, - ) - } - - "heatmap-overlay" -> { - HeatmapLayerPage( - onToggleSidebar = navigationViewModel::toggleSidebar, - ) - } - - "vector-tile" -> { - VectorTilePage( - onToggleSidebar = navigationViewModel::toggleSidebar, - ) - } - - "vector-style" -> { - VectorStylePage( - onToggleSidebar = navigationViewModel::toggleSidebar, - ) - } - - "offline-map" -> { - OfflineMapPage( - onToggleSidebar = navigationViewModel::toggleSidebar, - ) - } - - "geojson-basic" -> { - BasicGeoJSONMapPage( - onToggleSidebar = navigationViewModel::toggleSidebar, - ) - } - - "geojson-layer" -> { - GeoJSONLayerMapPage( - onToggleSidebar = navigationViewModel::toggleSidebar, - ) - } - - "kml-layer" -> { - KMLMapPage( - onToggleSidebar = navigationViewModel::toggleSidebar, - ) - } - - "tilt-map" -> { - TiltMapPage( - onToggleSidebar = navigationViewModel::toggleSidebar, - ) - } - } - } - - // Overlay sidebar - Sidebar( - sections = sidebarSections, - selectedItemId = currentPage, - onItemClick = { item -> - navigationViewModel.navigateTo(item.id) - }, - isExpanded = isSidebarExpanded, - onToggleSidebar = navigationViewModel::toggleSidebar, - ) - } - } -} +package com.mapconductor.example + +import androidx.appcompat.content.res.AppCompatResources +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.remember +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.LocalContext +import androidx.core.content.ContextCompat +import com.mapconductor.core.marker.ImageIcon +import com.mapconductor.example.navigation.NavigationViewModel +import com.mapconductor.example.pages.circle.AntennaHorizonsPage +import com.mapconductor.example.pages.circle.CircleMapPage +import com.mapconductor.example.pages.geojson.basic.BasicGeoJSONMapPage +import com.mapconductor.example.pages.geojson.layer.GeoJSONLayerMapPage +import com.mapconductor.example.pages.groundimage.GroundImageMapPage +import com.mapconductor.example.pages.groundimage.GroundImageResources +import com.mapconductor.example.pages.heatmaplayer.HeatmapLayerPage +import com.mapconductor.example.pages.infobubble.MultipleBubblesPage +import com.mapconductor.example.pages.infobubble.RichContentBubblePage +import com.mapconductor.example.pages.infobubble.SimpleTextBubblePage +import com.mapconductor.example.pages.infobubble.StyledInfoBubblePage +import com.mapconductor.example.pages.kml.KMLMapPage +import com.mapconductor.example.pages.map.basic.StoreMapPage +import com.mapconductor.example.pages.map.camerarestriction.CameraRestrictionMapPage +import com.mapconductor.example.pages.map.camerasync.CameraSyncPage +import com.mapconductor.example.pages.map.design.MapDesignMapPage +import com.mapconductor.example.pages.map.fitbounds.FitBoundsMapPage +import com.mapconductor.example.pages.map.flyto.FlyToMapIcons +import com.mapconductor.example.pages.map.flyto.FlyToMapPage +import com.mapconductor.example.pages.map.projected.ProjectedCoordinatesPage +import com.mapconductor.example.pages.map.tilt.TiltMapPage +import com.mapconductor.example.pages.map.uisettings.UISettingsMapPage +import com.mapconductor.example.pages.map.visibleregion.VisibleRegionPage +import com.mapconductor.example.pages.marker.animation.AnimationMapPage +import com.mapconductor.example.pages.marker.icons.MarkerBasicPage +import com.mapconductor.example.pages.marker.labelposition.MarkerLabelPositionPage +import com.mapconductor.example.pages.marker.postoffice.PostOfficePage +import com.mapconductor.example.pages.marker.postofficecluster.MarkerClusterMapPage as PostOfficeClusterMapPage +import com.mapconductor.example.pages.marker.streettree.StreetTreePage +import com.mapconductor.example.pages.offlinemap.OfflineMapPage +import com.mapconductor.example.pages.polygon.basic.PolygonMapPage +import com.mapconductor.example.pages.polygon.boston.BostonBuildingsPage +import com.mapconductor.example.pages.polygon.click.PolygonClickPage +import com.mapconductor.example.pages.polygon.collection.PolygonsMapPage +import com.mapconductor.example.pages.polygon.geodesic.PolygonGeodesicPage +import com.mapconductor.example.pages.polygon.hole.HolePolygonMapPage +import com.mapconductor.example.pages.polyline.PolylineClickMapPage +import com.mapconductor.example.pages.polyline.PolylineMapPage +import com.mapconductor.example.pages.polyline.boston.BostonRoadsPage +import com.mapconductor.example.pages.rasterlayer.RasterHeaderProbePage +import com.mapconductor.example.pages.rasterlayer.RasterLayerMapPage +import com.mapconductor.example.pages.startup.StartUpPage +import com.mapconductor.example.pages.vectorstyle.VectorStylePage +import com.mapconductor.example.pages.vectortile.VectorTilePage +import com.mapconductor.example.ui.sidebar.Sidebar +import com.mapconductor.example.ui.sidebar.SidebarItem +import com.mapconductor.example.ui.sidebar.SidebarSection +import com.mapconductor.example.ui.theme.AppTheme + +@Composable +fun DemoAppScreen(initPage: String = "map") { + val navigationViewModel: NavigationViewModel = remember { NavigationViewModel(initPage) } + + val currentPage by navigationViewModel.currentPage + val isSidebarExpanded by navigationViewModel.isSidebarExpanded + val context = LocalContext.current + val flyToMapPageIcons = + remember { + FlyToMapIcons( + honolulu = ContextCompat.getDrawable(context, R.drawable.honolulu)!!, + tokyo = ContextCompat.getDrawable(context, R.drawable.tokyo)!!, + london = ContextCompat.getDrawable(context, R.drawable.london)!!, + newYork = ContextCompat.getDrawable(context, R.drawable.newyork)!!, + sydney = ContextCompat.getDrawable(context, R.drawable.sydney)!!, + ) + } + + val groundImageResources = + remember { + GroundImageResources( + image = ContextCompat.getDrawable(context, R.drawable.university_of_eswatini)!!, + ) + } + val postOfficeIcon = + remember { + val baseicon = AppCompatResources.getDrawable(context, R.drawable.postoffice)!! + ImageIcon( + image = baseicon, + scale = 0.5f, + ) + } + + val sidebarSections = + listOf( + SidebarSection( + title = "Map", + items = + listOf( + SidebarItem(id = "map-basic", title = "Map"), + SidebarItem(id = "tilt-map", title = "Tilt Map"), + SidebarItem(id = "ui-settings", title = "UI Settings"), + SidebarItem(id = "map-flyTo", title = "Move Camera"), + SidebarItem(id = "map-fitBounds", title = "Fit Bounds"), + SidebarItem(id = "map-design", title = "Map Design"), + SidebarItem(id = "map-visibleregion", title = "Visible Region"), + SidebarItem(id = "map-projected", title = "Projected Coordinates"), + SidebarItem(id = "map-camerasync", title = "Camera Sync"), + SidebarItem(id = "camera-restriction", title = "Camera Restriction"), + ), + ), + SidebarSection( + title = "Info Bubble", + items = + listOf( + SidebarItem(id = "simple-info-bubble", title = "Simple Text Bubble"), + SidebarItem(id = "styled-info-bubble", title = "Custom Styled Bubble"), + SidebarItem(id = "rich-content-info-bubble", title = "Rich Content Bubble"), + SidebarItem(id = "multiple-info-bubbles", title = "Multiple Bubbles"), + ), + ), + SidebarSection( + title = "Marker", + items = + listOf( + SidebarItem(id = "marker-basic", title = "Marker"), + SidebarItem(id = "marker-label-position", title = "Marker Label Position"), + SidebarItem(id = "marker-animation", title = "Marker Animation"), + SidebarItem(id = "marker-postoffice", title = "Bunch of Markers"), + SidebarItem(id = "marker-postoffice-cluster", title = "Marker Clustering"), + SidebarItem(id = "marker-streettree", title = "Street Trees"), + ), + ), + SidebarSection( + title = "Circle", + items = + listOf( + SidebarItem(id = "circle", title = "Circle"), + SidebarItem(id = "antenna-horizons", title = "US Antenna Horizons"), + ), + ), + SidebarSection( + title = "Ground Image", + items = listOf(SidebarItem(id = "groundImage", title = "Ground Image")), + ), + SidebarSection( + title = "Polyline", + items = + listOf( + SidebarItem(id = "polyline", title = "Polyline"), + SidebarItem(id = "polyline-click", title = "Polyline Click"), + SidebarItem(id = "boston-roads", title = "Boston Roads"), + ), + ), + SidebarSection( + title = "Polygon", + items = + listOf( + SidebarItem(id = "polygon", title = "Polygon"), + SidebarItem(id = "polygon-click", title = "Polygon Click"), + SidebarItem(id = "polygon-geodesic", title = "Geodesic Polygons"), + SidebarItem(id = "polygon-hole", title = "Hole Polygon"), + SidebarItem(id = "polygons", title = "Polygons"), + SidebarItem(id = "boston-buildings", title = "Boston Buildings"), + ), + ), + SidebarSection( + title = "Raster Layer", + items = listOf(SidebarItem(id = "raster-layer", title = "Raster Layer")), + ), + SidebarSection( + title = "Heatmap Layer", + items = listOf(SidebarItem(id = "heatmap-overlay", title = "Heatmap Overlay")), + ), + SidebarSection( + title = "Vector Tile Layer", + items = + listOf( + SidebarItem(id = "vector-tile", title = "MapLibre Style"), + SidebarItem(id = "vector-style", title = "Style Adjustments"), + SidebarItem(id = "offline-map", title = "Offline Map"), + ), + ), + SidebarSection( + title = "GeoJSON", + items = + listOf( + SidebarItem(id = "geojson-basic", title = "Basic GeoJSON"), + SidebarItem(id = "geojson-layer", title = "GeoJSON Layer"), + ), + ), + SidebarSection( + title = "KML", + items = listOf(SidebarItem(id = "kml-layer", title = "KML Layer")), + ), + ) + + AppTheme { + Box(modifier = Modifier.fillMaxSize()) { + // Main content + Box(modifier = Modifier.fillMaxSize()) { + when (currentPage) { + "startup" -> { + StartUpPage( + onToggleSidebar = navigationViewModel::toggleSidebar, + ) + } + + "simple-info-bubble" -> { + SimpleTextBubblePage( + onToggleSidebar = navigationViewModel::toggleSidebar, + ) + } + + "styled-info-bubble" -> { + StyledInfoBubblePage( + onToggleSidebar = navigationViewModel::toggleSidebar, + ) + } + + "rich-content-info-bubble" -> { + RichContentBubblePage( + onToggleSidebar = navigationViewModel::toggleSidebar, + ) + } + + "multiple-info-bubbles" -> { + MultipleBubblesPage( + onToggleSidebar = navigationViewModel::toggleSidebar, + ) + } + + "camera-restriction" -> { + CameraRestrictionMapPage( + onToggleSidebar = navigationViewModel::toggleSidebar, + ) + } + + "ui-settings" -> { + UISettingsMapPage( + onToggleSidebar = navigationViewModel::toggleSidebar, + ) + } + + "map-basic" -> { + StoreMapPage( + onToggleSidebar = navigationViewModel::toggleSidebar, + ) + } + + "map-design" -> { + MapDesignMapPage( + onToggleSidebar = navigationViewModel::toggleSidebar, + ) + } + + "map-visibleregion" -> { + VisibleRegionPage( + onToggleSidebar = navigationViewModel::toggleSidebar, + ) +// ZoomCalibrationPage( +// onToggleSidebar = navigationViewModel::toggleSidebar, +// ) + } + + "map-projected" -> { + ProjectedCoordinatesPage( + onToggleSidebar = navigationViewModel::toggleSidebar, + ) + } + + "map-camerasync" -> { + CameraSyncPage( + onToggleSidebar = navigationViewModel::toggleSidebar, + ) + } + + "map-flyTo" -> { + FlyToMapPage( + icons = flyToMapPageIcons, + onToggleSidebar = navigationViewModel::toggleSidebar, + ) + } + + "map-fitBounds" -> { + FitBoundsMapPage( + onToggleSidebar = navigationViewModel::toggleSidebar, + ) + } + + "marker-basic" -> { + MarkerBasicPage( + onToggleSidebar = navigationViewModel::toggleSidebar, + ) + } + + "marker-label-position" -> { + MarkerLabelPositionPage( + onToggleSidebar = navigationViewModel::toggleSidebar, + ) + } + + "marker-animation" -> { + AnimationMapPage( + onToggleSidebar = navigationViewModel::toggleSidebar, + ) + } + + "marker-postoffice" -> { + PostOfficePage( + postOfficeIcon = postOfficeIcon, + onToggleSidebar = navigationViewModel::toggleSidebar, + ) + } + + "marker-postoffice-cluster" -> { + PostOfficeClusterMapPage( + postOfficeIcon = postOfficeIcon, + onToggleSidebar = navigationViewModel::toggleSidebar, + ) + } + + "marker-streettree" -> { + StreetTreePage( + onToggleSidebar = navigationViewModel::toggleSidebar, + ) + } + + "circle" -> { + CircleMapPage( + onToggleSidebar = navigationViewModel::toggleSidebar, + ) + } + + "polyline" -> { + PolylineMapPage( + onToggleSidebar = navigationViewModel::toggleSidebar, + ) + } + + "polyline-click" -> { + PolylineClickMapPage( + onToggleSidebar = navigationViewModel::toggleSidebar, + ) + } + + "polygon" -> { + PolygonMapPage( + onToggleSidebar = navigationViewModel::toggleSidebar, + ) + } + + "polygon-click" -> { + PolygonClickPage( + onToggleSidebar = navigationViewModel::toggleSidebar, + ) + } + + "polygon-geodesic" -> { + PolygonGeodesicPage( + onToggleSidebar = navigationViewModel::toggleSidebar, + ) + } + + "polygon-hole" -> { + HolePolygonMapPage( + onToggleSidebar = navigationViewModel::toggleSidebar, + ) + } + + "polygons" -> { + PolygonsMapPage( + onToggleSidebar = navigationViewModel::toggleSidebar, + ) + } + + "boston-buildings" -> { + BostonBuildingsPage( + onToggleSidebar = navigationViewModel::toggleSidebar, + ) + } + + "antenna-horizons" -> { + AntennaHorizonsPage(onToggleSidebar = navigationViewModel::toggleSidebar) + } + + "boston-roads" -> { + BostonRoadsPage( + onToggleSidebar = navigationViewModel::toggleSidebar, + ) + } + + "groundImage" -> { + GroundImageMapPage( + groundImageResources = groundImageResources, + onToggleSidebar = navigationViewModel::toggleSidebar, + ) + } + + "raster-layer" -> { + RasterLayerMapPage( + onToggleSidebar = navigationViewModel::toggleSidebar, + ) + } + // 計測専用。サイドバーには出さない(RasterHeaderInstrumentedTest が使う)。 + "raster-header" -> { + RasterHeaderProbePage( + onToggleSidebar = navigationViewModel::toggleSidebar, + ) + } + + "heatmap-overlay" -> { + HeatmapLayerPage( + onToggleSidebar = navigationViewModel::toggleSidebar, + ) + } + + "vector-tile" -> { + VectorTilePage( + onToggleSidebar = navigationViewModel::toggleSidebar, + ) + } + + "vector-style" -> { + VectorStylePage( + onToggleSidebar = navigationViewModel::toggleSidebar, + ) + } + + "offline-map" -> { + OfflineMapPage( + onToggleSidebar = navigationViewModel::toggleSidebar, + ) + } + + "geojson-basic" -> { + BasicGeoJSONMapPage( + onToggleSidebar = navigationViewModel::toggleSidebar, + ) + } + + "geojson-layer" -> { + GeoJSONLayerMapPage( + onToggleSidebar = navigationViewModel::toggleSidebar, + ) + } + + "kml-layer" -> { + KMLMapPage( + onToggleSidebar = navigationViewModel::toggleSidebar, + ) + } + + "tilt-map" -> { + TiltMapPage( + onToggleSidebar = navigationViewModel::toggleSidebar, + ) + } + } + } + + // Overlay sidebar + Sidebar( + sections = sidebarSections, + selectedItemId = currentPage, + onItemClick = { item -> + navigationViewModel.navigateTo(item.id) + }, + isExpanded = isSidebarExpanded, + onToggleSidebar = navigationViewModel::toggleSidebar, + ) + } + } +} diff --git a/example-app/src/main/java/com/mapconductor/example/StarCircleView.kt b/example-app/src/main/java/com/mapconductor/example/StarCircleView.kt index 1d4b48d9..20ea761a 100644 --- a/example-app/src/main/java/com/mapconductor/example/StarCircleView.kt +++ b/example-app/src/main/java/com/mapconductor/example/StarCircleView.kt @@ -1,69 +1,69 @@ -package com.mapconductor.example - -import android.content.Context -import android.graphics.Canvas -import android.graphics.Color -import android.graphics.Paint -import android.graphics.Path -import android.util.AttributeSet -import android.view.View - -class StarCircleView -@JvmOverloads -constructor( - context: Context, - attrs: AttributeSet? = null, - defStyleAttr: Int = 0, -) : View(context, attrs, defStyleAttr) { - private val paint = Paint(Paint.ANTI_ALIAS_FLAG) - - override fun onDraw(canvas: Canvas) { - super.onDraw(canvas) - canvas.save() - canvas.scale(10f, 10f) - - // 背景:黄色い円 (#FFD400), 半径12px, 中心(14, 14) - paint.color = Color.parseColor("#FFD400") - paint.style = Paint.Style.FILL - canvas.drawCircle(14f, 14f, 12f, paint) - - // 五芒星座標(SVGの polygon → scale(0.91), translate(1.26, 0.26) を適用済み) - val starPath = Path() - - // スケーリングと平行移動を反映した点列(直接数値を適用) - val points = - arrayOf( - Pair(14f, 4f), - Pair(16.94f, 11.4f), - Pair(24.9f, 11.4f), - Pair(18.48f, 16.1f), - Pair(21.42f, 23.5f), - Pair(14f, 18.8f), - Pair(6.58f, 23.5f), - Pair(9.52f, 16.1f), - Pair(3.1f, 11.4f), - Pair(11.06f, 11.4f), - ) - - // 変換処理:scale(0.91) → x*0.91, y*0.91 / translate(1.26, 0.26) - val transformed = - points.map { (x, y) -> - val scaledX = x * 0.91f + 1.26f - val scaledY = y * 0.91f + 0.26f - Pair(scaledX, scaledY) - } - - // Path構築(moveTo → lineTo) - starPath.moveTo(transformed[0].first, transformed[0].second) - for (i in 1 until transformed.size) { - starPath.lineTo(transformed[i].first, transformed[i].second) - } - starPath.close() - - // 星を白で塗りつぶし - paint.color = Color.WHITE - canvas.drawPath(starPath, paint) - - canvas.restore() - } -} +package com.mapconductor.example + +import android.content.Context +import android.graphics.Canvas +import android.graphics.Color +import android.graphics.Paint +import android.graphics.Path +import android.util.AttributeSet +import android.view.View + +class StarCircleView + @JvmOverloads + constructor( + context: Context, + attrs: AttributeSet? = null, + defStyleAttr: Int = 0, + ) : View(context, attrs, defStyleAttr) { + private val paint = Paint(Paint.ANTI_ALIAS_FLAG) + + override fun onDraw(canvas: Canvas) { + super.onDraw(canvas) + canvas.save() + canvas.scale(10f, 10f) + + // 背景:黄色い円 (#FFD400), 半径12px, 中心(14, 14) + paint.color = Color.parseColor("#FFD400") + paint.style = Paint.Style.FILL + canvas.drawCircle(14f, 14f, 12f, paint) + + // 五芒星座標(SVGの polygon → scale(0.91), translate(1.26, 0.26) を適用済み) + val starPath = Path() + + // スケーリングと平行移動を反映した点列(直接数値を適用) + val points = + arrayOf( + Pair(14f, 4f), + Pair(16.94f, 11.4f), + Pair(24.9f, 11.4f), + Pair(18.48f, 16.1f), + Pair(21.42f, 23.5f), + Pair(14f, 18.8f), + Pair(6.58f, 23.5f), + Pair(9.52f, 16.1f), + Pair(3.1f, 11.4f), + Pair(11.06f, 11.4f), + ) + + // 変換処理:scale(0.91) → x*0.91, y*0.91 / translate(1.26, 0.26) + val transformed = + points.map { (x, y) -> + val scaledX = x * 0.91f + 1.26f + val scaledY = y * 0.91f + 0.26f + Pair(scaledX, scaledY) + } + + // Path構築(moveTo → lineTo) + starPath.moveTo(transformed[0].first, transformed[0].second) + for (i in 1 until transformed.size) { + starPath.lineTo(transformed[i].first, transformed[i].second) + } + starPath.close() + + // 星を白で塗りつぶし + paint.color = Color.WHITE + canvas.drawPath(starPath, paint) + + canvas.restore() + } + } diff --git a/example-app/src/main/java/com/mapconductor/example/pages/circle/AntennaHorizonsPage.kt b/example-app/src/main/java/com/mapconductor/example/pages/circle/AntennaHorizonsPage.kt index 662993cf..794e951a 100644 --- a/example-app/src/main/java/com/mapconductor/example/pages/circle/AntennaHorizonsPage.kt +++ b/example-app/src/main/java/com/mapconductor/example/pages/circle/AntennaHorizonsPage.kt @@ -1,10 +1,22 @@ package com.mapconductor.example.pages.circle import androidx.compose.foundation.background -import androidx.compose.foundation.layout.* +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.widthIn import androidx.compose.foundation.text.ClickableText -import androidx.compose.material3.* -import androidx.compose.runtime.* +import androidx.compose.material3.Checkbox +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.key +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalContext @@ -33,12 +45,14 @@ private data class Antenna( val lon: Double, val radius: Double, val registration: Long, - val carrier: Int + val carrier: Int, ) // Keep source records packed. CircleState.extra resolves a row on demand; // retaining another 723,800 JVM record objects would duplicate the source data. -private class AntennaTable(bytes: ByteArray) : AbstractList() { +private class AntennaTable( + bytes: ByteArray, +) : AbstractList() { private val buffer = ByteBuffer.wrap(bytes).asReadOnlyBuffer().order(ByteOrder.LITTLE_ENDIAN) override val size: Int val carrierCounts = IntArray(4) @@ -49,7 +63,15 @@ private class AntennaTable(bytes: ByteArray) : AbstractList() { require(size >= 0 && bytes.size.toLong() == 8L + size * 16L) for (index in 0 until size) { val row = get(index) - require(row.lat.isFinite() && row.lat in -90.0..90.0 && row.lon.isFinite() && row.lon in -180.0..180.0 && row.radius > 0 && row.radius <= 100000 && row.carrier in 0..3) + require( + row.lat.isFinite() && + row.lat in -90.0..90.0 && + row.lon.isFinite() && + row.lon in -180.0..180.0 && + row.radius > 0 && + row.radius <= 100000 && + row.carrier in 0..3, + ) carrierCounts[row.carrier]++ } } @@ -59,7 +81,7 @@ private class AntennaTable(bytes: ByteArray) : AbstractList() { val p = 8 + index * 16 return Antenna( buffer.getInt(p) / 100000.0, buffer.getInt(p + 4) / 100000.0, - buffer.getFloat(p + 8).toDouble(), index.toLong(), buffer.getInt(p + 12) / 1000 + buffer.getFloat(p + 8).toDouble(), index.toLong(), buffer.getInt(p + 12) / 1000, ) } @@ -84,59 +106,69 @@ fun AntennaHorizonsPage( var adding by remember { mutableStateOf?>(null) } LaunchedEffect(Unit) { try { - rows = withContext(Dispatchers.IO) { - val bytes = context.assets.open("antennas/us-antennas.bin").use { it.readBytes() } - AntennaTable(bytes) - } + rows = + withContext(Dispatchers.IO) { + val bytes = context.assets.open("antennas/us-antennas.bin").use { it.readBytes() } + AntennaTable(bytes) + } } catch (e: Exception) { error = e.message } } LaunchedEffect(rows) { tap = null - allStates = withContext(Dispatchers.Default) { - val onCellClick: com.mapconductor.core.circle.OnCircleEventHandler = { event -> - tap = (event.state.extra as? String)?.removePrefix("asr-")?.toIntOrNull()?.let { rows.getOrNull(it) } - } - rows.map { a -> - val color = carrierColors[a.carrier] - val id = "asr-${a.registration}" - CircleState( - center = GeoPoint(a.lat, a.lon), - radiusMeters = 500.0, - id = id, - geodesic = true, - zIndex = a.registration.toInt(), - strokeWidth = 0.5.dp, - strokeColor = color.copy(alpha = 0.35f), - fillColor = color.copy(alpha = 0.65f), - extra = id, - onClick = onCellClick - ) + allStates = + withContext(Dispatchers.Default) { + val onCellClick: com.mapconductor.core.circle.OnCircleEventHandler = { event -> + tap = + (event.state.extra as? String)?.removePrefix("asr-")?.toIntOrNull()?.let { rows.getOrNull(it) } + } + rows.map { a -> + val color = carrierColors[a.carrier] + val id = "asr-${a.registration}" + CircleState( + center = GeoPoint(a.lat, a.lon), + radiusMeters = 500.0, + id = id, + geodesic = true, + zIndex = a.registration.toInt(), + strokeWidth = 0.5.dp, + strokeColor = color.copy(alpha = 0.35f), + fillColor = color.copy(alpha = 0.65f), + extra = id, + onClick = onCellClick, + ) + } } - } } LaunchedEffect(allStates, carriers) { tap = null - states = withContext(Dispatchers.Default) { - if (carriers.size == carrierNames.size) allStates - else if (carriers.isEmpty()) emptyList() - else allStates.filterIndexed { index, _ -> - ((rows as? AntennaTable)?.carrierAt(index) ?: rows[index].carrier) in carriers + states = + withContext(Dispatchers.Default) { + if (carriers.size == carrierNames.size) { + allStates + } else if (carriers.isEmpty()) { + emptyList() + } else { + allStates.filterIndexed { index, _ -> + ((rows as? AntennaTable)?.carrierAt(index) ?: rows[index].carrier) in carriers + } + } } - } - } - val camera = remember(alaska) { - MapCameraPosition( - position = if (alaska) GeoPoint(64.0, -150.0) else GeoPoint(39.0, -98.0), - zoom = if (alaska) 5.0 else 4.0 - ) } + val camera = + remember(alaska) { + MapCameraPosition( + position = if (alaska) GeoPoint(64.0, -150.0) else GeoPoint(39.0, -98.0), + zoom = if (alaska) 5.0 else 4.0, + ) + } key(alaska) { DemoMapPageScaffold( menuItems = DefaultMapViewItems(camera), onToggleSidebar = onToggleSidebar, - onMapViewStateChanged = { mapState = it }) { padding -> + onMapViewStateChanged = { mapState = it }, + ) { padding -> mapState?.let { state -> MapViewContainer(state = state, modifier = modifier.padding(padding), onMapClick = { tap = null }) { Circles( @@ -147,10 +179,11 @@ fun AntennaHorizonsPage( ) tap?.let { a -> InfoBubble( - position = GeoPoint( - a.lat, - a.lon - ) + position = + GeoPoint( + a.lat, + a.lon, + ), ) { Text("${carrierNames[a.carrier]}\nCell position · Display radius: 500 m") } } } @@ -160,11 +193,12 @@ fun AntennaHorizonsPage( .padding(top = padding.calculateTopPadding() + 12.dp, start = 12.dp) .widthIn(max = 350.dp) .background(MaterialTheme.colorScheme.surface) - .padding(12.dp) + .padding(12.dp), ) { Text("US cell positions (MCC 310–314)", style = MaterialTheme.typography.titleMedium) Text( - error ?: if (rows.isEmpty()) "Loading OpenCellID data…" else "${states.size} / ${rows.size} circles" + error + ?: if (rows.isEmpty()) "Loading OpenCellID data…" else "${states.size} / ${rows.size} circles", ) adding?.let { (added, total) -> Text("Adding to the map… $added / $total") } TextButton(onClick = { alaska = !alaska }) { Text(if (alaska) "US overview" else "Alaska") } @@ -174,30 +208,44 @@ fun AntennaHorizonsPage( index in carriers, { checked -> carriers = if (checked) carriers + index else carriers - index - }); Text("$name (${(rows as? AntennaTable)?.carrierCounts?.get(index) ?: 0})") + }, + ) + Text("$name (${(rows as? AntennaTable)?.carrierCounts?.get(index) ?: 0})") } } Text( "Cell positions shown as 500 m radius circles; not signal coverage. Showing all cells for the selected carriers. MCC 310–314; not a complete tower inventory.", - style = MaterialTheme.typography.bodySmall + style = MaterialTheme.typography.bodySmall, ) ClickableText( - text = buildAnnotatedString { - append("Cell tower data from ") - pushStringAnnotation("URL", "https://opencellid.org"); append("OpenCellID"); pop() - append(" · ") - pushStringAnnotation( - "URL", - "https://creativecommons.org/licenses/by-sa/4.0/" - ); append("CC BY-SA 4.0"); pop() - }, + text = + buildAnnotatedString { + append("Cell tower data from ") + pushStringAnnotation("URL", "https://opencellid.org") + append("OpenCellID") + pop() + append(" · ") + pushStringAnnotation( + "URL", + "https://creativecommons.org/licenses/by-sa/4.0/", + ) + append("CC BY-SA 4.0") + pop() + }, style = MaterialTheme.typography.bodySmall.copy(color = MaterialTheme.colorScheme.primary), onClick = { offset -> // Link annotations keep both source and license independently tappable. val url = - if (offset < 30) "https://opencellid.org" else "https://creativecommons.org/licenses/by-sa/4.0/" + if (offset < + 30 + ) { + "https://opencellid.org" + } else { + "https://creativecommons.org/licenses/by-sa/4.0/" + } uriHandler.openUri(url) - }) + }, + ) } } } diff --git a/example-app/src/main/java/com/mapconductor/example/pages/circle/CirclePageViewModel.kt b/example-app/src/main/java/com/mapconductor/example/pages/circle/CirclePageViewModel.kt index e7d9a4ea..7f1d0164 100644 --- a/example-app/src/main/java/com/mapconductor/example/pages/circle/CirclePageViewModel.kt +++ b/example-app/src/main/java/com/mapconductor/example/pages/circle/CirclePageViewModel.kt @@ -236,5 +236,4 @@ class CirclePageViewModel( override fun removeToast(toastMessage: ToastMessage) { this._messages.value = this._messages.value.filter { it != toastMessage } } - } diff --git a/example-app/src/main/java/com/mapconductor/example/pages/groundimage/GroundImageMapPageViewModel.kt b/example-app/src/main/java/com/mapconductor/example/pages/groundimage/GroundImageMapPageViewModel.kt index 3999ad35..5023791c 100644 --- a/example-app/src/main/java/com/mapconductor/example/pages/groundimage/GroundImageMapPageViewModel.kt +++ b/example-app/src/main/java/com/mapconductor/example/pages/groundimage/GroundImageMapPageViewModel.kt @@ -1,256 +1,255 @@ -package com.mapconductor.example.pages.groundimage - -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.setValue -import androidx.compose.ui.graphics.Color -import androidx.compose.ui.unit.dp -import androidx.lifecycle.ViewModel -import com.mapconductor.core.features.GeoPoint -import com.mapconductor.core.features.GeoRectBounds -import com.mapconductor.core.groundimage.GroundImageEvent -import com.mapconductor.core.groundimage.GroundImageState -import com.mapconductor.core.map.MapCameraPosition -import com.mapconductor.core.map.MapViewStateInterface -import com.mapconductor.core.marker.DefaultMarkerIcon -import com.mapconductor.core.marker.MarkerState -import com.mapconductor.core.polyline.PolylineState -import com.mapconductor.example.toast.ToastMessage -import android.graphics.drawable.Drawable -import kotlinx.coroutines.flow.MutableStateFlow -import kotlinx.coroutines.flow.StateFlow -import kotlinx.coroutines.flow.asStateFlow - -interface GroundImageMapPageViewModelInterface { - val initCameraPosition: MapCameraPosition - val mapViewState: StateFlow?> - val messages: StateFlow> - - val markers: List - val framePolyline: PolylineState - val imageResources: GroundImageResources - val image: Drawable - - /** 画像を Drawable でなく URL で渡す(SDK が読む)。 */ - var useImageUrl: Boolean - var opacity: Float - val groundImageState: GroundImageState - - fun onMapViewChanged(state: MapViewStateInterface<*>) - - fun onGroundImageClick(clicked: GroundImageEvent) - - fun onMarkerDrag(dragged: MarkerState) - - fun showToast(text: String) - - fun removeToast(toastMessage: ToastMessage) -} - -/** `useImageUrl` のときに貼る画像。res/drawable/university_of_eswatini.png と同じもの。 */ -private const val GROUND_IMAGE_URL = - "https://raw.githubusercontent.com/MapConductor/android-sdk/develop/example-app/src/main/res/drawable/university_of_eswatini.png" - -class GroundImageMapPageViewModel( - override val imageResources: GroundImageResources, -) : ViewModel(), - GroundImageMapPageViewModelInterface { - override val initCameraPosition = - MapCameraPosition( - // Drone imagery over the University of Eswatini campus. Same content as - // react-sdk/examples/basic and the iOS sample. - position = - GeoPoint.fromLatLong( - latitude = -26.479235, - longitude = 31.306239, - ), - zoom = 15.0, - bearing = 0.0, - tilt = 0.0, - paddings = null, - ) - - private val _mapViewState = MutableStateFlow?>(null) - override val mapViewState: StateFlow?> = _mapViewState.asStateFlow() - - override fun onMapViewChanged(state: MapViewStateInterface<*>) { - mapViewState.value?.cameraPosition?.let { - state.moveCameraTo(it) - } - this._mapViewState.value = state - } - - private val _messages: MutableStateFlow> = MutableStateFlow(emptyList()) - override val messages: StateFlow> = _messages.asStateFlow() - - private var southWestPosition by mutableStateOf( - GeoPoint( - latitude = -26.484901389754125, - longitude = 31.2995982170105, - ), - ) - - private var northEastPosition by mutableStateOf( - GeoPoint( - latitude = -26.473569450536356, - longitude = 31.31288051605225, - ), - ) - - private fun calculateMarkerLabels(): Pair { - val swLat = southWestPosition.latitude - val swLng = southWestPosition.longitude - val neLat = northEastPosition.latitude - val neLng = northEastPosition.longitude - - val southWestLabel = - when { - swLat <= neLat && swLng <= neLng -> "SW" // Normal - swLat <= neLat && swLng > neLng -> "SE" // East-West flipped - swLat > neLat && swLng <= neLng -> "NW" // North-South flipped - else -> "NE" // Both flipped - } - - val northEastLabel = - when { - neLat >= swLat && neLng >= swLng -> "NE" // Normal - neLat >= swLat && neLng < swLng -> "NW" // East-West flipped - neLat < swLat && neLng >= swLng -> "SE" // North-South flipped - else -> "SW" // Both flipped - } - - return Pair(southWestLabel, northEastLabel) - } - - override val markers: List - get() { - val (swLabel, neLabel) = calculateMarkerLabels() - return listOf( - MarkerState( - id = "south_west", - position = southWestPosition, - icon = - DefaultMarkerIcon( - fillColor = Color.Blue, - strokeColor = Color.White, - label = swLabel, - labelTextColor = Color.White, - ), - draggable = true, - onDrag = this::onMarkerDrag, - ), - MarkerState( - id = "north_east", - position = northEastPosition, - icon = - DefaultMarkerIcon( - fillColor = Color.Red, - strokeColor = Color.White, - label = neLabel, - labelTextColor = Color.White, - ), - draggable = true, - onDrag = this::onMarkerDrag, - ), - ) - } - - /** - * グラウンドイメージの外周をなぞる矩形。 - * - * NE → NW → SW → SE → NE の順に 5 点で閉じる。SW / NE の 2 点だけでは - * **画像がどこまで載っているのかが見えない**ので、ドラッグで範囲を変えたときの - * 手応えを出すために引いている。react-sdk の `GroundImagePage.tsx` と同じ構成。 - * - * `points` を差し替えるだけで再描画されるので、インスタンスは作り直さない - * (作り直すとドラッグ中に id が変わってちらつく)。 - */ - override val framePolyline: PolylineState = - PolylineState( - id = "groundimage-frame", - points = framePoints(southWestPosition, northEastPosition), - strokeColor = Color.White, - strokeWidth = 3.dp, - clickable = false, - ) - - override var opacity by mutableStateOf(1.0f) - - override var image by mutableStateOf(imageResources.image) - - override var useImageUrl by mutableStateOf(false) - - private var bounds by mutableStateOf( - GeoRectBounds( - southWest = southWestPosition, - northEast = northEastPosition, - ), - ) - - override val groundImageState - get() = - if (useImageUrl) { - GroundImageState( - id = "groundImage", - bounds = bounds, - imageUrl = GROUND_IMAGE_URL, - opacity = opacity, - onClick = this::onGroundImageClick, - ) - } else { - GroundImageState( - id = "groundImage", - bounds = bounds, - image = image, - opacity = opacity, - onClick = this::onGroundImageClick, - ) - } - - override fun onGroundImageClick(clicked: GroundImageEvent) { - showToast("Ground image clicked.") - } - - override fun onMarkerDrag(dragged: MarkerState) { - // Update the internal position based on which marker was dragged - when (dragged.id) { - "south_west" -> southWestPosition = GeoPoint.from(dragged.position) - "north_east" -> northEastPosition = GeoPoint.from(dragged.position) - } - - // Update bounds using the new positions - bounds = - GeoRectBounds().also { - it.extend(markers[0].position) - it.extend(markers[1].position) - } - - framePolyline.points = framePoints(southWestPosition, northEastPosition) - } - - override fun showToast(text: String) { - this._messages.value = this._messages.value + ToastMessage(text = text) - } - - override fun removeToast(toastMessage: ToastMessage) { - this._messages.value = this._messages.value.filter { it != toastMessage } - } - -} - -/** - * 2 つの角から矩形の 4 辺をなぞる点列を作る。NE → NW → SW → SE → NE で閉じる。 - * - * ドラッグで南北・東西が反転しても、常に 2 点を対角とする矩形になる。 - */ -private fun framePoints( - southWest: GeoPoint, - northEast: GeoPoint, -): List = - listOf( - northEast, - GeoPoint(latitude = northEast.latitude, longitude = southWest.longitude), - southWest, - GeoPoint(latitude = southWest.latitude, longitude = northEast.longitude), - northEast, - ) +package com.mapconductor.example.pages.groundimage + +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.unit.dp +import androidx.lifecycle.ViewModel +import com.mapconductor.core.features.GeoPoint +import com.mapconductor.core.features.GeoRectBounds +import com.mapconductor.core.groundimage.GroundImageEvent +import com.mapconductor.core.groundimage.GroundImageState +import com.mapconductor.core.map.MapCameraPosition +import com.mapconductor.core.map.MapViewStateInterface +import com.mapconductor.core.marker.DefaultMarkerIcon +import com.mapconductor.core.marker.MarkerState +import com.mapconductor.core.polyline.PolylineState +import com.mapconductor.example.toast.ToastMessage +import android.graphics.drawable.Drawable +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow + +interface GroundImageMapPageViewModelInterface { + val initCameraPosition: MapCameraPosition + val mapViewState: StateFlow?> + val messages: StateFlow> + + val markers: List + val framePolyline: PolylineState + val imageResources: GroundImageResources + val image: Drawable + + /** 画像を Drawable でなく URL で渡す(SDK が読む)。 */ + var useImageUrl: Boolean + var opacity: Float + val groundImageState: GroundImageState + + fun onMapViewChanged(state: MapViewStateInterface<*>) + + fun onGroundImageClick(clicked: GroundImageEvent) + + fun onMarkerDrag(dragged: MarkerState) + + fun showToast(text: String) + + fun removeToast(toastMessage: ToastMessage) +} + +/** `useImageUrl` のときに貼る画像。res/drawable/university_of_eswatini.png と同じもの。 */ +private const val GROUND_IMAGE_URL = + "https://raw.githubusercontent.com/MapConductor/android-sdk/develop/example-app/src/main/res/drawable/university_of_eswatini.png" + +class GroundImageMapPageViewModel( + override val imageResources: GroundImageResources, +) : ViewModel(), + GroundImageMapPageViewModelInterface { + override val initCameraPosition = + MapCameraPosition( + // Drone imagery over the University of Eswatini campus. Same content as + // react-sdk/examples/basic and the iOS sample. + position = + GeoPoint.fromLatLong( + latitude = -26.479235, + longitude = 31.306239, + ), + zoom = 15.0, + bearing = 0.0, + tilt = 0.0, + paddings = null, + ) + + private val _mapViewState = MutableStateFlow?>(null) + override val mapViewState: StateFlow?> = _mapViewState.asStateFlow() + + override fun onMapViewChanged(state: MapViewStateInterface<*>) { + mapViewState.value?.cameraPosition?.let { + state.moveCameraTo(it) + } + this._mapViewState.value = state + } + + private val _messages: MutableStateFlow> = MutableStateFlow(emptyList()) + override val messages: StateFlow> = _messages.asStateFlow() + + private var southWestPosition by mutableStateOf( + GeoPoint( + latitude = -26.484901389754125, + longitude = 31.2995982170105, + ), + ) + + private var northEastPosition by mutableStateOf( + GeoPoint( + latitude = -26.473569450536356, + longitude = 31.31288051605225, + ), + ) + + private fun calculateMarkerLabels(): Pair { + val swLat = southWestPosition.latitude + val swLng = southWestPosition.longitude + val neLat = northEastPosition.latitude + val neLng = northEastPosition.longitude + + val southWestLabel = + when { + swLat <= neLat && swLng <= neLng -> "SW" // Normal + swLat <= neLat && swLng > neLng -> "SE" // East-West flipped + swLat > neLat && swLng <= neLng -> "NW" // North-South flipped + else -> "NE" // Both flipped + } + + val northEastLabel = + when { + neLat >= swLat && neLng >= swLng -> "NE" // Normal + neLat >= swLat && neLng < swLng -> "NW" // East-West flipped + neLat < swLat && neLng >= swLng -> "SE" // North-South flipped + else -> "SW" // Both flipped + } + + return Pair(southWestLabel, northEastLabel) + } + + override val markers: List + get() { + val (swLabel, neLabel) = calculateMarkerLabels() + return listOf( + MarkerState( + id = "south_west", + position = southWestPosition, + icon = + DefaultMarkerIcon( + fillColor = Color.Blue, + strokeColor = Color.White, + label = swLabel, + labelTextColor = Color.White, + ), + draggable = true, + onDrag = this::onMarkerDrag, + ), + MarkerState( + id = "north_east", + position = northEastPosition, + icon = + DefaultMarkerIcon( + fillColor = Color.Red, + strokeColor = Color.White, + label = neLabel, + labelTextColor = Color.White, + ), + draggable = true, + onDrag = this::onMarkerDrag, + ), + ) + } + + /** + * グラウンドイメージの外周をなぞる矩形。 + * + * NE → NW → SW → SE → NE の順に 5 点で閉じる。SW / NE の 2 点だけでは + * **画像がどこまで載っているのかが見えない**ので、ドラッグで範囲を変えたときの + * 手応えを出すために引いている。react-sdk の `GroundImagePage.tsx` と同じ構成。 + * + * `points` を差し替えるだけで再描画されるので、インスタンスは作り直さない + * (作り直すとドラッグ中に id が変わってちらつく)。 + */ + override val framePolyline: PolylineState = + PolylineState( + id = "groundimage-frame", + points = framePoints(southWestPosition, northEastPosition), + strokeColor = Color.White, + strokeWidth = 3.dp, + clickable = false, + ) + + override var opacity by mutableStateOf(1.0f) + + override var image by mutableStateOf(imageResources.image) + + override var useImageUrl by mutableStateOf(false) + + private var bounds by mutableStateOf( + GeoRectBounds( + southWest = southWestPosition, + northEast = northEastPosition, + ), + ) + + override val groundImageState + get() = + if (useImageUrl) { + GroundImageState( + id = "groundImage", + bounds = bounds, + imageUrl = GROUND_IMAGE_URL, + opacity = opacity, + onClick = this::onGroundImageClick, + ) + } else { + GroundImageState( + id = "groundImage", + bounds = bounds, + image = image, + opacity = opacity, + onClick = this::onGroundImageClick, + ) + } + + override fun onGroundImageClick(clicked: GroundImageEvent) { + showToast("Ground image clicked.") + } + + override fun onMarkerDrag(dragged: MarkerState) { + // Update the internal position based on which marker was dragged + when (dragged.id) { + "south_west" -> southWestPosition = GeoPoint.from(dragged.position) + "north_east" -> northEastPosition = GeoPoint.from(dragged.position) + } + + // Update bounds using the new positions + bounds = + GeoRectBounds().also { + it.extend(markers[0].position) + it.extend(markers[1].position) + } + + framePolyline.points = framePoints(southWestPosition, northEastPosition) + } + + override fun showToast(text: String) { + this._messages.value = this._messages.value + ToastMessage(text = text) + } + + override fun removeToast(toastMessage: ToastMessage) { + this._messages.value = this._messages.value.filter { it != toastMessage } + } +} + +/** + * 2 つの角から矩形の 4 辺をなぞる点列を作る。NE → NW → SW → SE → NE で閉じる。 + * + * ドラッグで南北・東西が反転しても、常に 2 点を対角とする矩形になる。 + */ +private fun framePoints( + southWest: GeoPoint, + northEast: GeoPoint, +): List = + listOf( + northEast, + GeoPoint(latitude = northEast.latitude, longitude = southWest.longitude), + southWest, + GeoPoint(latitude = southWest.latitude, longitude = northEast.longitude), + northEast, + ) diff --git a/example-app/src/main/java/com/mapconductor/example/pages/heatmaplayer/HeatmapLayerPageViewModel.kt b/example-app/src/main/java/com/mapconductor/example/pages/heatmaplayer/HeatmapLayerPageViewModel.kt index 8b243dd3..a05c2593 100644 --- a/example-app/src/main/java/com/mapconductor/example/pages/heatmaplayer/HeatmapLayerPageViewModel.kt +++ b/example-app/src/main/java/com/mapconductor/example/pages/heatmaplayer/HeatmapLayerPageViewModel.kt @@ -1,95 +1,94 @@ -package com.mapconductor.example.pages.heatmaplayer - -import androidx.lifecycle.ViewModel -import com.mapconductor.core.features.GeoPoint -import com.mapconductor.core.map.MapCameraPosition -import com.mapconductor.core.map.MapViewStateInterface -import com.mapconductor.heatmap.HeatmapPointState -import com.mapconductor.postoffice.PostOfficeDataLoader -import kotlinx.coroutines.CoroutineScope -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.flow.MutableStateFlow -import kotlinx.coroutines.flow.StateFlow -import kotlinx.coroutines.flow.asStateFlow -import kotlinx.coroutines.launch - -interface HeatmapLayerViewModelInterface { - val initCameraPosition: MapCameraPosition - - val points: StateFlow> - val mapViewState: StateFlow?> - val isMapLoaded: StateFlow - val isDataLoading: StateFlow - - fun onMapViewChanged(mapViewState: MapViewStateInterface<*>) - - fun onMapLoaded(mapViewState: MapViewStateInterface<*>) - - fun loadPostOfficeData() -} - -class HeatmapLayerPageViewModel( - private val dataLoader: PostOfficeDataLoader, - private val coroutine: CoroutineScope = CoroutineScope(Dispatchers.Default), -) : ViewModel(), - HeatmapLayerViewModelInterface { - override val initCameraPosition = - MapCameraPosition( - position = - GeoPoint.fromLatLong( - latitude = 35.68049, - longitude = 139.76669, - ), - zoom = 10.0, - bearing = 0.0, - tilt = 0.0, - paddings = null, - ) - private val _points: MutableStateFlow> = MutableStateFlow(emptyList()) - override val points: StateFlow> = _points.asStateFlow() - - private val _isMapLoaded: MutableStateFlow = MutableStateFlow(false) - override val isMapLoaded: StateFlow = _isMapLoaded.asStateFlow() - - private val _isDataLoading: MutableStateFlow = MutableStateFlow(false) - override val isDataLoading: StateFlow = _isDataLoading.asStateFlow() - - private var _mapViewState: MutableStateFlow?> = MutableStateFlow(null) - override val mapViewState: StateFlow?> = _mapViewState.asStateFlow() - - private var cameraPosition: MapCameraPosition = initCameraPosition - - override fun loadPostOfficeData() { - if (_points.value.isNotEmpty()) return - - coroutine.launch { - _isDataLoading.value = true - _points.value = dataLoader.loadAllPostOffices().map { HeatmapPointState(it.position) } - _isDataLoading.value = false - } - } - - // Convenience: in case of error paths, ensure the dialog is hidden - private fun markLoadingFinished() { - if (_isDataLoading.value) { - _isDataLoading.value = false - } - } - - override fun onMapLoaded(mapViewState: MapViewStateInterface<*>) { - coroutine.launch { - _isMapLoaded.value = true - _mapViewState.value?.moveCameraTo( - cameraPosition = cameraPosition, - ) - } - } - - override fun onMapViewChanged(mapViewState: MapViewStateInterface<*>) { - cameraPosition = mapViewState.cameraPosition - - _mapViewState.value = mapViewState - _isMapLoaded.value = false - } - -} +package com.mapconductor.example.pages.heatmaplayer + +import androidx.lifecycle.ViewModel +import com.mapconductor.core.features.GeoPoint +import com.mapconductor.core.map.MapCameraPosition +import com.mapconductor.core.map.MapViewStateInterface +import com.mapconductor.heatmap.HeatmapPointState +import com.mapconductor.postoffice.PostOfficeDataLoader +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.launch + +interface HeatmapLayerViewModelInterface { + val initCameraPosition: MapCameraPosition + + val points: StateFlow> + val mapViewState: StateFlow?> + val isMapLoaded: StateFlow + val isDataLoading: StateFlow + + fun onMapViewChanged(mapViewState: MapViewStateInterface<*>) + + fun onMapLoaded(mapViewState: MapViewStateInterface<*>) + + fun loadPostOfficeData() +} + +class HeatmapLayerPageViewModel( + private val dataLoader: PostOfficeDataLoader, + private val coroutine: CoroutineScope = CoroutineScope(Dispatchers.Default), +) : ViewModel(), + HeatmapLayerViewModelInterface { + override val initCameraPosition = + MapCameraPosition( + position = + GeoPoint.fromLatLong( + latitude = 35.68049, + longitude = 139.76669, + ), + zoom = 10.0, + bearing = 0.0, + tilt = 0.0, + paddings = null, + ) + private val _points: MutableStateFlow> = MutableStateFlow(emptyList()) + override val points: StateFlow> = _points.asStateFlow() + + private val _isMapLoaded: MutableStateFlow = MutableStateFlow(false) + override val isMapLoaded: StateFlow = _isMapLoaded.asStateFlow() + + private val _isDataLoading: MutableStateFlow = MutableStateFlow(false) + override val isDataLoading: StateFlow = _isDataLoading.asStateFlow() + + private var _mapViewState: MutableStateFlow?> = MutableStateFlow(null) + override val mapViewState: StateFlow?> = _mapViewState.asStateFlow() + + private var cameraPosition: MapCameraPosition = initCameraPosition + + override fun loadPostOfficeData() { + if (_points.value.isNotEmpty()) return + + coroutine.launch { + _isDataLoading.value = true + _points.value = dataLoader.loadAllPostOffices().map { HeatmapPointState(it.position) } + _isDataLoading.value = false + } + } + + // Convenience: in case of error paths, ensure the dialog is hidden + private fun markLoadingFinished() { + if (_isDataLoading.value) { + _isDataLoading.value = false + } + } + + override fun onMapLoaded(mapViewState: MapViewStateInterface<*>) { + coroutine.launch { + _isMapLoaded.value = true + _mapViewState.value?.moveCameraTo( + cameraPosition = cameraPosition, + ) + } + } + + override fun onMapViewChanged(mapViewState: MapViewStateInterface<*>) { + cameraPosition = mapViewState.cameraPosition + + _mapViewState.value = mapViewState + _isMapLoaded.value = false + } +} diff --git a/example-app/src/main/java/com/mapconductor/example/pages/infobubble/StyledInfoBubblePage.kt b/example-app/src/main/java/com/mapconductor/example/pages/infobubble/StyledInfoBubblePage.kt index 5f1fd011..7f770563 100644 --- a/example-app/src/main/java/com/mapconductor/example/pages/infobubble/StyledInfoBubblePage.kt +++ b/example-app/src/main/java/com/mapconductor/example/pages/infobubble/StyledInfoBubblePage.kt @@ -1,202 +1,201 @@ -package com.mapconductor.example.pages.infobubble - -import androidx.compose.foundation.background -import androidx.compose.foundation.border -import androidx.compose.foundation.clickable -import androidx.compose.foundation.layout.Box -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.Row -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.layout.size -import androidx.compose.foundation.layout.width -import androidx.compose.foundation.shape.CircleShape -import androidx.compose.material3.Card -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.Slider -import androidx.compose.material3.Text -import androidx.compose.runtime.Composable -import androidx.compose.runtime.LaunchedEffect -import androidx.compose.runtime.getValue -import androidx.compose.runtime.key -import androidx.compose.runtime.mutableFloatStateOf -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.remember -import androidx.compose.runtime.setValue -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.graphics.Color -import androidx.compose.ui.unit.dp -import com.mapconductor.compose.info.InfoBubble -import com.mapconductor.compose.marker.Marker -import com.mapconductor.core.features.GeoPoint -import com.mapconductor.core.map.MapCameraPosition -import com.mapconductor.core.map.MapViewStateInterface -import com.mapconductor.core.marker.DefaultMarkerIcon -import com.mapconductor.core.marker.MarkerState -import com.mapconductor.example.MapViewContainer -import com.mapconductor.example.ui.DefaultMapViewItems -import com.mapconductor.example.ui.DemoMapPageScaffold - -/** - * react の StyledInfoBubblePage.tsx / ios の StyledInfoBubblePage.swift と同一仕様: - * マーカー 1 個と常時表示の InfoBubble を置き、パネルの 8 色スウォッチ 4 行 - * (バブル塗り / バブル枠線 / 文字 / マーカー)と 2 本のスライダー - * (枠線幅・マーカースケール 0.5〜2.0、0.25 刻み)でスタイルを組み替える。 - * - * palette は 4 行で共有する 8 色。白と黒を含めておくと - * 塗り=白 / 文字=黒の既定も同じ列で選べる。 - */ - -private val palette = - listOf( - Color(0xFFFFFFFF), - Color(0xFF111827), - Color(0xFFEF4444), - Color(0xFFF97316), - Color(0xFFEAB308), - Color(0xFF22C55E), - Color(0xFF3B82F6), - Color(0xFFA855F7), - ) - -private val startPosition = GeoPoint.fromLatLong(35.6812, 139.7671) - -@Composable -private fun SwatchRow( - label: String, - selected: Color, - onSelect: (Color) -> Unit, -) { - Row(verticalAlignment = Alignment.CenterVertically) { - Text( - text = label, - style = MaterialTheme.typography.bodySmall, - modifier = Modifier.width(64.dp), - ) - palette.forEach { color -> - Box( - modifier = - Modifier - .padding(end = 6.dp) - .size(22.dp) - .border( - width = if (selected == color) 2.dp else 1.dp, - color = if (selected == color) Color(0xFF2563EB) else Color(0x40111827), - shape = CircleShape, - ) - .padding(3.dp) - .background(color, CircleShape) - .clickable { onSelect(color) }, - ) - } - } -} - -@Composable -fun StyledInfoBubblePage( - modifier: Modifier = Modifier, - onToggleSidebar: () -> Unit = {}, -) { - val initCameraPosition = - remember { - MapCameraPosition( - position = startPosition, - zoom = 14.0, - ) - } - var mapViewState by remember { mutableStateOf?>(null) } - - var fillColor by remember { mutableStateOf(Color(0xFFFFFFFF)) } - var strokeColor by remember { mutableStateOf(Color(0xFF111827)) } - var fontColor by remember { mutableStateOf(Color(0xFF111827)) } - var markerColor by remember { mutableStateOf(Color(0xFFEF4444)) } - var strokeWidth by remember { mutableFloatStateOf(2.0f) } - var markerScale by remember { mutableFloatStateOf(1.0f) } - - val marker = - remember { - MarkerState( - id = "styled-bubble-marker", - position = startPosition, - icon = DefaultMarkerIcon(fillColor = Color(0xFFEF4444)), - ) - } - - LaunchedEffect(markerColor, markerScale) { - marker.icon = DefaultMarkerIcon(fillColor = markerColor, scale = markerScale) - } - - DemoMapPageScaffold( - menuItems = DefaultMapViewItems(initCameraPosition), - modifier = modifier, - onToggleSidebar = onToggleSidebar, - onMapViewStateChanged = { state -> - @Suppress("UNCHECKED_CAST") - mapViewState = state as MapViewStateInterface - }, - ) { paddingValues -> - mapViewState?.let { - MapViewContainer( - state = mapViewState, - ) { - Marker(marker) - // InfoBubble はスタイルとマーカーアイコンを登録時に焼き込むので、 - // 変更のたびに key で登録し直して最新の見た目・配置に揃える。 - key(fillColor, strokeColor, fontColor, strokeWidth, markerScale) { - InfoBubble( - marker = marker, - bubbleColor = fillColor, - borderColor = strokeColor, - borderWidth = strokeWidth.dp, - cornerRadius = 6.dp, - contentPadding = 10.dp, - ) { - Text( - text = "Custom Styled Bubble", - color = fontColor, - style = MaterialTheme.typography.bodyMedium, - ) - } - } - } - } - - // react / ios と同じ左下配置 - Card( - modifier = - Modifier - .align(Alignment.BottomStart) - .padding( - bottom = paddingValues.calculateBottomPadding() + 16.dp, - start = 16.dp, - ), - ) { - Column(modifier = Modifier.padding(12.dp)) { - SwatchRow(label = "Fill", selected = fillColor) { fillColor = it } - SwatchRow(label = "Stroke", selected = strokeColor) { strokeColor = it } - SwatchRow(label = "Font", selected = fontColor) { fontColor = it } - SwatchRow(label = "Marker", selected = markerColor) { markerColor = it } - Text( - text = "Stroke Width: %.2f".format(strokeWidth), - style = MaterialTheme.typography.bodySmall, - ) - Slider( - value = strokeWidth, - onValueChange = { strokeWidth = it }, - valueRange = 0.5f..2.0f, - steps = 5, - ) - Text( - text = "Marker Scale: %.2f".format(markerScale), - style = MaterialTheme.typography.bodySmall, - ) - Slider( - value = markerScale, - onValueChange = { markerScale = it }, - valueRange = 0.5f..2.0f, - steps = 5, - ) - } - } - } -} +package com.mapconductor.example.pages.infobubble + +import androidx.compose.foundation.background +import androidx.compose.foundation.border +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.material3.Card +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Slider +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.key +import androidx.compose.runtime.mutableFloatStateOf +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.unit.dp +import com.mapconductor.compose.info.InfoBubble +import com.mapconductor.compose.marker.Marker +import com.mapconductor.core.features.GeoPoint +import com.mapconductor.core.map.MapCameraPosition +import com.mapconductor.core.map.MapViewStateInterface +import com.mapconductor.core.marker.DefaultMarkerIcon +import com.mapconductor.core.marker.MarkerState +import com.mapconductor.example.MapViewContainer +import com.mapconductor.example.ui.DefaultMapViewItems +import com.mapconductor.example.ui.DemoMapPageScaffold + +/** + * react の StyledInfoBubblePage.tsx / ios の StyledInfoBubblePage.swift と同一仕様: + * マーカー 1 個と常時表示の InfoBubble を置き、パネルの 8 色スウォッチ 4 行 + * (バブル塗り / バブル枠線 / 文字 / マーカー)と 2 本のスライダー + * (枠線幅・マーカースケール 0.5〜2.0、0.25 刻み)でスタイルを組み替える。 + * + * palette は 4 行で共有する 8 色。白と黒を含めておくと + * 塗り=白 / 文字=黒の既定も同じ列で選べる。 + */ + +private val palette = + listOf( + Color(0xFFFFFFFF), + Color(0xFF111827), + Color(0xFFEF4444), + Color(0xFFF97316), + Color(0xFFEAB308), + Color(0xFF22C55E), + Color(0xFF3B82F6), + Color(0xFFA855F7), + ) + +private val startPosition = GeoPoint.fromLatLong(35.6812, 139.7671) + +@Composable +private fun SwatchRow( + label: String, + selected: Color, + onSelect: (Color) -> Unit, +) { + Row(verticalAlignment = Alignment.CenterVertically) { + Text( + text = label, + style = MaterialTheme.typography.bodySmall, + modifier = Modifier.width(64.dp), + ) + palette.forEach { color -> + Box( + modifier = + Modifier + .padding(end = 6.dp) + .size(22.dp) + .border( + width = if (selected == color) 2.dp else 1.dp, + color = if (selected == color) Color(0xFF2563EB) else Color(0x40111827), + shape = CircleShape, + ).padding(3.dp) + .background(color, CircleShape) + .clickable { onSelect(color) }, + ) + } + } +} + +@Composable +fun StyledInfoBubblePage( + modifier: Modifier = Modifier, + onToggleSidebar: () -> Unit = {}, +) { + val initCameraPosition = + remember { + MapCameraPosition( + position = startPosition, + zoom = 14.0, + ) + } + var mapViewState by remember { mutableStateOf?>(null) } + + var fillColor by remember { mutableStateOf(Color(0xFFFFFFFF)) } + var strokeColor by remember { mutableStateOf(Color(0xFF111827)) } + var fontColor by remember { mutableStateOf(Color(0xFF111827)) } + var markerColor by remember { mutableStateOf(Color(0xFFEF4444)) } + var strokeWidth by remember { mutableFloatStateOf(2.0f) } + var markerScale by remember { mutableFloatStateOf(1.0f) } + + val marker = + remember { + MarkerState( + id = "styled-bubble-marker", + position = startPosition, + icon = DefaultMarkerIcon(fillColor = Color(0xFFEF4444)), + ) + } + + LaunchedEffect(markerColor, markerScale) { + marker.icon = DefaultMarkerIcon(fillColor = markerColor, scale = markerScale) + } + + DemoMapPageScaffold( + menuItems = DefaultMapViewItems(initCameraPosition), + modifier = modifier, + onToggleSidebar = onToggleSidebar, + onMapViewStateChanged = { state -> + @Suppress("UNCHECKED_CAST") + mapViewState = state as MapViewStateInterface + }, + ) { paddingValues -> + mapViewState?.let { + MapViewContainer( + state = mapViewState, + ) { + Marker(marker) + // InfoBubble はスタイルとマーカーアイコンを登録時に焼き込むので、 + // 変更のたびに key で登録し直して最新の見た目・配置に揃える。 + key(fillColor, strokeColor, fontColor, strokeWidth, markerScale) { + InfoBubble( + marker = marker, + bubbleColor = fillColor, + borderColor = strokeColor, + borderWidth = strokeWidth.dp, + cornerRadius = 6.dp, + contentPadding = 10.dp, + ) { + Text( + text = "Custom Styled Bubble", + color = fontColor, + style = MaterialTheme.typography.bodyMedium, + ) + } + } + } + } + + // react / ios と同じ左下配置 + Card( + modifier = + Modifier + .align(Alignment.BottomStart) + .padding( + bottom = paddingValues.calculateBottomPadding() + 16.dp, + start = 16.dp, + ), + ) { + Column(modifier = Modifier.padding(12.dp)) { + SwatchRow(label = "Fill", selected = fillColor) { fillColor = it } + SwatchRow(label = "Stroke", selected = strokeColor) { strokeColor = it } + SwatchRow(label = "Font", selected = fontColor) { fontColor = it } + SwatchRow(label = "Marker", selected = markerColor) { markerColor = it } + Text( + text = "Stroke Width: %.2f".format(strokeWidth), + style = MaterialTheme.typography.bodySmall, + ) + Slider( + value = strokeWidth, + onValueChange = { strokeWidth = it }, + valueRange = 0.5f..2.0f, + steps = 5, + ) + Text( + text = "Marker Scale: %.2f".format(markerScale), + style = MaterialTheme.typography.bodySmall, + ) + Slider( + value = markerScale, + onValueChange = { markerScale = it }, + valueRange = 0.5f..2.0f, + steps = 5, + ) + } + } + } +} diff --git a/example-app/src/main/java/com/mapconductor/example/pages/map/camerarestriction/CameraRestrictionMapPage.kt b/example-app/src/main/java/com/mapconductor/example/pages/map/camerarestriction/CameraRestrictionMapPage.kt index 3d21e08b..05495d34 100644 --- a/example-app/src/main/java/com/mapconductor/example/pages/map/camerarestriction/CameraRestrictionMapPage.kt +++ b/example-app/src/main/java/com/mapconductor/example/pages/map/camerarestriction/CameraRestrictionMapPage.kt @@ -144,8 +144,7 @@ fun CameraRestrictionMapPage( .padding( bottom = paddingValues.calculateBottomPadding() + 16.dp, start = 16.dp, - ) - .sizeIn(maxWidth = 420.dp), + ).sizeIn(maxWidth = 420.dp), ) { Column(modifier = Modifier.padding(12.dp)) { Row(verticalAlignment = Alignment.CenterVertically) { diff --git a/example-app/src/main/java/com/mapconductor/example/pages/map/camerasync/CameraSyncPage.kt b/example-app/src/main/java/com/mapconductor/example/pages/map/camerasync/CameraSyncPage.kt index d93f8ee0..b955b671 100644 --- a/example-app/src/main/java/com/mapconductor/example/pages/map/camerasync/CameraSyncPage.kt +++ b/example-app/src/main/java/com/mapconductor/example/pages/map/camerasync/CameraSyncPage.kt @@ -1,816 +1,825 @@ -package com.mapconductor.example.pages.map.camerasync - -import androidx.compose.foundation.background -import androidx.compose.foundation.clickable -import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Box -import androidx.compose.foundation.layout.BoxWithConstraints -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.ExperimentalLayoutApi -import androidx.compose.foundation.layout.FlowRow -import androidx.compose.foundation.layout.Row -import androidx.compose.foundation.layout.fillMaxHeight -import androidx.compose.foundation.layout.fillMaxSize -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.height -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.layout.size -import androidx.compose.foundation.layout.width -import androidx.compose.material.icons.Icons -import androidx.compose.material.icons.filled.Menu -import androidx.compose.material3.Button -import androidx.compose.material3.Card -import androidx.compose.material3.CardDefaults -import androidx.compose.material3.HorizontalDivider -import androidx.compose.material3.Icon -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.Scaffold -import androidx.compose.material3.Text -import androidx.compose.runtime.Composable -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableIntStateOf -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.remember -import androidx.compose.runtime.rememberCoroutineScope -import androidx.compose.runtime.rememberUpdatedState -import androidx.compose.runtime.saveable.rememberSaveable -import androidx.compose.runtime.setValue -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.graphics.Color -import androidx.compose.ui.layout.onSizeChanged -import androidx.compose.ui.platform.LocalDensity -import androidx.compose.ui.text.style.TextOverflow -import androidx.compose.ui.unit.IntSize -import androidx.compose.ui.unit.dp -import com.mapconductor.compose.polygon.Polygon -import com.mapconductor.compose.polyline.Polyline -import com.mapconductor.core.features.GeoPoint -import com.mapconductor.core.features.GeoRectBounds -import com.mapconductor.core.map.MapCameraPosition -import com.mapconductor.core.map.MapViewStateInterface -import com.mapconductor.core.polygon.PolygonState -import com.mapconductor.core.polyline.PolylineState -import com.mapconductor.example.MapViewContainer -import com.mapconductor.example.ui.DefaultMapViewItems -import com.mapconductor.example.ui.IconSelectMenu -import java.util.Locale -import android.os.SystemClock -import kotlinx.coroutines.launch - -private data class CameraLocationInfo( - val name: String, - val bounds: GeoRectBounds, - val center: GeoPoint, - val zoom: Double, -) - -private enum class ActiveMapPane { - Left, - Right, -} - -@Composable -fun CameraSyncPage(onToggleSidebar: () -> Unit = {}) { - val initCameraPosition = - remember { - MapCameraPosition( - position = GeoPoint(latitude = 35.6812, longitude = 139.7671, altitude = 0.0), // Tokyo - zoom = 12.0, - bearing = 0.0, - tilt = 0.0, - ) - } - - val locations = remember { defaultLocations() } - val boundsPolylines = remember(locations) { locations.map(::boundsPolyline) } - val referenceRectangles = remember(locations) { referenceRectangles(locations) } - - val leftMenuItems = DefaultMapViewItems(initCameraPosition) - val rightMenuItems = DefaultMapViewItems(initCameraPosition) - - // Default to Google Maps vs Longdo for zoom calibration. - // 添字直書きは DefaultMapViewItems の並びが変わるたびに壊れる(実際 arcgis2d を - // 挿入したときにずれた)ので、キーで引く。 - val leftDefaultIndex = - remember(leftMenuItems) { leftMenuItems.indexOfFirst { it.key == "google" }.coerceAtLeast(0) } - val rightDefaultIndex = - remember(rightMenuItems) { rightMenuItems.indexOfFirst { it.key == "longdo" }.coerceAtLeast(0) } - var leftSelectedIndex by rememberSaveable { mutableIntStateOf(leftDefaultIndex) } - var rightSelectedIndex by rememberSaveable { mutableIntStateOf(rightDefaultIndex) } - - @Suppress("UNCHECKED_CAST") - val leftState = leftMenuItems[leftSelectedIndex].value as MapViewStateInterface<*> - - @Suppress("UNCHECKED_CAST") - val rightState = rightMenuItems[rightSelectedIndex].value as MapViewStateInterface<*> - - // Use rememberUpdatedState to ensure callbacks always reference the current state, - // not the state captured when the callback lambda was created. - val currentLeftState by rememberUpdatedState(leftState) - val currentRightState by rememberUpdatedState(rightState) - - var leftCameraPosition by remember { mutableStateOf(initCameraPosition) } - var rightCameraPosition by remember { mutableStateOf(initCameraPosition) } - val mainScope = rememberCoroutineScope() - - // Guard against feedback loops for programmatic sync: - // when we move a map by code, ignore the next camera callbacks that correspond to that same target. - var programmaticLeftKey by remember { mutableStateOf(null) } - var programmaticLeftTarget by remember { mutableStateOf(null) } - var programmaticLeftUntilMs by remember { mutableStateOf(0L) } - var programmaticLeftSinceMs by remember { mutableStateOf(0L) } - var programmaticRightKey by remember { mutableStateOf(null) } - var programmaticRightTarget by remember { mutableStateOf(null) } - var programmaticRightUntilMs by remember { mutableStateOf(0L) } - var programmaticRightSinceMs by remember { mutableStateOf(0L) } - val programmaticTtlMs = 1200L - val programmaticGraceMs = 250L - - // Move-time sync throttling to keep the UI responsive and avoid overwhelming SDKs. - var lastLeftMoveSyncAtMs by remember { mutableStateOf(0L) } - var lastRightMoveSyncAtMs by remember { mutableStateOf(0L) } - val moveSyncIntervalMs = 33L // ~30fps - - fun cameraKey(camera: MapCameraPosition): Long { - val latE5 = (camera.position.latitude * 1e5).toInt() - val lonE5 = (camera.position.longitude * 1e5).toInt() - val zoom100 = (camera.zoom * 100).toInt() - val bearing10 = (camera.bearing * 10).toInt() - return (((latE5 * 31 + lonE5) * 31 + zoom100) * 31 + bearing10).toLong() - } - - fun markProgrammaticMove( - pane: ActiveMapPane, - target: MapCameraPosition, - nowMs: Long, - ) { - val key = cameraKey(target) - when (pane) { - ActiveMapPane.Left -> { - programmaticLeftKey = key - programmaticLeftTarget = target - programmaticLeftSinceMs = nowMs - programmaticLeftUntilMs = nowMs + programmaticTtlMs - } - - ActiveMapPane.Right -> { - programmaticRightKey = key - programmaticRightTarget = target - programmaticRightSinceMs = nowMs - programmaticRightUntilMs = nowMs + programmaticTtlMs - } - } - } - - fun clearProgrammaticMove(pane: ActiveMapPane) { - when (pane) { - ActiveMapPane.Left -> { - programmaticLeftKey = null - programmaticLeftTarget = null - programmaticLeftSinceMs = 0L - programmaticLeftUntilMs = 0L - } - - ActiveMapPane.Right -> { - programmaticRightKey = null - programmaticRightTarget = null - programmaticRightSinceMs = 0L - programmaticRightUntilMs = 0L - } - } - } - - fun bearingDeltaDeg( - a: Double, - b: Double, - ): Double { - val d = ((a - b) % 360.0 + 360.0) % 360.0 - return if (d > 180.0) 360.0 - d else d - } - - fun isCloseToTarget( - camera: MapCameraPosition, - target: MapCameraPosition, - ): Boolean { - val dLat = kotlin.math.abs(camera.position.latitude - target.position.latitude) - val dLon = kotlin.math.abs(camera.position.longitude - target.position.longitude) - val dZoom = kotlin.math.abs(camera.zoom - target.zoom) - val dBearing = bearingDeltaDeg(camera.bearing, target.bearing) - val dTilt = kotlin.math.abs(camera.tilt - target.tilt) - - // Tolerances are intentionally a bit loose: different SDKs can't represent the exact same camera. - return dLat < 0.0012 && dLon < 0.0012 && dZoom < 0.75 && dBearing < 12.0 && dTilt < 6.0 - } - - fun isProgrammaticMove( - pane: ActiveMapPane, - camera: MapCameraPosition, - nowMs: Long, - ): Boolean { - val (key, target, until) = - when (pane) { - ActiveMapPane.Left -> Triple(programmaticLeftKey, programmaticLeftTarget, programmaticLeftUntilMs) - ActiveMapPane.Right -> Triple(programmaticRightKey, programmaticRightTarget, programmaticRightUntilMs) - } - val k = key ?: return false - if (nowMs > until) return false - if (cameraKey(camera) == k) return true - return target?.let { isCloseToTarget(camera, it) } ?: false - } - - Scaffold { paddingValues -> - Column(modifier = Modifier - .fillMaxSize() - .padding(paddingValues)) { - Card( - modifier = Modifier - .fillMaxWidth() - .padding(10.dp), - elevation = CardDefaults.cardElevation(defaultElevation = 8.dp), - ) { - Row( - modifier = Modifier.padding(16.dp), - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(12.dp), - ) { - Icon( - imageVector = Icons.Default.Menu, - contentDescription = "Toggle sidebar", - modifier = - Modifier - .clickable(onClick = onToggleSidebar) - .size(32.dp) - .padding(end = 4.dp), - tint = MaterialTheme.colorScheme.onSurface, - ) - - Text( - text = "Camera Sync", - style = MaterialTheme.typography.titleMedium, - maxLines = 1, - overflow = TextOverflow.Ellipsis, - ) - } - } - - @OptIn(ExperimentalLayoutApi::class) - FlowRow( - modifier = - Modifier - .fillMaxWidth() - .padding(horizontal = 10.dp), - horizontalArrangement = Arrangement.spacedBy(8.dp), - verticalArrangement = Arrangement.spacedBy(8.dp), - maxLines = 2, - ) { - locations.forEach { location -> - Button( - onClick = { - val now = SystemClock.uptimeMillis() - val position = - MapCameraPosition( - position = location.center, - zoom = location.zoom, - bearing = 0.0, - tilt = 0.0, - ) - currentLeftState.moveCameraTo(position, durationMillis = 1000) - currentRightState.moveCameraTo(position, durationMillis = 1000) - leftCameraPosition = position - rightCameraPosition = position - // Both maps will emit camera callbacks; treat them as programmatic during the animation. - markProgrammaticMove(ActiveMapPane.Left, position, now) - markProgrammaticMove(ActiveMapPane.Right, position, now) - programmaticLeftUntilMs = now + 1000L + programmaticTtlMs - programmaticRightUntilMs = now + 1000L + programmaticTtlMs - }, - ) { - Text(text = location.name, maxLines = 1, overflow = TextOverflow.Ellipsis) - } - } - } - - HorizontalDivider(modifier = Modifier.padding(top = 10.dp)) - - BoxWithConstraints(modifier = Modifier.fillMaxSize()) { - val stackVertically = maxHeight > maxWidth - - if (stackVertically) { - Column(modifier = Modifier.fillMaxSize()) { - CameraSyncMapPane( - modifier = Modifier - .weight(1f) - .fillMaxWidth(), - menuContent = { - IconSelectMenu( - itemList = leftMenuItems, - selectedIndex = leftSelectedIndex, - onSelect = { index, _ -> leftSelectedIndex = index }, - ) - }, - mapViewState = leftState, - providerKey = leftMenuItems[leftSelectedIndex].key, - label = "Source Camera", - cameraPosition = leftCameraPosition, - onCameraMove = { position -> - mainScope.launch { - val now = SystemClock.uptimeMillis() - // Ignore feedback from programmatic moves (but stop ignoring if the user deviates). - if (programmaticLeftKey != null) { - if (now > programmaticLeftUntilMs) { - clearProgrammaticMove(ActiveMapPane.Left) - } else { - val age = now - programmaticLeftSinceMs - if (age <= programmaticGraceMs || - isProgrammaticMove(ActiveMapPane.Left, position, now) - ) { - leftCameraPosition = position - return@launch - } - clearProgrammaticMove(ActiveMapPane.Left) - } - } - - if (now - lastLeftMoveSyncAtMs < moveSyncIntervalMs) return@launch - lastLeftMoveSyncAtMs = now - - leftCameraPosition = position - rightCameraPosition = position - markProgrammaticMove(ActiveMapPane.Right, position, now) - currentRightState.moveCameraTo(position, durationMillis = 0) - } - }, - onCameraMoveEnd = { position -> - mainScope.launch { - val now = SystemClock.uptimeMillis() - if (programmaticLeftKey != null) { - if (now > programmaticLeftUntilMs) { - clearProgrammaticMove(ActiveMapPane.Left) - } else { - val age = now - programmaticLeftSinceMs - if (age <= programmaticGraceMs || - isProgrammaticMove(ActiveMapPane.Left, position, now) - ) { - leftCameraPosition = position - return@launch - } - clearProgrammaticMove(ActiveMapPane.Left) - } - } - leftCameraPosition = position - rightCameraPosition = position - markProgrammaticMove(ActiveMapPane.Right, position, now) - currentRightState.moveCameraTo(position, durationMillis = 0) - } - }, - boundsPolylines = boundsPolylines, - referenceRectangles = referenceRectangles, - ) - - Box( - modifier = - Modifier - .fillMaxWidth() - .height(1.dp) - .background(MaterialTheme.colorScheme.outline), - ) - - CameraSyncMapPane( - modifier = Modifier - .weight(1f) - .fillMaxWidth(), - menuContent = { - IconSelectMenu( - itemList = rightMenuItems, - selectedIndex = rightSelectedIndex, - onSelect = { index, _ -> rightSelectedIndex = index }, - ) - }, - mapViewState = rightState, - providerKey = rightMenuItems[rightSelectedIndex].key, - label = "Synced Camera", - cameraPosition = rightCameraPosition, - onCameraMove = { position -> - mainScope.launch { - val now = SystemClock.uptimeMillis() - if (programmaticRightKey != null) { - if (now > programmaticRightUntilMs) { - clearProgrammaticMove(ActiveMapPane.Right) - } else { - val age = now - programmaticRightSinceMs - if (age <= programmaticGraceMs || - isProgrammaticMove(ActiveMapPane.Right, position, now) - ) { - rightCameraPosition = position - return@launch - } - clearProgrammaticMove(ActiveMapPane.Right) - } - } - - if (now - lastRightMoveSyncAtMs < moveSyncIntervalMs) return@launch - lastRightMoveSyncAtMs = now - - rightCameraPosition = position - leftCameraPosition = position - markProgrammaticMove(ActiveMapPane.Left, position, now) - currentLeftState.moveCameraTo(position, durationMillis = 0) - } - }, - onCameraMoveEnd = { position -> - mainScope.launch { - val now = SystemClock.uptimeMillis() - if (programmaticRightKey != null) { - if (now > programmaticRightUntilMs) { - clearProgrammaticMove(ActiveMapPane.Right) - } else { - val age = now - programmaticRightSinceMs - if (age <= programmaticGraceMs || - isProgrammaticMove(ActiveMapPane.Right, position, now) - ) { - rightCameraPosition = position - return@launch - } - clearProgrammaticMove(ActiveMapPane.Right) - } - } - rightCameraPosition = position - leftCameraPosition = position - markProgrammaticMove(ActiveMapPane.Left, position, now) - currentLeftState.moveCameraTo(position, durationMillis = 0) - } - }, - boundsPolylines = boundsPolylines, - referenceRectangles = referenceRectangles, - ) - } - } else { - Row(modifier = Modifier.fillMaxSize()) { - CameraSyncMapPane( - modifier = Modifier - .weight(1f) - .fillMaxHeight(), - menuContent = { - IconSelectMenu( - itemList = leftMenuItems, - selectedIndex = leftSelectedIndex, - onSelect = { index, _ -> leftSelectedIndex = index }, - ) - }, - mapViewState = leftState, - providerKey = leftMenuItems[leftSelectedIndex].key, - label = "Source Camera", - cameraPosition = leftCameraPosition, - onCameraMove = { position -> - mainScope.launch { - val now = SystemClock.uptimeMillis() - if (programmaticLeftKey != null) { - if (now > programmaticLeftUntilMs) { - clearProgrammaticMove(ActiveMapPane.Left) - } else { - val age = now - programmaticLeftSinceMs - if (age <= programmaticGraceMs || - isProgrammaticMove(ActiveMapPane.Left, position, now) - ) { - leftCameraPosition = position - return@launch - } - clearProgrammaticMove(ActiveMapPane.Left) - } - } - - if (now - lastLeftMoveSyncAtMs < moveSyncIntervalMs) return@launch - lastLeftMoveSyncAtMs = now - - leftCameraPosition = position - rightCameraPosition = position - markProgrammaticMove(ActiveMapPane.Right, position, now) - currentRightState.moveCameraTo(position, durationMillis = 0) - } - }, - onCameraMoveEnd = { position -> - mainScope.launch { - val now = SystemClock.uptimeMillis() - if (programmaticLeftKey != null) { - if (now > programmaticLeftUntilMs) { - clearProgrammaticMove(ActiveMapPane.Left) - } else { - val age = now - programmaticLeftSinceMs - if (age <= programmaticGraceMs || - isProgrammaticMove(ActiveMapPane.Left, position, now) - ) { - leftCameraPosition = position - return@launch - } - clearProgrammaticMove(ActiveMapPane.Left) - } - } - leftCameraPosition = position - rightCameraPosition = position - markProgrammaticMove(ActiveMapPane.Right, position, now) - currentRightState.moveCameraTo(position, durationMillis = 0) - } - }, - boundsPolylines = boundsPolylines, - referenceRectangles = referenceRectangles, - ) - - Box( - modifier = - Modifier - .fillMaxHeight() - .width(1.dp) - .background(MaterialTheme.colorScheme.outline), - ) - - CameraSyncMapPane( - modifier = Modifier - .weight(1f) - .fillMaxHeight(), - menuContent = { - IconSelectMenu( - itemList = rightMenuItems, - selectedIndex = rightSelectedIndex, - onSelect = { index, _ -> rightSelectedIndex = index }, - ) - }, - mapViewState = rightState, - providerKey = rightMenuItems[rightSelectedIndex].key, - label = "Synced Camera", - cameraPosition = rightCameraPosition, - onCameraMove = { position -> - mainScope.launch { - val now = SystemClock.uptimeMillis() - if (programmaticRightKey != null) { - if (now > programmaticRightUntilMs) { - clearProgrammaticMove(ActiveMapPane.Right) - } else { - val age = now - programmaticRightSinceMs - if (age <= programmaticGraceMs || - isProgrammaticMove(ActiveMapPane.Right, position, now) - ) { - rightCameraPosition = position - return@launch - } - clearProgrammaticMove(ActiveMapPane.Right) - } - } - - if (now - lastRightMoveSyncAtMs < moveSyncIntervalMs) return@launch - lastRightMoveSyncAtMs = now - - rightCameraPosition = position - leftCameraPosition = position - markProgrammaticMove(ActiveMapPane.Left, position, now) - currentLeftState.moveCameraTo(position, durationMillis = 0) - } - }, - onCameraMoveEnd = { position -> - mainScope.launch { - val now = SystemClock.uptimeMillis() - if (programmaticRightKey != null) { - if (now > programmaticRightUntilMs) { - clearProgrammaticMove(ActiveMapPane.Right) - } else { - val age = now - programmaticRightSinceMs - if (age <= programmaticGraceMs || - isProgrammaticMove(ActiveMapPane.Right, position, now) - ) { - rightCameraPosition = position - return@launch - } - clearProgrammaticMove(ActiveMapPane.Right) - } - } - rightCameraPosition = position - leftCameraPosition = position - markProgrammaticMove(ActiveMapPane.Left, position, now) - currentLeftState.moveCameraTo(position, durationMillis = 0) - } - }, - boundsPolylines = boundsPolylines, - referenceRectangles = referenceRectangles, - ) - } - } - } - } - } -} - -@Composable -private fun CameraSyncMapPane( - modifier: Modifier, - menuContent: (@Composable () -> Unit)? = null, - mapViewState: MapViewStateInterface<*>, - // このペインで選択中のプロバイダキー。ArcGIS は 2D / 3D が同じ状態型なので、 - // これを渡さないと ArcGIS 2D を選んでも 3D(SceneView)が描かれてしまう。 - providerKey: String, - label: String, - cameraPosition: MapCameraPosition, - onCameraMoveStart: (() -> Unit)? = null, - onCameraMove: ((MapCameraPosition) -> Unit)? = null, - onCameraMoveEnd: (MapCameraPosition) -> Unit, - boundsPolylines: List, - referenceRectangles: List, -) { - var mapSize by remember { mutableStateOf(IntSize.Zero) } - Box(modifier = modifier) { - // Base: Map (full available size). Overlays are drawn on top to maximize map area. - MapViewContainer( - modifier = Modifier - .fillMaxSize() - .onSizeChanged { mapSize = it }, - state = mapViewState, - providerKey = providerKey, - onCameraMoveStart = { onCameraMoveStart?.invoke() }, - onCameraMove = { pos -> onCameraMove?.invoke(pos) }, - onCameraMoveEnd = onCameraMoveEnd, - ) { - boundsPolylines.forEach { Polyline(it) } - referenceRectangles.forEach { Polygon(it) } - } - - // Top overlay: SDK selector (interactive) - if (menuContent != null) { - Box( - modifier = - Modifier - .align(Alignment.TopStart) - .padding(10.dp) - .fillMaxWidth(0.72f), - ) { - menuContent() - } - } - - // Bottom overlay: camera state display (read-only) - CameraInfoCard( - modifier = - Modifier - .align(Alignment.BottomStart) - .padding(10.dp), - label = label, - position = cameraPosition, - mapSize = mapSize, - ) - } -} - -@Composable -private fun CameraInfoCard( - modifier: Modifier, - label: String, - position: MapCameraPosition, - mapSize: IntSize, -) { - val fmt = remember { Locale.US } - val density = LocalDensity.current - val widthDp = with(density) { mapSize.width.toDp().value } - val heightDp = with(density) { mapSize.height.toDp().value } - Card(modifier = modifier) { - Column(modifier = Modifier.padding(10.dp)) { - Text( - text = label, - style = MaterialTheme.typography.labelMedium, - ) - Text( - text = "Lat: ${String.format(fmt, "%.5f", position.position.latitude)}", - style = MaterialTheme.typography.bodySmall, - ) - Text( - text = "Lng: ${String.format(fmt, "%.5f", position.position.longitude)}", - style = MaterialTheme.typography.bodySmall, - ) - Text( - text = "Zoom: ${String.format(fmt, "%.2f", position.zoom)}", - style = MaterialTheme.typography.bodySmall, - ) - Text( - text = "Tilt: ${String.format(fmt, "%.1f°", position.tilt)}", - style = MaterialTheme.typography.bodySmall, - ) - Text( - text = "Bearing: ${String.format(fmt, "%.1f°", position.bearing)}", - style = MaterialTheme.typography.bodySmall, - ) - Text( - text = "Alt: ${String.format(fmt, "%.0f m", position.position.altitude)}", - style = MaterialTheme.typography.bodySmall, - ) - Text( - text = "Size: ${String.format(fmt, "%.0f × %.0f dp", widthDp, heightDp)}", - style = MaterialTheme.typography.bodySmall, - ) - } - } -} - -private fun defaultLocations(): List = - listOf( - CameraLocationInfo( - name = "Tokyo", - bounds = - GeoRectBounds( - southWest = GeoPoint(latitude = 35.62, longitude = 139.70, altitude = 0.0), - northEast = GeoPoint(latitude = 35.74, longitude = 139.84, altitude = 0.0), - ), - center = GeoPoint(latitude = 35.6812, longitude = 139.7671, altitude = 0.0), - zoom = 12.0, - ), - CameraLocationInfo( - name = "French Southern and Antarctic Lands", - bounds = - GeoRectBounds( - southWest = GeoPoint(latitude = -49.5, longitude = 50.0, altitude = 0.0), - northEast = GeoPoint(latitude = -37.5, longitude = 77.0, altitude = 0.0), - ), - center = GeoPoint(latitude = -43.5, longitude = 63.5, altitude = 0.0), - zoom = 4.0, - ), - CameraLocationInfo( - name = "Finland", - bounds = - GeoRectBounds( - southWest = GeoPoint(latitude = 59.8, longitude = 19.1, altitude = 0.0), - northEast = GeoPoint(latitude = 70.1, longitude = 31.6, altitude = 0.0), - ), - center = GeoPoint(latitude = 64.95, longitude = 25.35, altitude = 0.0), - zoom = 5.0, - ), - CameraLocationInfo( - name = "Iceland", - bounds = - GeoRectBounds( - southWest = GeoPoint(latitude = 63.3, longitude = -24.5, altitude = 0.0), - northEast = GeoPoint(latitude = 66.6, longitude = -13.5, altitude = 0.0), - ), - center = GeoPoint(latitude = 64.95, longitude = -19.0, altitude = 0.0), - zoom = 6.0, - ), - CameraLocationInfo( - name = "Kiribati", - bounds = - GeoRectBounds( - southWest = GeoPoint(latitude = -11.5, longitude = -174.5, altitude = 0.0), - northEast = GeoPoint(latitude = 5.0, longitude = -147.0, altitude = 0.0), - ), - center = GeoPoint(latitude = -3.25, longitude = -160.75, altitude = 0.0), - zoom = 4.5, - ), - CameraLocationInfo( - name = "Oahu Island", - bounds = - GeoRectBounds( - southWest = GeoPoint(latitude = 21.25, longitude = -158.3, altitude = 0.0), - northEast = GeoPoint(latitude = 21.7, longitude = -157.65, altitude = 0.0), - ), - center = GeoPoint(latitude = 21.475, longitude = -157.975, altitude = 0.0), - zoom = 9.5, - ), - ) - -private fun boundsPolyline(location: CameraLocationInfo): PolylineState { - val sw = location.bounds.southWest ?: return PolylineState(points = emptyList()) - val ne = location.bounds.northEast ?: return PolylineState(points = emptyList()) - val points = - listOf( - sw, - GeoPoint(latitude = sw.latitude, longitude = ne.longitude, altitude = 0.0), - ne, - GeoPoint(latitude = ne.latitude, longitude = sw.longitude, altitude = 0.0), - sw, - ) - return PolylineState( - points = points, - strokeColor = Color.Red, - strokeWidth = 3.dp, - geodesic = true, - ) -} - -private fun referenceRectangles(locations: List): List { - val size = 1.0 // approx 100km at equator - return locations.mapIndexed { index, location -> - val lat = location.center.latitude - val lng = location.center.longitude - val points = - listOf( - GeoPoint(latitude = lat - size / 2.0, longitude = lng - size / 2.0, altitude = 0.0), - GeoPoint(latitude = lat - size / 2.0, longitude = lng + size / 2.0, altitude = 0.0), - GeoPoint(latitude = lat + size / 2.0, longitude = lng + size / 2.0, altitude = 0.0), - GeoPoint(latitude = lat + size / 2.0, longitude = lng - size / 2.0, altitude = 0.0), - GeoPoint(latitude = lat - size / 2.0, longitude = lng - size / 2.0, altitude = 0.0), - ) - PolygonState( - points = points, - id = "camera_sync_reference_$index", - strokeColor = Color.Blue, - strokeWidth = 2.dp, - fillColor = Color.Blue.copy(alpha = 0.1f), - geodesic = false, - zIndex = 1, - ) - } -} +package com.mapconductor.example.pages.map.camerasync + +import androidx.compose.foundation.background +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.BoxWithConstraints +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.ExperimentalLayoutApi +import androidx.compose.foundation.layout.FlowRow +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxHeight +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Menu +import androidx.compose.material3.Button +import androidx.compose.material3.Card +import androidx.compose.material3.CardDefaults +import androidx.compose.material3.HorizontalDivider +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Scaffold +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableIntStateOf +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.rememberUpdatedState +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.layout.onSizeChanged +import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.IntSize +import androidx.compose.ui.unit.dp +import com.mapconductor.compose.polygon.Polygon +import com.mapconductor.compose.polyline.Polyline +import com.mapconductor.core.features.GeoPoint +import com.mapconductor.core.features.GeoRectBounds +import com.mapconductor.core.map.MapCameraPosition +import com.mapconductor.core.map.MapViewStateInterface +import com.mapconductor.core.polygon.PolygonState +import com.mapconductor.core.polyline.PolylineState +import com.mapconductor.example.MapViewContainer +import com.mapconductor.example.ui.DefaultMapViewItems +import com.mapconductor.example.ui.IconSelectMenu +import java.util.Locale +import android.os.SystemClock +import kotlinx.coroutines.launch + +private data class CameraLocationInfo( + val name: String, + val bounds: GeoRectBounds, + val center: GeoPoint, + val zoom: Double, +) + +private enum class ActiveMapPane { + Left, + Right, +} + +@Composable +fun CameraSyncPage(onToggleSidebar: () -> Unit = {}) { + val initCameraPosition = + remember { + MapCameraPosition( + position = GeoPoint(latitude = 35.6812, longitude = 139.7671, altitude = 0.0), // Tokyo + zoom = 12.0, + bearing = 0.0, + tilt = 0.0, + ) + } + + val locations = remember { defaultLocations() } + val boundsPolylines = remember(locations) { locations.map(::boundsPolyline) } + val referenceRectangles = remember(locations) { referenceRectangles(locations) } + + val leftMenuItems = DefaultMapViewItems(initCameraPosition) + val rightMenuItems = DefaultMapViewItems(initCameraPosition) + + // Default to Google Maps vs Longdo for zoom calibration. + // 添字直書きは DefaultMapViewItems の並びが変わるたびに壊れる(実際 arcgis2d を + // 挿入したときにずれた)ので、キーで引く。 + val leftDefaultIndex = + remember(leftMenuItems) { leftMenuItems.indexOfFirst { it.key == "google" }.coerceAtLeast(0) } + val rightDefaultIndex = + remember(rightMenuItems) { rightMenuItems.indexOfFirst { it.key == "longdo" }.coerceAtLeast(0) } + var leftSelectedIndex by rememberSaveable { mutableIntStateOf(leftDefaultIndex) } + var rightSelectedIndex by rememberSaveable { mutableIntStateOf(rightDefaultIndex) } + + @Suppress("UNCHECKED_CAST") + val leftState = leftMenuItems[leftSelectedIndex].value as MapViewStateInterface<*> + + @Suppress("UNCHECKED_CAST") + val rightState = rightMenuItems[rightSelectedIndex].value as MapViewStateInterface<*> + + // Use rememberUpdatedState to ensure callbacks always reference the current state, + // not the state captured when the callback lambda was created. + val currentLeftState by rememberUpdatedState(leftState) + val currentRightState by rememberUpdatedState(rightState) + + var leftCameraPosition by remember { mutableStateOf(initCameraPosition) } + var rightCameraPosition by remember { mutableStateOf(initCameraPosition) } + val mainScope = rememberCoroutineScope() + + // Guard against feedback loops for programmatic sync: + // when we move a map by code, ignore the next camera callbacks that correspond to that same target. + var programmaticLeftKey by remember { mutableStateOf(null) } + var programmaticLeftTarget by remember { mutableStateOf(null) } + var programmaticLeftUntilMs by remember { mutableStateOf(0L) } + var programmaticLeftSinceMs by remember { mutableStateOf(0L) } + var programmaticRightKey by remember { mutableStateOf(null) } + var programmaticRightTarget by remember { mutableStateOf(null) } + var programmaticRightUntilMs by remember { mutableStateOf(0L) } + var programmaticRightSinceMs by remember { mutableStateOf(0L) } + val programmaticTtlMs = 1200L + val programmaticGraceMs = 250L + + // Move-time sync throttling to keep the UI responsive and avoid overwhelming SDKs. + var lastLeftMoveSyncAtMs by remember { mutableStateOf(0L) } + var lastRightMoveSyncAtMs by remember { mutableStateOf(0L) } + val moveSyncIntervalMs = 33L // ~30fps + + fun cameraKey(camera: MapCameraPosition): Long { + val latE5 = (camera.position.latitude * 1e5).toInt() + val lonE5 = (camera.position.longitude * 1e5).toInt() + val zoom100 = (camera.zoom * 100).toInt() + val bearing10 = (camera.bearing * 10).toInt() + return (((latE5 * 31 + lonE5) * 31 + zoom100) * 31 + bearing10).toLong() + } + + fun markProgrammaticMove( + pane: ActiveMapPane, + target: MapCameraPosition, + nowMs: Long, + ) { + val key = cameraKey(target) + when (pane) { + ActiveMapPane.Left -> { + programmaticLeftKey = key + programmaticLeftTarget = target + programmaticLeftSinceMs = nowMs + programmaticLeftUntilMs = nowMs + programmaticTtlMs + } + + ActiveMapPane.Right -> { + programmaticRightKey = key + programmaticRightTarget = target + programmaticRightSinceMs = nowMs + programmaticRightUntilMs = nowMs + programmaticTtlMs + } + } + } + + fun clearProgrammaticMove(pane: ActiveMapPane) { + when (pane) { + ActiveMapPane.Left -> { + programmaticLeftKey = null + programmaticLeftTarget = null + programmaticLeftSinceMs = 0L + programmaticLeftUntilMs = 0L + } + + ActiveMapPane.Right -> { + programmaticRightKey = null + programmaticRightTarget = null + programmaticRightSinceMs = 0L + programmaticRightUntilMs = 0L + } + } + } + + fun bearingDeltaDeg( + a: Double, + b: Double, + ): Double { + val d = ((a - b) % 360.0 + 360.0) % 360.0 + return if (d > 180.0) 360.0 - d else d + } + + fun isCloseToTarget( + camera: MapCameraPosition, + target: MapCameraPosition, + ): Boolean { + val dLat = kotlin.math.abs(camera.position.latitude - target.position.latitude) + val dLon = kotlin.math.abs(camera.position.longitude - target.position.longitude) + val dZoom = kotlin.math.abs(camera.zoom - target.zoom) + val dBearing = bearingDeltaDeg(camera.bearing, target.bearing) + val dTilt = kotlin.math.abs(camera.tilt - target.tilt) + + // Tolerances are intentionally a bit loose: different SDKs can't represent the exact same camera. + return dLat < 0.0012 && dLon < 0.0012 && dZoom < 0.75 && dBearing < 12.0 && dTilt < 6.0 + } + + fun isProgrammaticMove( + pane: ActiveMapPane, + camera: MapCameraPosition, + nowMs: Long, + ): Boolean { + val (key, target, until) = + when (pane) { + ActiveMapPane.Left -> Triple(programmaticLeftKey, programmaticLeftTarget, programmaticLeftUntilMs) + ActiveMapPane.Right -> Triple(programmaticRightKey, programmaticRightTarget, programmaticRightUntilMs) + } + val k = key ?: return false + if (nowMs > until) return false + if (cameraKey(camera) == k) return true + return target?.let { isCloseToTarget(camera, it) } ?: false + } + + Scaffold { paddingValues -> + Column( + modifier = + Modifier + .fillMaxSize() + .padding(paddingValues), + ) { + Card( + modifier = + Modifier + .fillMaxWidth() + .padding(10.dp), + elevation = CardDefaults.cardElevation(defaultElevation = 8.dp), + ) { + Row( + modifier = Modifier.padding(16.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(12.dp), + ) { + Icon( + imageVector = Icons.Default.Menu, + contentDescription = "Toggle sidebar", + modifier = + Modifier + .clickable(onClick = onToggleSidebar) + .size(32.dp) + .padding(end = 4.dp), + tint = MaterialTheme.colorScheme.onSurface, + ) + + Text( + text = "Camera Sync", + style = MaterialTheme.typography.titleMedium, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + } + } + + @OptIn(ExperimentalLayoutApi::class) + FlowRow( + modifier = + Modifier + .fillMaxWidth() + .padding(horizontal = 10.dp), + horizontalArrangement = Arrangement.spacedBy(8.dp), + verticalArrangement = Arrangement.spacedBy(8.dp), + maxLines = 2, + ) { + locations.forEach { location -> + Button( + onClick = { + val now = SystemClock.uptimeMillis() + val position = + MapCameraPosition( + position = location.center, + zoom = location.zoom, + bearing = 0.0, + tilt = 0.0, + ) + currentLeftState.moveCameraTo(position, durationMillis = 1000) + currentRightState.moveCameraTo(position, durationMillis = 1000) + leftCameraPosition = position + rightCameraPosition = position + // Both maps will emit camera callbacks; treat them as programmatic during the animation. + markProgrammaticMove(ActiveMapPane.Left, position, now) + markProgrammaticMove(ActiveMapPane.Right, position, now) + programmaticLeftUntilMs = now + 1000L + programmaticTtlMs + programmaticRightUntilMs = now + 1000L + programmaticTtlMs + }, + ) { + Text(text = location.name, maxLines = 1, overflow = TextOverflow.Ellipsis) + } + } + } + + HorizontalDivider(modifier = Modifier.padding(top = 10.dp)) + + BoxWithConstraints(modifier = Modifier.fillMaxSize()) { + val stackVertically = maxHeight > maxWidth + + if (stackVertically) { + Column(modifier = Modifier.fillMaxSize()) { + CameraSyncMapPane( + modifier = + Modifier + .weight(1f) + .fillMaxWidth(), + menuContent = { + IconSelectMenu( + itemList = leftMenuItems, + selectedIndex = leftSelectedIndex, + onSelect = { index, _ -> leftSelectedIndex = index }, + ) + }, + mapViewState = leftState, + providerKey = leftMenuItems[leftSelectedIndex].key, + label = "Source Camera", + cameraPosition = leftCameraPosition, + onCameraMove = { position -> + mainScope.launch { + val now = SystemClock.uptimeMillis() + // Ignore feedback from programmatic moves (but stop ignoring if the user deviates). + if (programmaticLeftKey != null) { + if (now > programmaticLeftUntilMs) { + clearProgrammaticMove(ActiveMapPane.Left) + } else { + val age = now - programmaticLeftSinceMs + if (age <= programmaticGraceMs || + isProgrammaticMove(ActiveMapPane.Left, position, now) + ) { + leftCameraPosition = position + return@launch + } + clearProgrammaticMove(ActiveMapPane.Left) + } + } + + if (now - lastLeftMoveSyncAtMs < moveSyncIntervalMs) return@launch + lastLeftMoveSyncAtMs = now + + leftCameraPosition = position + rightCameraPosition = position + markProgrammaticMove(ActiveMapPane.Right, position, now) + currentRightState.moveCameraTo(position, durationMillis = 0) + } + }, + onCameraMoveEnd = { position -> + mainScope.launch { + val now = SystemClock.uptimeMillis() + if (programmaticLeftKey != null) { + if (now > programmaticLeftUntilMs) { + clearProgrammaticMove(ActiveMapPane.Left) + } else { + val age = now - programmaticLeftSinceMs + if (age <= programmaticGraceMs || + isProgrammaticMove(ActiveMapPane.Left, position, now) + ) { + leftCameraPosition = position + return@launch + } + clearProgrammaticMove(ActiveMapPane.Left) + } + } + leftCameraPosition = position + rightCameraPosition = position + markProgrammaticMove(ActiveMapPane.Right, position, now) + currentRightState.moveCameraTo(position, durationMillis = 0) + } + }, + boundsPolylines = boundsPolylines, + referenceRectangles = referenceRectangles, + ) + + Box( + modifier = + Modifier + .fillMaxWidth() + .height(1.dp) + .background(MaterialTheme.colorScheme.outline), + ) + + CameraSyncMapPane( + modifier = + Modifier + .weight(1f) + .fillMaxWidth(), + menuContent = { + IconSelectMenu( + itemList = rightMenuItems, + selectedIndex = rightSelectedIndex, + onSelect = { index, _ -> rightSelectedIndex = index }, + ) + }, + mapViewState = rightState, + providerKey = rightMenuItems[rightSelectedIndex].key, + label = "Synced Camera", + cameraPosition = rightCameraPosition, + onCameraMove = { position -> + mainScope.launch { + val now = SystemClock.uptimeMillis() + if (programmaticRightKey != null) { + if (now > programmaticRightUntilMs) { + clearProgrammaticMove(ActiveMapPane.Right) + } else { + val age = now - programmaticRightSinceMs + if (age <= programmaticGraceMs || + isProgrammaticMove(ActiveMapPane.Right, position, now) + ) { + rightCameraPosition = position + return@launch + } + clearProgrammaticMove(ActiveMapPane.Right) + } + } + + if (now - lastRightMoveSyncAtMs < moveSyncIntervalMs) return@launch + lastRightMoveSyncAtMs = now + + rightCameraPosition = position + leftCameraPosition = position + markProgrammaticMove(ActiveMapPane.Left, position, now) + currentLeftState.moveCameraTo(position, durationMillis = 0) + } + }, + onCameraMoveEnd = { position -> + mainScope.launch { + val now = SystemClock.uptimeMillis() + if (programmaticRightKey != null) { + if (now > programmaticRightUntilMs) { + clearProgrammaticMove(ActiveMapPane.Right) + } else { + val age = now - programmaticRightSinceMs + if (age <= programmaticGraceMs || + isProgrammaticMove(ActiveMapPane.Right, position, now) + ) { + rightCameraPosition = position + return@launch + } + clearProgrammaticMove(ActiveMapPane.Right) + } + } + rightCameraPosition = position + leftCameraPosition = position + markProgrammaticMove(ActiveMapPane.Left, position, now) + currentLeftState.moveCameraTo(position, durationMillis = 0) + } + }, + boundsPolylines = boundsPolylines, + referenceRectangles = referenceRectangles, + ) + } + } else { + Row(modifier = Modifier.fillMaxSize()) { + CameraSyncMapPane( + modifier = + Modifier + .weight(1f) + .fillMaxHeight(), + menuContent = { + IconSelectMenu( + itemList = leftMenuItems, + selectedIndex = leftSelectedIndex, + onSelect = { index, _ -> leftSelectedIndex = index }, + ) + }, + mapViewState = leftState, + providerKey = leftMenuItems[leftSelectedIndex].key, + label = "Source Camera", + cameraPosition = leftCameraPosition, + onCameraMove = { position -> + mainScope.launch { + val now = SystemClock.uptimeMillis() + if (programmaticLeftKey != null) { + if (now > programmaticLeftUntilMs) { + clearProgrammaticMove(ActiveMapPane.Left) + } else { + val age = now - programmaticLeftSinceMs + if (age <= programmaticGraceMs || + isProgrammaticMove(ActiveMapPane.Left, position, now) + ) { + leftCameraPosition = position + return@launch + } + clearProgrammaticMove(ActiveMapPane.Left) + } + } + + if (now - lastLeftMoveSyncAtMs < moveSyncIntervalMs) return@launch + lastLeftMoveSyncAtMs = now + + leftCameraPosition = position + rightCameraPosition = position + markProgrammaticMove(ActiveMapPane.Right, position, now) + currentRightState.moveCameraTo(position, durationMillis = 0) + } + }, + onCameraMoveEnd = { position -> + mainScope.launch { + val now = SystemClock.uptimeMillis() + if (programmaticLeftKey != null) { + if (now > programmaticLeftUntilMs) { + clearProgrammaticMove(ActiveMapPane.Left) + } else { + val age = now - programmaticLeftSinceMs + if (age <= programmaticGraceMs || + isProgrammaticMove(ActiveMapPane.Left, position, now) + ) { + leftCameraPosition = position + return@launch + } + clearProgrammaticMove(ActiveMapPane.Left) + } + } + leftCameraPosition = position + rightCameraPosition = position + markProgrammaticMove(ActiveMapPane.Right, position, now) + currentRightState.moveCameraTo(position, durationMillis = 0) + } + }, + boundsPolylines = boundsPolylines, + referenceRectangles = referenceRectangles, + ) + + Box( + modifier = + Modifier + .fillMaxHeight() + .width(1.dp) + .background(MaterialTheme.colorScheme.outline), + ) + + CameraSyncMapPane( + modifier = + Modifier + .weight(1f) + .fillMaxHeight(), + menuContent = { + IconSelectMenu( + itemList = rightMenuItems, + selectedIndex = rightSelectedIndex, + onSelect = { index, _ -> rightSelectedIndex = index }, + ) + }, + mapViewState = rightState, + providerKey = rightMenuItems[rightSelectedIndex].key, + label = "Synced Camera", + cameraPosition = rightCameraPosition, + onCameraMove = { position -> + mainScope.launch { + val now = SystemClock.uptimeMillis() + if (programmaticRightKey != null) { + if (now > programmaticRightUntilMs) { + clearProgrammaticMove(ActiveMapPane.Right) + } else { + val age = now - programmaticRightSinceMs + if (age <= programmaticGraceMs || + isProgrammaticMove(ActiveMapPane.Right, position, now) + ) { + rightCameraPosition = position + return@launch + } + clearProgrammaticMove(ActiveMapPane.Right) + } + } + + if (now - lastRightMoveSyncAtMs < moveSyncIntervalMs) return@launch + lastRightMoveSyncAtMs = now + + rightCameraPosition = position + leftCameraPosition = position + markProgrammaticMove(ActiveMapPane.Left, position, now) + currentLeftState.moveCameraTo(position, durationMillis = 0) + } + }, + onCameraMoveEnd = { position -> + mainScope.launch { + val now = SystemClock.uptimeMillis() + if (programmaticRightKey != null) { + if (now > programmaticRightUntilMs) { + clearProgrammaticMove(ActiveMapPane.Right) + } else { + val age = now - programmaticRightSinceMs + if (age <= programmaticGraceMs || + isProgrammaticMove(ActiveMapPane.Right, position, now) + ) { + rightCameraPosition = position + return@launch + } + clearProgrammaticMove(ActiveMapPane.Right) + } + } + rightCameraPosition = position + leftCameraPosition = position + markProgrammaticMove(ActiveMapPane.Left, position, now) + currentLeftState.moveCameraTo(position, durationMillis = 0) + } + }, + boundsPolylines = boundsPolylines, + referenceRectangles = referenceRectangles, + ) + } + } + } + } + } +} + +@Composable +private fun CameraSyncMapPane( + modifier: Modifier, + menuContent: (@Composable () -> Unit)? = null, + mapViewState: MapViewStateInterface<*>, + // このペインで選択中のプロバイダキー。ArcGIS は 2D / 3D が同じ状態型なので、 + // これを渡さないと ArcGIS 2D を選んでも 3D(SceneView)が描かれてしまう。 + providerKey: String, + label: String, + cameraPosition: MapCameraPosition, + onCameraMoveStart: (() -> Unit)? = null, + onCameraMove: ((MapCameraPosition) -> Unit)? = null, + onCameraMoveEnd: (MapCameraPosition) -> Unit, + boundsPolylines: List, + referenceRectangles: List, +) { + var mapSize by remember { mutableStateOf(IntSize.Zero) } + Box(modifier = modifier) { + // Base: Map (full available size). Overlays are drawn on top to maximize map area. + MapViewContainer( + modifier = + Modifier + .fillMaxSize() + .onSizeChanged { mapSize = it }, + state = mapViewState, + providerKey = providerKey, + onCameraMoveStart = { onCameraMoveStart?.invoke() }, + onCameraMove = { pos -> onCameraMove?.invoke(pos) }, + onCameraMoveEnd = onCameraMoveEnd, + ) { + boundsPolylines.forEach { Polyline(it) } + referenceRectangles.forEach { Polygon(it) } + } + + // Top overlay: SDK selector (interactive) + if (menuContent != null) { + Box( + modifier = + Modifier + .align(Alignment.TopStart) + .padding(10.dp) + .fillMaxWidth(0.72f), + ) { + menuContent() + } + } + + // Bottom overlay: camera state display (read-only) + CameraInfoCard( + modifier = + Modifier + .align(Alignment.BottomStart) + .padding(10.dp), + label = label, + position = cameraPosition, + mapSize = mapSize, + ) + } +} + +@Composable +private fun CameraInfoCard( + modifier: Modifier, + label: String, + position: MapCameraPosition, + mapSize: IntSize, +) { + val fmt = remember { Locale.US } + val density = LocalDensity.current + val widthDp = with(density) { mapSize.width.toDp().value } + val heightDp = with(density) { mapSize.height.toDp().value } + Card(modifier = modifier) { + Column(modifier = Modifier.padding(10.dp)) { + Text( + text = label, + style = MaterialTheme.typography.labelMedium, + ) + Text( + text = "Lat: ${String.format(fmt, "%.5f", position.position.latitude)}", + style = MaterialTheme.typography.bodySmall, + ) + Text( + text = "Lng: ${String.format(fmt, "%.5f", position.position.longitude)}", + style = MaterialTheme.typography.bodySmall, + ) + Text( + text = "Zoom: ${String.format(fmt, "%.2f", position.zoom)}", + style = MaterialTheme.typography.bodySmall, + ) + Text( + text = "Tilt: ${String.format(fmt, "%.1f°", position.tilt)}", + style = MaterialTheme.typography.bodySmall, + ) + Text( + text = "Bearing: ${String.format(fmt, "%.1f°", position.bearing)}", + style = MaterialTheme.typography.bodySmall, + ) + Text( + text = "Alt: ${String.format(fmt, "%.0f m", position.position.altitude)}", + style = MaterialTheme.typography.bodySmall, + ) + Text( + text = "Size: ${String.format(fmt, "%.0f × %.0f dp", widthDp, heightDp)}", + style = MaterialTheme.typography.bodySmall, + ) + } + } +} + +private fun defaultLocations(): List = + listOf( + CameraLocationInfo( + name = "Tokyo", + bounds = + GeoRectBounds( + southWest = GeoPoint(latitude = 35.62, longitude = 139.70, altitude = 0.0), + northEast = GeoPoint(latitude = 35.74, longitude = 139.84, altitude = 0.0), + ), + center = GeoPoint(latitude = 35.6812, longitude = 139.7671, altitude = 0.0), + zoom = 12.0, + ), + CameraLocationInfo( + name = "French Southern and Antarctic Lands", + bounds = + GeoRectBounds( + southWest = GeoPoint(latitude = -49.5, longitude = 50.0, altitude = 0.0), + northEast = GeoPoint(latitude = -37.5, longitude = 77.0, altitude = 0.0), + ), + center = GeoPoint(latitude = -43.5, longitude = 63.5, altitude = 0.0), + zoom = 4.0, + ), + CameraLocationInfo( + name = "Finland", + bounds = + GeoRectBounds( + southWest = GeoPoint(latitude = 59.8, longitude = 19.1, altitude = 0.0), + northEast = GeoPoint(latitude = 70.1, longitude = 31.6, altitude = 0.0), + ), + center = GeoPoint(latitude = 64.95, longitude = 25.35, altitude = 0.0), + zoom = 5.0, + ), + CameraLocationInfo( + name = "Iceland", + bounds = + GeoRectBounds( + southWest = GeoPoint(latitude = 63.3, longitude = -24.5, altitude = 0.0), + northEast = GeoPoint(latitude = 66.6, longitude = -13.5, altitude = 0.0), + ), + center = GeoPoint(latitude = 64.95, longitude = -19.0, altitude = 0.0), + zoom = 6.0, + ), + CameraLocationInfo( + name = "Kiribati", + bounds = + GeoRectBounds( + southWest = GeoPoint(latitude = -11.5, longitude = -174.5, altitude = 0.0), + northEast = GeoPoint(latitude = 5.0, longitude = -147.0, altitude = 0.0), + ), + center = GeoPoint(latitude = -3.25, longitude = -160.75, altitude = 0.0), + zoom = 4.5, + ), + CameraLocationInfo( + name = "Oahu Island", + bounds = + GeoRectBounds( + southWest = GeoPoint(latitude = 21.25, longitude = -158.3, altitude = 0.0), + northEast = GeoPoint(latitude = 21.7, longitude = -157.65, altitude = 0.0), + ), + center = GeoPoint(latitude = 21.475, longitude = -157.975, altitude = 0.0), + zoom = 9.5, + ), + ) + +private fun boundsPolyline(location: CameraLocationInfo): PolylineState { + val sw = location.bounds.southWest ?: return PolylineState(points = emptyList()) + val ne = location.bounds.northEast ?: return PolylineState(points = emptyList()) + val points = + listOf( + sw, + GeoPoint(latitude = sw.latitude, longitude = ne.longitude, altitude = 0.0), + ne, + GeoPoint(latitude = ne.latitude, longitude = sw.longitude, altitude = 0.0), + sw, + ) + return PolylineState( + points = points, + strokeColor = Color.Red, + strokeWidth = 3.dp, + geodesic = true, + ) +} + +private fun referenceRectangles(locations: List): List { + val size = 1.0 // approx 100km at equator + return locations.mapIndexed { index, location -> + val lat = location.center.latitude + val lng = location.center.longitude + val points = + listOf( + GeoPoint(latitude = lat - size / 2.0, longitude = lng - size / 2.0, altitude = 0.0), + GeoPoint(latitude = lat - size / 2.0, longitude = lng + size / 2.0, altitude = 0.0), + GeoPoint(latitude = lat + size / 2.0, longitude = lng + size / 2.0, altitude = 0.0), + GeoPoint(latitude = lat + size / 2.0, longitude = lng - size / 2.0, altitude = 0.0), + GeoPoint(latitude = lat - size / 2.0, longitude = lng - size / 2.0, altitude = 0.0), + ) + PolygonState( + points = points, + id = "camera_sync_reference_$index", + strokeColor = Color.Blue, + strokeWidth = 2.dp, + fillColor = Color.Blue.copy(alpha = 0.1f), + geodesic = false, + zIndex = 1, + ) + } +} diff --git a/example-app/src/main/java/com/mapconductor/example/pages/map/tilt/TiltMapPage.kt b/example-app/src/main/java/com/mapconductor/example/pages/map/tilt/TiltMapPage.kt index 0e152d9f..baed617b 100644 --- a/example-app/src/main/java/com/mapconductor/example/pages/map/tilt/TiltMapPage.kt +++ b/example-app/src/main/java/com/mapconductor/example/pages/map/tilt/TiltMapPage.kt @@ -1,202 +1,201 @@ -package com.mapconductor.example.pages.map.tilt - -import androidx.compose.foundation.Canvas -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.Row -import androidx.compose.foundation.layout.Spacer -import androidx.compose.foundation.layout.calculateEndPadding -import androidx.compose.foundation.layout.calculateStartPadding -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.height -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.layout.sizeIn -import androidx.compose.material3.Card -import androidx.compose.material3.Slider -import androidx.compose.material3.Text -import androidx.compose.runtime.Composable -import androidx.compose.runtime.collectAsState -import androidx.compose.runtime.remember -import androidx.compose.runtime.rememberCoroutineScope -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.geometry.Offset -import androidx.compose.ui.graphics.Color -import androidx.compose.ui.graphics.Path -import androidx.compose.ui.graphics.StrokeCap -import androidx.compose.ui.graphics.drawscope.Stroke -import androidx.compose.ui.unit.LayoutDirection -import androidx.compose.ui.unit.dp -import com.mapconductor.compose.circle.Circle -import com.mapconductor.compose.marker.Marker -import com.mapconductor.example.MapViewContainer -import com.mapconductor.example.ui.DefaultMapViewItems -import com.mapconductor.example.ui.DemoMapPageScaffold -import kotlin.math.PI -import kotlin.math.abs -import kotlin.math.tan -import kotlinx.coroutines.delay -import kotlinx.coroutines.launch - -@Composable -fun TiltMapPage( - modifier: Modifier = Modifier, - onToggleSidebar: () -> Unit = {}, -) { - val coroutineScope = rememberCoroutineScope() - val debounceMs = 80L - val viewModel = remember { TiltMapPageViewModel() } - - val tilt = viewModel.tilt - - DemoMapPageScaffold( - menuItems = DefaultMapViewItems(viewModel.initCameraPosition), - modifier = modifier, - onToggleSidebar = onToggleSidebar, - onMapViewStateChanged = viewModel::onMapViewChanged, - ) { paddingValues -> - val mapViewState = viewModel.mapViewState.collectAsState().value - - mapViewState?.let { - MapViewContainer( - state = mapViewState, - ) { - viewModel.anchorCircleStates.forEach { circleState -> - Circle(circleState) - } - viewModel.markerStates.forEach { markerState -> - Marker(markerState) - } - } - } - - // Message Card - Card( - modifier = - Modifier - .align(Alignment.BottomStart) - .padding( - bottom = paddingValues.calculateBottomPadding(), - start = paddingValues.calculateStartPadding(LayoutDirection.Ltr) + 16.dp, - end = paddingValues.calculateEndPadding(LayoutDirection.Ltr) + 16.dp, - ) - .sizeIn( - maxWidth = 600.dp, - ), - ) { - Column(modifier = Modifier.padding(6.dp)) { - TiltCameraDiagram( - tilt = tilt, - modifier = - Modifier - .fillMaxWidth() - .height(120.dp), - ) - Spacer(modifier = Modifier.height(6.dp)) - Row { - Text("tilt: ${"%.2f".format(tilt)}") - Slider( - value = viewModel.tilt.toFloat(), - onValueChange = { newValue -> - coroutineScope.launch { - delay(debounceMs) - viewModel.tilt = newValue.toDouble() - } - }, - onValueChangeFinished = { - }, - valueRange = -89.0f..89.0f, // スライダー範囲 - steps = 0, - ) - } - } - } - } -} - -@Composable -private fun TiltCameraDiagram( - tilt: Double, - modifier: Modifier = Modifier, -) { - Canvas(modifier = modifier) { - val width = size.width - val height = size.height - val groundY = height * 0.78f - val originX = width * 0.5f - val originY = groundY - val baseCameraY = height * 0.22f - val maxTilt = 90.0 - val tiltAbs = abs(tilt).coerceIn(0.0, maxTilt) - val tiltRad = (tiltAbs * PI / 180.0).toFloat() - val altitudePx = groundY - baseCameraY - val targetDistance = - (altitudePx * tan(tiltRad)) - .coerceAtMost(width * 0.44f) - val targetX = if (tilt < 0.0) originX - targetDistance else originX - val targetY = groundY - val cameraX = if (tilt > 0.0) originX + targetDistance else originX - val cameraY = baseCameraY - val sightEndX = - if (tilt == 0.0) { - cameraX - } else { - targetX - } - val sightEndY = targetY - - drawLine( - color = Color(0xFFE4E0EC), - start = Offset(width * 0.08f, groundY), - end = Offset(width * 0.94f, groundY), - strokeWidth = 3f, - cap = StrokeCap.Round, - ) - drawLine( - color = Color(0xFF8E879A), - start = Offset(cameraX, cameraY), - end = Offset(cameraX, groundY), - strokeWidth = 2f, - ) - drawCircle( - color = Color(0xFF5DA7FF), - radius = 8f, - center = Offset(cameraX, cameraY), - ) - drawCircle( - color = Color(0xFFFF6259), - radius = 7f, - center = Offset(targetX, targetY), - ) - drawLine( - color = Color(0xFFFFC857), - start = Offset(cameraX, cameraY), - end = Offset(sightEndX, sightEndY), - strokeWidth = 4f, - cap = StrokeCap.Round, - ) - - val cameraBody = - Path().apply { - moveTo(cameraX - 12f, cameraY - 8f) - lineTo(cameraX + 14f, cameraY - 4f) - lineTo(cameraX + 10f, cameraY + 10f) - lineTo(cameraX - 12f, cameraY + 8f) - close() - } - drawPath(cameraBody, Color(0xFF2F2A38)) - drawPath(cameraBody, Color.White.copy(alpha = 0.7f), style = Stroke(width = 1.5f)) - - drawCircle( - color = Color(0xFF8E879A), - radius = 3.5f, - center = Offset(originX, originY), - ) - drawLine( - color = Color(0xFFB8AFCA), - start = Offset(minOf(cameraX, targetX), groundY + 12f), - end = Offset(maxOf(cameraX, targetX), groundY + 12f), - strokeWidth = 2f, - cap = StrokeCap.Round, - ) - } -} +package com.mapconductor.example.pages.map.tilt + +import androidx.compose.foundation.Canvas +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.calculateEndPadding +import androidx.compose.foundation.layout.calculateStartPadding +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.sizeIn +import androidx.compose.material3.Card +import androidx.compose.material3.Slider +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.collectAsState +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.Path +import androidx.compose.ui.graphics.StrokeCap +import androidx.compose.ui.graphics.drawscope.Stroke +import androidx.compose.ui.unit.LayoutDirection +import androidx.compose.ui.unit.dp +import com.mapconductor.compose.circle.Circle +import com.mapconductor.compose.marker.Marker +import com.mapconductor.example.MapViewContainer +import com.mapconductor.example.ui.DefaultMapViewItems +import com.mapconductor.example.ui.DemoMapPageScaffold +import kotlin.math.PI +import kotlin.math.abs +import kotlin.math.tan +import kotlinx.coroutines.delay +import kotlinx.coroutines.launch + +@Composable +fun TiltMapPage( + modifier: Modifier = Modifier, + onToggleSidebar: () -> Unit = {}, +) { + val coroutineScope = rememberCoroutineScope() + val debounceMs = 80L + val viewModel = remember { TiltMapPageViewModel() } + + val tilt = viewModel.tilt + + DemoMapPageScaffold( + menuItems = DefaultMapViewItems(viewModel.initCameraPosition), + modifier = modifier, + onToggleSidebar = onToggleSidebar, + onMapViewStateChanged = viewModel::onMapViewChanged, + ) { paddingValues -> + val mapViewState = viewModel.mapViewState.collectAsState().value + + mapViewState?.let { + MapViewContainer( + state = mapViewState, + ) { + viewModel.anchorCircleStates.forEach { circleState -> + Circle(circleState) + } + viewModel.markerStates.forEach { markerState -> + Marker(markerState) + } + } + } + + // Message Card + Card( + modifier = + Modifier + .align(Alignment.BottomStart) + .padding( + bottom = paddingValues.calculateBottomPadding(), + start = paddingValues.calculateStartPadding(LayoutDirection.Ltr) + 16.dp, + end = paddingValues.calculateEndPadding(LayoutDirection.Ltr) + 16.dp, + ).sizeIn( + maxWidth = 600.dp, + ), + ) { + Column(modifier = Modifier.padding(6.dp)) { + TiltCameraDiagram( + tilt = tilt, + modifier = + Modifier + .fillMaxWidth() + .height(120.dp), + ) + Spacer(modifier = Modifier.height(6.dp)) + Row { + Text("tilt: ${"%.2f".format(tilt)}") + Slider( + value = viewModel.tilt.toFloat(), + onValueChange = { newValue -> + coroutineScope.launch { + delay(debounceMs) + viewModel.tilt = newValue.toDouble() + } + }, + onValueChangeFinished = { + }, + valueRange = -89.0f..89.0f, // スライダー範囲 + steps = 0, + ) + } + } + } + } +} + +@Composable +private fun TiltCameraDiagram( + tilt: Double, + modifier: Modifier = Modifier, +) { + Canvas(modifier = modifier) { + val width = size.width + val height = size.height + val groundY = height * 0.78f + val originX = width * 0.5f + val originY = groundY + val baseCameraY = height * 0.22f + val maxTilt = 90.0 + val tiltAbs = abs(tilt).coerceIn(0.0, maxTilt) + val tiltRad = (tiltAbs * PI / 180.0).toFloat() + val altitudePx = groundY - baseCameraY + val targetDistance = + (altitudePx * tan(tiltRad)) + .coerceAtMost(width * 0.44f) + val targetX = if (tilt < 0.0) originX - targetDistance else originX + val targetY = groundY + val cameraX = if (tilt > 0.0) originX + targetDistance else originX + val cameraY = baseCameraY + val sightEndX = + if (tilt == 0.0) { + cameraX + } else { + targetX + } + val sightEndY = targetY + + drawLine( + color = Color(0xFFE4E0EC), + start = Offset(width * 0.08f, groundY), + end = Offset(width * 0.94f, groundY), + strokeWidth = 3f, + cap = StrokeCap.Round, + ) + drawLine( + color = Color(0xFF8E879A), + start = Offset(cameraX, cameraY), + end = Offset(cameraX, groundY), + strokeWidth = 2f, + ) + drawCircle( + color = Color(0xFF5DA7FF), + radius = 8f, + center = Offset(cameraX, cameraY), + ) + drawCircle( + color = Color(0xFFFF6259), + radius = 7f, + center = Offset(targetX, targetY), + ) + drawLine( + color = Color(0xFFFFC857), + start = Offset(cameraX, cameraY), + end = Offset(sightEndX, sightEndY), + strokeWidth = 4f, + cap = StrokeCap.Round, + ) + + val cameraBody = + Path().apply { + moveTo(cameraX - 12f, cameraY - 8f) + lineTo(cameraX + 14f, cameraY - 4f) + lineTo(cameraX + 10f, cameraY + 10f) + lineTo(cameraX - 12f, cameraY + 8f) + close() + } + drawPath(cameraBody, Color(0xFF2F2A38)) + drawPath(cameraBody, Color.White.copy(alpha = 0.7f), style = Stroke(width = 1.5f)) + + drawCircle( + color = Color(0xFF8E879A), + radius = 3.5f, + center = Offset(originX, originY), + ) + drawLine( + color = Color(0xFFB8AFCA), + start = Offset(minOf(cameraX, targetX), groundY + 12f), + end = Offset(maxOf(cameraX, targetX), groundY + 12f), + strokeWidth = 2f, + cap = StrokeCap.Round, + ) + } +} diff --git a/example-app/src/main/java/com/mapconductor/example/pages/map/uisettings/UISettingsMapPage.kt b/example-app/src/main/java/com/mapconductor/example/pages/map/uisettings/UISettingsMapPage.kt index 4836934d..1797b04f 100644 --- a/example-app/src/main/java/com/mapconductor/example/pages/map/uisettings/UISettingsMapPage.kt +++ b/example-app/src/main/java/com/mapconductor/example/pages/map/uisettings/UISettingsMapPage.kt @@ -1,185 +1,184 @@ -package com.mapconductor.example.pages.map.uisettings - -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.Row -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.layout.sizeIn -import androidx.compose.material3.Card -import androidx.compose.material3.Switch -import androidx.compose.material3.Text -import androidx.compose.runtime.Composable -import androidx.compose.runtime.LaunchedEffect -import androidx.compose.runtime.collectAsState -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.remember -import androidx.compose.runtime.saveable.rememberSaveable -import androidx.compose.runtime.setValue -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.unit.dp -import com.mapconductor.core.map.MapUISettings -import com.mapconductor.example.MapViewContainer -import com.mapconductor.example.ui.DefaultMapViewItems -import com.mapconductor.example.ui.DemoMapPageScaffold -import com.mapconductor.tomtom.TomTomMapViewState -import kotlin.time.Duration.Companion.milliseconds -import android.util.Log -import kotlinx.coroutines.delay - -/** - * Exercises [MapUISettings] against a live map. - * - * Four switches flip the gesture flags; after each change the page reads the - * values back off the provider's own map object and logs them under the - * `MCUISettings` tag, so a device run can be verified from logcat without having - * to touch the screen. On start it also cycles None -> Default automatically. - */ -@Composable -fun UISettingsMapPage( - modifier: Modifier = Modifier, - onToggleSidebar: () -> Unit = {}, -) { - val viewModel = remember { UISettingsMapPageViewModel() } - // A UI test presets the flags through an intent extra rather than tapping the - // switches, which is far more reliable than driving a Compose Switch by coordinate. - val preset = - if (com.mapconductor.example.MainActivity.gesturesExtra == "none") { - MapUISettings.None - } else { - null - } - - DemoMapPageScaffold( - menuItems = DefaultMapViewItems(viewModel.initCameraPosition), - onToggleSidebar = onToggleSidebar, - onMapViewStateChanged = viewModel::onMapViewChanged, - ) { paddingValues -> - val mapViewState = viewModel.mapViewState.collectAsState().value - - mapViewState?.let { state -> - // The flags live on the map state, not in this page: rememberXxxMapViewState - // saves them, so they survive a rotation. A page-local `remember` would - // come back all-true and overwrite the restored state. - // The intent preset is applied once per state (rememberSaveable keyed by its - // id), so a rotation does not re-apply it over what the user toggled since. - var presetApplied by rememberSaveable(state.id) { mutableStateOf(false) } - LaunchedEffect(state) { - if (!presetApplied && preset != null) state.uiSettings = preset - presetApplied = true - } - MapViewContainer( - state = state, - modifier = modifier, - onCameraMove = { c -> - Log.i("MCCamera", "%.5f,%.5f".format(c.position.latitude, c.position.longitude)) - }, - ) - - // Read back after every change, so manual toggles are verifiable too. - LaunchedEffect(state.uiSettings, state) { - delay(800.milliseconds) - report("settings=${state.uiSettings}", state) - } - } - - // ios / react と同じ左下配置(react の .control-panel、ios の bottomLeading と揃える) - Card( - modifier = - Modifier - .align(Alignment.BottomStart) - .padding( - bottom = paddingValues.calculateBottomPadding() + 16.dp, - start = 16.dp, - ) - .sizeIn(maxWidth = 360.dp), - ) { - Column(modifier = Modifier.padding(12.dp)) { - val state = mapViewState - val settings = state?.uiSettings ?: MapUISettings.Default - val update: (MapUISettings) -> Unit = { state?.uiSettings = it } - GestureSwitch("scrollGesture", settings.scrollGesture) { - update(settings.copy(scrollGesture = it)) - } - GestureSwitch("zoomGesture", settings.zoomGesture) { - update(settings.copy(zoomGesture = it)) - } - GestureSwitch("rotateGesture", settings.rotateGesture) { - update(settings.copy(rotateGesture = it)) - } - GestureSwitch("tiltGesture", settings.tiltGesture) { - update(settings.copy(tiltGesture = it)) - } - } - } - } -} - -@Composable -private fun GestureSwitch( - label: String, - checked: Boolean, - onChange: (Boolean) -> Unit, -) { - Row( - modifier = Modifier.fillMaxWidth(), - verticalAlignment = Alignment.CenterVertically, - ) { - Text(text = label, modifier = Modifier.padding(end = 12.dp)) - Switch(checked = checked, onCheckedChange = onChange) - } -} - -/** - * Reads the gesture flags back off the native map so logcat shows ground truth. - * - * TomTom marks `TomTomMap` as its own library group's, which is what Android - * Lint objects to. Reading a vendor's map object is the whole point here: the - * escape hatch `getMapViewHolder().map` exists so a sample can check what the - * SDK actually told the native map, and a diagnostic that trusted our own - * state instead would be worth nothing. - */ -@Suppress("RestrictedApi") -private fun report( - phase: String, - state: Any, -) { - val holder = (state as? com.mapconductor.core.map.MapViewStateInterface<*>)?.getMapViewHolder() - val map = holder?.map - val actual = - when (state) { - is TomTomMapViewState -> { - val ttMap = map as? com.tomtom.sdk.map.display.TomTomMap - if (ttMap == null) { - "map unavailable" - } else { - "scroll=${ttMap.isScrollEnabled} zoom=${ttMap.isZoomEnabled} " + - "rotate=${ttMap.isRotationEnabled} tilt=${ttMap.isTiltEnabled}" - } - } - - is com.mapconductor.googlemaps.GoogleMapViewState -> { - val ui = (map as? com.google.android.gms.maps.GoogleMap)?.uiSettings - if (ui == null) { - "map unavailable" - } else { - "scroll=${ui.isScrollGesturesEnabled} zoom=${ui.isZoomGesturesEnabled} " + - "rotate=${ui.isRotateGesturesEnabled} tilt=${ui.isTiltGesturesEnabled}" - } - } - - is com.mapconductor.maplibre.MapLibreViewState -> { - val ui = (map as? org.maplibre.android.maps.MapLibreMap)?.uiSettings - if (ui == null) { - "map unavailable" - } else { - "scroll=${ui.isScrollGesturesEnabled} zoom=${ui.isZoomGesturesEnabled} " + - "rotate=${ui.isRotateGesturesEnabled} tilt=${ui.isTiltGesturesEnabled}" - } - } - - else -> "applied (no native reader for ${state::class.simpleName})" - } - Log.i("MCUISettings", "$phase | ${state::class.simpleName} | $actual") -} +package com.mapconductor.example.pages.map.uisettings + +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.sizeIn +import androidx.compose.material3.Card +import androidx.compose.material3.Switch +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.collectAsState +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.unit.dp +import com.mapconductor.core.map.MapUISettings +import com.mapconductor.example.MapViewContainer +import com.mapconductor.example.ui.DefaultMapViewItems +import com.mapconductor.example.ui.DemoMapPageScaffold +import com.mapconductor.tomtom.TomTomMapViewState +import kotlin.time.Duration.Companion.milliseconds +import android.util.Log +import kotlinx.coroutines.delay + +/** + * Exercises [MapUISettings] against a live map. + * + * Four switches flip the gesture flags; after each change the page reads the + * values back off the provider's own map object and logs them under the + * `MCUISettings` tag, so a device run can be verified from logcat without having + * to touch the screen. On start it also cycles None -> Default automatically. + */ +@Composable +fun UISettingsMapPage( + modifier: Modifier = Modifier, + onToggleSidebar: () -> Unit = {}, +) { + val viewModel = remember { UISettingsMapPageViewModel() } + // A UI test presets the flags through an intent extra rather than tapping the + // switches, which is far more reliable than driving a Compose Switch by coordinate. + val preset = + if (com.mapconductor.example.MainActivity.gesturesExtra == "none") { + MapUISettings.None + } else { + null + } + + DemoMapPageScaffold( + menuItems = DefaultMapViewItems(viewModel.initCameraPosition), + onToggleSidebar = onToggleSidebar, + onMapViewStateChanged = viewModel::onMapViewChanged, + ) { paddingValues -> + val mapViewState = viewModel.mapViewState.collectAsState().value + + mapViewState?.let { state -> + // The flags live on the map state, not in this page: rememberXxxMapViewState + // saves them, so they survive a rotation. A page-local `remember` would + // come back all-true and overwrite the restored state. + // The intent preset is applied once per state (rememberSaveable keyed by its + // id), so a rotation does not re-apply it over what the user toggled since. + var presetApplied by rememberSaveable(state.id) { mutableStateOf(false) } + LaunchedEffect(state) { + if (!presetApplied && preset != null) state.uiSettings = preset + presetApplied = true + } + MapViewContainer( + state = state, + modifier = modifier, + onCameraMove = { c -> + Log.i("MCCamera", "%.5f,%.5f".format(c.position.latitude, c.position.longitude)) + }, + ) + + // Read back after every change, so manual toggles are verifiable too. + LaunchedEffect(state.uiSettings, state) { + delay(800.milliseconds) + report("settings=${state.uiSettings}", state) + } + } + + // ios / react と同じ左下配置(react の .control-panel、ios の bottomLeading と揃える) + Card( + modifier = + Modifier + .align(Alignment.BottomStart) + .padding( + bottom = paddingValues.calculateBottomPadding() + 16.dp, + start = 16.dp, + ).sizeIn(maxWidth = 360.dp), + ) { + Column(modifier = Modifier.padding(12.dp)) { + val state = mapViewState + val settings = state?.uiSettings ?: MapUISettings.Default + val update: (MapUISettings) -> Unit = { state?.uiSettings = it } + GestureSwitch("scrollGesture", settings.scrollGesture) { + update(settings.copy(scrollGesture = it)) + } + GestureSwitch("zoomGesture", settings.zoomGesture) { + update(settings.copy(zoomGesture = it)) + } + GestureSwitch("rotateGesture", settings.rotateGesture) { + update(settings.copy(rotateGesture = it)) + } + GestureSwitch("tiltGesture", settings.tiltGesture) { + update(settings.copy(tiltGesture = it)) + } + } + } + } +} + +@Composable +private fun GestureSwitch( + label: String, + checked: Boolean, + onChange: (Boolean) -> Unit, +) { + Row( + modifier = Modifier.fillMaxWidth(), + verticalAlignment = Alignment.CenterVertically, + ) { + Text(text = label, modifier = Modifier.padding(end = 12.dp)) + Switch(checked = checked, onCheckedChange = onChange) + } +} + +/** + * Reads the gesture flags back off the native map so logcat shows ground truth. + * + * TomTom marks `TomTomMap` as its own library group's, which is what Android + * Lint objects to. Reading a vendor's map object is the whole point here: the + * escape hatch `getMapViewHolder().map` exists so a sample can check what the + * SDK actually told the native map, and a diagnostic that trusted our own + * state instead would be worth nothing. + */ +@Suppress("RestrictedApi") +private fun report( + phase: String, + state: Any, +) { + val holder = (state as? com.mapconductor.core.map.MapViewStateInterface<*>)?.getMapViewHolder() + val map = holder?.map + val actual = + when (state) { + is TomTomMapViewState -> { + val ttMap = map as? com.tomtom.sdk.map.display.TomTomMap + if (ttMap == null) { + "map unavailable" + } else { + "scroll=${ttMap.isScrollEnabled} zoom=${ttMap.isZoomEnabled} " + + "rotate=${ttMap.isRotationEnabled} tilt=${ttMap.isTiltEnabled}" + } + } + + is com.mapconductor.googlemaps.GoogleMapViewState -> { + val ui = (map as? com.google.android.gms.maps.GoogleMap)?.uiSettings + if (ui == null) { + "map unavailable" + } else { + "scroll=${ui.isScrollGesturesEnabled} zoom=${ui.isZoomGesturesEnabled} " + + "rotate=${ui.isRotateGesturesEnabled} tilt=${ui.isTiltGesturesEnabled}" + } + } + + is com.mapconductor.maplibre.MapLibreViewState -> { + val ui = (map as? org.maplibre.android.maps.MapLibreMap)?.uiSettings + if (ui == null) { + "map unavailable" + } else { + "scroll=${ui.isScrollGesturesEnabled} zoom=${ui.isZoomGesturesEnabled} " + + "rotate=${ui.isRotateGesturesEnabled} tilt=${ui.isTiltGesturesEnabled}" + } + } + + else -> "applied (no native reader for ${state::class.simpleName})" + } + Log.i("MCUISettings", "$phase | ${state::class.simpleName} | $actual") +} diff --git a/example-app/src/main/java/com/mapconductor/example/pages/map/visibleregion/ZoomCalibrationPage.kt b/example-app/src/main/java/com/mapconductor/example/pages/map/visibleregion/ZoomCalibrationPage.kt index 08eca59f..c455beca 100644 --- a/example-app/src/main/java/com/mapconductor/example/pages/map/visibleregion/ZoomCalibrationPage.kt +++ b/example-app/src/main/java/com/mapconductor/example/pages/map/visibleregion/ZoomCalibrationPage.kt @@ -1,610 +1,610 @@ -package com.mapconductor.example.pages.map.visibleregion - -import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.Row -import androidx.compose.foundation.layout.Spacer -import androidx.compose.foundation.layout.fillMaxSize -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.height -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.layout.width -import androidx.compose.foundation.rememberScrollState -import androidx.compose.foundation.verticalScroll -import androidx.compose.material3.Button -import androidx.compose.material3.Card -import androidx.compose.material3.CardDefaults -import androidx.compose.material3.HorizontalDivider -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.OutlinedButton -import androidx.compose.material3.Slider -import androidx.compose.material3.Text -import androidx.compose.material3.TextButton -import androidx.compose.runtime.Composable -import androidx.compose.runtime.LaunchedEffect -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.remember -import androidx.compose.runtime.saveable.rememberSaveable -import androidx.compose.runtime.setValue -import androidx.compose.ui.Modifier -import androidx.compose.ui.text.font.FontFamily -import androidx.compose.ui.text.font.FontWeight -import androidx.compose.ui.unit.dp -import androidx.compose.ui.unit.sp -import com.mapconductor.arcgis.ArcGISMapView -import com.mapconductor.arcgis.rememberArcGISMapViewState -import com.mapconductor.core.features.GeoPoint -import com.mapconductor.core.map.MapCameraPosition -import com.mapconductor.core.spherical.WGS84Geodesic.computeDistanceBetween -import com.mapconductor.googlemaps.GoogleMapView -import com.mapconductor.googlemaps.rememberGoogleMapViewState -import android.annotation.SuppressLint - -@SuppressLint("DefaultLocale") -@Composable -fun ZoomCalibrationPage(onToggleSidebar: () -> Unit = {}) { - val testLocation = GeoPoint.fromLongLat(139.6917, 35.6895) // Tokyo Station - val testZoomLevels = - listOf( - 0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, - 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, - 15.0, 16.0, 17.0, 18.0, 10.0, 20.0, - ) - - var currentZoomLevel by rememberSaveable { mutableStateOf(0.0) } - var googleMapResults by rememberSaveable { mutableStateOf>(emptyMap()) } - var arcgisResults by rememberSaveable { mutableStateOf>(emptyMap()) } - var measurementInProgress by remember { mutableStateOf(false) } - var measurementMessage by remember { mutableStateOf("") } - // Map view states with initial camera position - val initialCameraPosition = - MapCameraPosition( - position = testLocation, - zoom = currentZoomLevel, - bearing = 0.0, - tilt = 0.0, - ) - - val googleMapViewState = - rememberGoogleMapViewState( - cameraPosition = initialCameraPosition, - ) - val arcGisMapViewState = - rememberArcGISMapViewState( - cameraPosition = initialCameraPosition, - ) - - // Update camera positions when zoom level changes - LaunchedEffect(currentZoomLevel) { - val newCameraPosition = - MapCameraPosition( - position = testLocation, - zoom = currentZoomLevel, - bearing = 0.0, - tilt = 0.0, - ) - googleMapViewState.moveCameraTo(newCameraPosition) - arcGisMapViewState.moveCameraTo(newCameraPosition) - } - - Column( - modifier = - Modifier - .fillMaxSize() - .padding(16.dp) - .verticalScroll(rememberScrollState()), - ) { - Card( - modifier = Modifier.fillMaxWidth(), - elevation = CardDefaults.cardElevation(defaultElevation = 8.dp), - ) { - Column( - modifier = Modifier.padding(16.dp), - ) { - Text( - text = "Zoom Level Calibration Tool", - fontSize = 20.sp, - fontWeight = FontWeight.Bold, - ) - - Spacer(modifier = Modifier.height(8.dp)) - - Text( - text = "Location: Tokyo Station (35.6895°N, 139.6917°E)", - fontSize = 14.sp, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - - Spacer(modifier = Modifier.height(16.dp)) - - Text( - text = "Current Zoom Level: ${String.format("%.1f", currentZoomLevel)}", - fontSize = 16.sp, - fontWeight = FontWeight.Medium, - ) - - Slider( - value = currentZoomLevel.toFloat(), - onValueChange = { currentZoomLevel = it.toDouble() }, - valueRange = 0f..20f, - steps = 19, - modifier = Modifier.fillMaxWidth(), - ) - } - } - - Spacer(modifier = Modifier.height(16.dp)) - - // Map views section - Text( - text = "Live Map Comparison (Zoom: ${String.format("%.1f", currentZoomLevel)})", - fontSize = 16.sp, - fontWeight = FontWeight.Medium, - modifier = Modifier.padding(bottom = 8.dp), - ) - - Row( - modifier = - Modifier - .fillMaxWidth() - .height(280.dp), - ) { - Column( - modifier = Modifier.weight(1.5f), - ) { - Text( - text = "Google Maps", - fontSize = 14.sp, - fontWeight = FontWeight.Medium, - modifier = Modifier.padding(bottom = 4.dp), - ) - GoogleMapView( - state = googleMapViewState, - modifier = Modifier.fillMaxSize(), - ) - } - - Spacer(modifier = Modifier.width(16.dp)) - - Column( - modifier = Modifier.weight(1.5f), - ) { - Text( - text = "ArcGIS", - fontSize = 14.sp, - fontWeight = FontWeight.Medium, - modifier = Modifier.padding(bottom = 4.dp), - ) - ArcGISMapView( - state = arcGisMapViewState, - modifier = Modifier.fillMaxSize(), - ) - } - } - - Spacer(modifier = Modifier.height(16.dp)) - - Row( - modifier = Modifier.fillMaxWidth(), - horizontalArrangement = Arrangement.spacedBy(8.dp), - ) { - Button( - onClick = { - // Extract visible region data from Google Maps view - googleMapViewState.cameraPosition.visibleRegion?.let { visibleRegion -> - val info = createVisibleRegionInfo(visibleRegion) - googleMapResults = googleMapResults + (currentZoomLevel to info) - measurementMessage = - String.format("Google Maps data captured: %.2f, %.2f km", info.widthKm, info.heightKm) - measurementInProgress = true - } ?: run { - measurementMessage = - "Google Maps visible region not available yet. Please wait for map to load." - measurementInProgress = true - } - }, - enabled = !measurementInProgress, - modifier = Modifier.weight(1f), - ) { - Text("Capture Google Maps") - } - - Button( - onClick = { - // Extract visible region data from ArcGIS view - arcGisMapViewState.cameraPosition.visibleRegion?.let { visibleRegion -> - val info = createVisibleRegionInfo(visibleRegion) - arcgisResults = arcgisResults + (currentZoomLevel to info) - measurementMessage = - "ArcGIS data captured: ${String.format("%.2f", info.widthKm)} × ${ - String.format( - "%.2f", - info.heightKm - ) - } km" - measurementInProgress = true - } ?: run { - measurementMessage = "ArcGIS visible region not available yet. Please wait for map to load." - measurementInProgress = true - } - }, - enabled = !measurementInProgress, - modifier = Modifier.weight(1f), - ) { - Text("Capture ArcGIS") - } - } - - Spacer(modifier = Modifier.height(16.dp)) - - CalibrationResultsTable( - testZoomLevels = testZoomLevels, - googleMapResults = googleMapResults, - arcgisResults = arcgisResults, - ) - - Spacer(modifier = Modifier.height(16.dp)) - - CalibrationRecommendations( - googleMapResults = googleMapResults, - arcgisResults = arcgisResults, - ) - - // Clear all data button - if (googleMapResults.isNotEmpty() || arcgisResults.isNotEmpty()) { - Spacer(modifier = Modifier.height(16.dp)) - - Row( - modifier = Modifier.fillMaxWidth(), - horizontalArrangement = Arrangement.Center, - ) { - OutlinedButton( - onClick = { - googleMapResults = emptyMap() - arcgisResults = emptyMap() - measurementMessage = "All calibration data cleared" - measurementInProgress = true - }, - ) { - Text("Clear All Data") - } - } - } - - // Instructions for better calibration - Spacer(modifier = Modifier.height(16.dp)) - - Card( - colors = - CardDefaults.cardColors( - containerColor = MaterialTheme.colorScheme.surfaceVariant, - ), - ) { - Column( - modifier = Modifier.padding(16.dp), - ) { - Text( - text = "Calibration Instructions", - fontSize = 16.sp, - fontWeight = FontWeight.Bold, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - - Spacer(modifier = Modifier.height(8.dp)) - - Text( - text = - "• Adjust zoom level with the slider above\n" + - "• Wait for both maps to load completely\n" + - "• Tap 'Capture' buttons to automatically extract visible region data\n" + - "• Collect data for multiple zoom levels to improve accuracy\n" + - "• Compare the results in the table below", - fontSize = 14.sp, - color = MaterialTheme.colorScheme.onSurfaceVariant, - lineHeight = 20.sp, - ) - } - } - - if (measurementInProgress && measurementMessage.isNotEmpty()) { - Spacer(modifier = Modifier.height(16.dp)) - Card( - colors = - CardDefaults.cardColors( - containerColor = - if (measurementMessage.contains("captured")) { - MaterialTheme.colorScheme.primaryContainer - } else { - MaterialTheme.colorScheme.errorContainer - }, - ), - ) { - Text( - text = measurementMessage, - modifier = Modifier.padding(16.dp), - color = - if (measurementMessage.contains("captured")) { - MaterialTheme.colorScheme.onPrimaryContainer - } else { - MaterialTheme.colorScheme.onErrorContainer - }, - ) - - Row( - modifier = - Modifier - .fillMaxWidth() - .padding(horizontal = 16.dp, vertical = 8.dp), - horizontalArrangement = Arrangement.End, - ) { - TextButton( - onClick = { - measurementInProgress = false - measurementMessage = "" - }, - ) { - Text("OK") - } - } - } - } - - // Auto-dismiss successful measurements after 3 seconds - LaunchedEffect(measurementMessage) { - if (measurementMessage.contains("captured")) { - kotlinx.coroutines.delay(3000) - measurementInProgress = false - measurementMessage = "" - } - } - } -} - -@Composable -fun CalibrationResultsTable( - testZoomLevels: List, - googleMapResults: Map, - arcgisResults: Map, -) { - Card( - modifier = Modifier.fillMaxWidth(), - elevation = CardDefaults.cardElevation(defaultElevation = 4.dp), - ) { - Column( - modifier = Modifier.padding(16.dp), - ) { - Text( - text = "Calibration Results", - fontSize = 18.sp, - fontWeight = FontWeight.Bold, - ) - - Spacer(modifier = Modifier.height(12.dp)) - - // Table headers - Row( - modifier = Modifier.fillMaxWidth(), - horizontalArrangement = Arrangement.SpaceBetween, - ) { - Text("Zoom", fontWeight = FontWeight.Bold, modifier = Modifier.weight(1f)) - Text("Google Maps (km)", fontWeight = FontWeight.Bold, modifier = Modifier.weight(2f)) - Text("ArcGIS (km)", fontWeight = FontWeight.Bold, modifier = Modifier.weight(2f)) - Text("Ratio", fontWeight = FontWeight.Bold, modifier = Modifier.weight(1f)) - } - - HorizontalDivider(modifier = Modifier.padding(vertical = 8.dp)) - - testZoomLevels.forEach { zoomLevel -> - val googleData = googleMapResults[zoomLevel] - val arcgisData = arcgisResults[zoomLevel] - val ratio = - if (googleData != null && arcgisData != null) { - val googleArea = googleData.widthKm * googleData.heightKm - val arcgisArea = arcgisData.widthKm * arcgisData.heightKm - if (arcgisArea > 0) googleArea / arcgisArea else 0.0 - } else { - null - } - - Row( - modifier = Modifier.fillMaxWidth(), - horizontalArrangement = Arrangement.SpaceBetween, - ) { - Text( - text = String.format("%.1f", zoomLevel), - fontFamily = FontFamily.Monospace, - modifier = Modifier.weight(1f), - ) - Text( - text = - googleData?.let { - "${String.format("%.1f", it.widthKm)} × ${String.format("%.1f", it.heightKm)}" - } - ?: "-", - fontFamily = FontFamily.Monospace, - modifier = Modifier.weight(2f), - ) - Text( - text = - arcgisData?.let { - "${String.format("%.1f", it.widthKm)} × ${String.format("%.1f", it.heightKm)}" - } - ?: "-", - fontFamily = FontFamily.Monospace, - modifier = Modifier.weight(2f), - ) - Text( - text = ratio?.let { String.format("%.2f", it) } ?: "-", - fontFamily = FontFamily.Monospace, - modifier = Modifier.weight(1f), - ) - } - } - } - } -} - -@Composable -fun CalibrationRecommendations( - googleMapResults: Map, - arcgisResults: Map, -) { - if (googleMapResults.isEmpty() || arcgisResults.isEmpty()) return - - val averageRatio = calculateAverageRatio(googleMapResults, arcgisResults) - val currentZoom0Altitude = 198_506_928.2 // Use current value from ZoomAltitudeConverter - val recommendedZoom0Altitude = currentZoom0Altitude / averageRatio // Invert the ratio! - - Card( - modifier = Modifier.fillMaxWidth(), - colors = - CardDefaults.cardColors( - containerColor = MaterialTheme.colorScheme.primaryContainer, - ), - ) { - Column( - modifier = Modifier.padding(16.dp), - ) { - Text( - text = "Calibration Recommendations", - fontSize = 18.sp, - fontWeight = FontWeight.Bold, - color = MaterialTheme.colorScheme.onPrimaryContainer, - ) - - Spacer(modifier = Modifier.height(12.dp)) - - Text( - text = "Average Area Ratio (ArcGIS/Google): ${String.format("%.3f", averageRatio)}", - fontFamily = FontFamily.Monospace, - ) - - Text( - text = - if (averageRatio > 1.0) { - "ArcGIS shows ${String.format("%.1f", (averageRatio - 1.0) * 100)}% larger area (zoom too low)" - } else { - "ArcGIS shows ${ - String.format( - "%.1f", - (1.0 - averageRatio) * 100 - ) - }% smaller area (zoom too high)" - }, - fontSize = 12.sp, - color = MaterialTheme.colorScheme.onPrimaryContainer, - ) - - Text( - text = "Current DEFAULT_ZOOM0_ALTITUDE: ${String.format("%.0f", currentZoom0Altitude)}", - fontFamily = FontFamily.Monospace, - ) - - Text( - text = "Recommended DEFAULT_ZOOM0_ALTITUDE: ${String.format("%.0f", recommendedZoom0Altitude)}", - fontFamily = FontFamily.Monospace, - fontWeight = FontWeight.Bold, - color = MaterialTheme.colorScheme.primary, - ) - - Spacer(modifier = Modifier.height(8.dp)) - - val percentChange = ((recommendedZoom0Altitude - currentZoom0Altitude) / currentZoom0Altitude) * 100 - Text( - text = "Change: ${if (percentChange > 0) "+" else ""}${String.format("%.1f", percentChange)}%", - fontWeight = FontWeight.Medium, - ) - - Spacer(modifier = Modifier.height(12.dp)) - - Card( - colors = - CardDefaults.cardColors( - containerColor = MaterialTheme.colorScheme.surface, - ), - ) { - Column( - modifier = Modifier.padding(12.dp), - ) { - Text( - text = "Code to Update:", - fontWeight = FontWeight.Bold, - fontSize = 14.sp, - ) - - Spacer(modifier = Modifier.height(8.dp)) - - Text( - text = "const val DEFAULT_ZOOM0_ALTITUDE = ${String.format("%.1f", recommendedZoom0Altitude)}", - fontFamily = FontFamily.Monospace, - fontSize = 12.sp, - color = MaterialTheme.colorScheme.primary, - ) - - Text( - text = "// Location: ZoomAltitudeConverter.kt", - fontFamily = FontFamily.Monospace, - fontSize = 10.sp, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - } - } - } - } -} - -private fun calculateAverageRatio( - googleMapResults: Map, - arcgisResults: Map, -): Double { - val ratios = mutableListOf() - - googleMapResults.forEach { (zoomLevel, googleData) -> - arcgisResults[zoomLevel]?.let { arcgisData -> - val googleArea = googleData.widthKm * googleData.heightKm - val arcgisArea = arcgisData.widthKm * arcgisData.heightKm - if (arcgisArea > 0 && googleArea > 0) { - // Calculate the ratio of ArcGIS area to Google area - // If ArcGIS shows larger area, ratio > 1.0 (zoom conversion too low) - // If ArcGIS shows smaller area, ratio < 1.0 (zoom conversion too high) - val areaRatio = arcgisArea / googleArea - ratios.add(areaRatio) - } - } - } - - return if (ratios.isEmpty()) 1.0 else ratios.average() -} - -/** - * 表示領域の実寸(km)。ズーム較正はプロバイダ間で「同じズームのときの見えている - * 広さ」を比べるページなので、必要なのは幅と高さだけ。 - * - * 以前は表示領域サンプルと共有していたが、あちらを react と同じ「数値を並べるだけ」の - * 形に揃えた際に使わなくなったので、唯一の利用者であるここへ移した。 - */ -data class VisibleRegionInfo( - val widthKm: Double, - val heightKm: Double, -) - -private fun createVisibleRegionInfo(visibleRegion: com.mapconductor.core.map.VisibleRegion): VisibleRegionInfo { - val bounds = visibleRegion.bounds - if (bounds.isEmpty || bounds.southWest == null || bounds.northEast == null) { - return VisibleRegionInfo(widthKm = 0.0, heightKm = 0.0) - } - - val widthKm = - computeDistanceBetween( - bounds.southWest!!, - GeoPoint(bounds.southWest!!.latitude, bounds.northEast!!.longitude), - ) - val heightKm = - computeDistanceBetween( - bounds.southWest!!, - GeoPoint(bounds.northEast!!.latitude, bounds.southWest!!.longitude), - ) - - return VisibleRegionInfo(widthKm = widthKm, heightKm = heightKm) -} +package com.mapconductor.example.pages.map.visibleregion + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.verticalScroll +import androidx.compose.material3.Button +import androidx.compose.material3.Card +import androidx.compose.material3.CardDefaults +import androidx.compose.material3.HorizontalDivider +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedButton +import androidx.compose.material3.Slider +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.text.font.FontFamily +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import com.mapconductor.arcgis.ArcGISMapView +import com.mapconductor.arcgis.rememberArcGISMapViewState +import com.mapconductor.core.features.GeoPoint +import com.mapconductor.core.map.MapCameraPosition +import com.mapconductor.core.spherical.WGS84Geodesic.computeDistanceBetween +import com.mapconductor.googlemaps.GoogleMapView +import com.mapconductor.googlemaps.rememberGoogleMapViewState +import android.annotation.SuppressLint + +@SuppressLint("DefaultLocale") +@Composable +fun ZoomCalibrationPage(onToggleSidebar: () -> Unit = {}) { + val testLocation = GeoPoint.fromLongLat(139.6917, 35.6895) // Tokyo Station + val testZoomLevels = + listOf( + 0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, + 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, + 15.0, 16.0, 17.0, 18.0, 10.0, 20.0, + ) + + var currentZoomLevel by rememberSaveable { mutableStateOf(0.0) } + var googleMapResults by rememberSaveable { mutableStateOf>(emptyMap()) } + var arcgisResults by rememberSaveable { mutableStateOf>(emptyMap()) } + var measurementInProgress by remember { mutableStateOf(false) } + var measurementMessage by remember { mutableStateOf("") } + // Map view states with initial camera position + val initialCameraPosition = + MapCameraPosition( + position = testLocation, + zoom = currentZoomLevel, + bearing = 0.0, + tilt = 0.0, + ) + + val googleMapViewState = + rememberGoogleMapViewState( + cameraPosition = initialCameraPosition, + ) + val arcGisMapViewState = + rememberArcGISMapViewState( + cameraPosition = initialCameraPosition, + ) + + // Update camera positions when zoom level changes + LaunchedEffect(currentZoomLevel) { + val newCameraPosition = + MapCameraPosition( + position = testLocation, + zoom = currentZoomLevel, + bearing = 0.0, + tilt = 0.0, + ) + googleMapViewState.moveCameraTo(newCameraPosition) + arcGisMapViewState.moveCameraTo(newCameraPosition) + } + + Column( + modifier = + Modifier + .fillMaxSize() + .padding(16.dp) + .verticalScroll(rememberScrollState()), + ) { + Card( + modifier = Modifier.fillMaxWidth(), + elevation = CardDefaults.cardElevation(defaultElevation = 8.dp), + ) { + Column( + modifier = Modifier.padding(16.dp), + ) { + Text( + text = "Zoom Level Calibration Tool", + fontSize = 20.sp, + fontWeight = FontWeight.Bold, + ) + + Spacer(modifier = Modifier.height(8.dp)) + + Text( + text = "Location: Tokyo Station (35.6895°N, 139.6917°E)", + fontSize = 14.sp, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + + Spacer(modifier = Modifier.height(16.dp)) + + Text( + text = "Current Zoom Level: ${String.format("%.1f", currentZoomLevel)}", + fontSize = 16.sp, + fontWeight = FontWeight.Medium, + ) + + Slider( + value = currentZoomLevel.toFloat(), + onValueChange = { currentZoomLevel = it.toDouble() }, + valueRange = 0f..20f, + steps = 19, + modifier = Modifier.fillMaxWidth(), + ) + } + } + + Spacer(modifier = Modifier.height(16.dp)) + + // Map views section + Text( + text = "Live Map Comparison (Zoom: ${String.format("%.1f", currentZoomLevel)})", + fontSize = 16.sp, + fontWeight = FontWeight.Medium, + modifier = Modifier.padding(bottom = 8.dp), + ) + + Row( + modifier = + Modifier + .fillMaxWidth() + .height(280.dp), + ) { + Column( + modifier = Modifier.weight(1.5f), + ) { + Text( + text = "Google Maps", + fontSize = 14.sp, + fontWeight = FontWeight.Medium, + modifier = Modifier.padding(bottom = 4.dp), + ) + GoogleMapView( + state = googleMapViewState, + modifier = Modifier.fillMaxSize(), + ) + } + + Spacer(modifier = Modifier.width(16.dp)) + + Column( + modifier = Modifier.weight(1.5f), + ) { + Text( + text = "ArcGIS", + fontSize = 14.sp, + fontWeight = FontWeight.Medium, + modifier = Modifier.padding(bottom = 4.dp), + ) + ArcGISMapView( + state = arcGisMapViewState, + modifier = Modifier.fillMaxSize(), + ) + } + } + + Spacer(modifier = Modifier.height(16.dp)) + + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.spacedBy(8.dp), + ) { + Button( + onClick = { + // Extract visible region data from Google Maps view + googleMapViewState.cameraPosition.visibleRegion?.let { visibleRegion -> + val info = createVisibleRegionInfo(visibleRegion) + googleMapResults = googleMapResults + (currentZoomLevel to info) + measurementMessage = + String.format("Google Maps data captured: %.2f, %.2f km", info.widthKm, info.heightKm) + measurementInProgress = true + } ?: run { + measurementMessage = + "Google Maps visible region not available yet. Please wait for map to load." + measurementInProgress = true + } + }, + enabled = !measurementInProgress, + modifier = Modifier.weight(1f), + ) { + Text("Capture Google Maps") + } + + Button( + onClick = { + // Extract visible region data from ArcGIS view + arcGisMapViewState.cameraPosition.visibleRegion?.let { visibleRegion -> + val info = createVisibleRegionInfo(visibleRegion) + arcgisResults = arcgisResults + (currentZoomLevel to info) + measurementMessage = + "ArcGIS data captured: ${String.format("%.2f", info.widthKm)} × ${ + String.format( + "%.2f", + info.heightKm, + ) + } km" + measurementInProgress = true + } ?: run { + measurementMessage = "ArcGIS visible region not available yet. Please wait for map to load." + measurementInProgress = true + } + }, + enabled = !measurementInProgress, + modifier = Modifier.weight(1f), + ) { + Text("Capture ArcGIS") + } + } + + Spacer(modifier = Modifier.height(16.dp)) + + CalibrationResultsTable( + testZoomLevels = testZoomLevels, + googleMapResults = googleMapResults, + arcgisResults = arcgisResults, + ) + + Spacer(modifier = Modifier.height(16.dp)) + + CalibrationRecommendations( + googleMapResults = googleMapResults, + arcgisResults = arcgisResults, + ) + + // Clear all data button + if (googleMapResults.isNotEmpty() || arcgisResults.isNotEmpty()) { + Spacer(modifier = Modifier.height(16.dp)) + + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.Center, + ) { + OutlinedButton( + onClick = { + googleMapResults = emptyMap() + arcgisResults = emptyMap() + measurementMessage = "All calibration data cleared" + measurementInProgress = true + }, + ) { + Text("Clear All Data") + } + } + } + + // Instructions for better calibration + Spacer(modifier = Modifier.height(16.dp)) + + Card( + colors = + CardDefaults.cardColors( + containerColor = MaterialTheme.colorScheme.surfaceVariant, + ), + ) { + Column( + modifier = Modifier.padding(16.dp), + ) { + Text( + text = "Calibration Instructions", + fontSize = 16.sp, + fontWeight = FontWeight.Bold, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + + Spacer(modifier = Modifier.height(8.dp)) + + Text( + text = + "• Adjust zoom level with the slider above\n" + + "• Wait for both maps to load completely\n" + + "• Tap 'Capture' buttons to automatically extract visible region data\n" + + "• Collect data for multiple zoom levels to improve accuracy\n" + + "• Compare the results in the table below", + fontSize = 14.sp, + color = MaterialTheme.colorScheme.onSurfaceVariant, + lineHeight = 20.sp, + ) + } + } + + if (measurementInProgress && measurementMessage.isNotEmpty()) { + Spacer(modifier = Modifier.height(16.dp)) + Card( + colors = + CardDefaults.cardColors( + containerColor = + if (measurementMessage.contains("captured")) { + MaterialTheme.colorScheme.primaryContainer + } else { + MaterialTheme.colorScheme.errorContainer + }, + ), + ) { + Text( + text = measurementMessage, + modifier = Modifier.padding(16.dp), + color = + if (measurementMessage.contains("captured")) { + MaterialTheme.colorScheme.onPrimaryContainer + } else { + MaterialTheme.colorScheme.onErrorContainer + }, + ) + + Row( + modifier = + Modifier + .fillMaxWidth() + .padding(horizontal = 16.dp, vertical = 8.dp), + horizontalArrangement = Arrangement.End, + ) { + TextButton( + onClick = { + measurementInProgress = false + measurementMessage = "" + }, + ) { + Text("OK") + } + } + } + } + + // Auto-dismiss successful measurements after 3 seconds + LaunchedEffect(measurementMessage) { + if (measurementMessage.contains("captured")) { + kotlinx.coroutines.delay(3000) + measurementInProgress = false + measurementMessage = "" + } + } + } +} + +@Composable +fun CalibrationResultsTable( + testZoomLevels: List, + googleMapResults: Map, + arcgisResults: Map, +) { + Card( + modifier = Modifier.fillMaxWidth(), + elevation = CardDefaults.cardElevation(defaultElevation = 4.dp), + ) { + Column( + modifier = Modifier.padding(16.dp), + ) { + Text( + text = "Calibration Results", + fontSize = 18.sp, + fontWeight = FontWeight.Bold, + ) + + Spacer(modifier = Modifier.height(12.dp)) + + // Table headers + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.SpaceBetween, + ) { + Text("Zoom", fontWeight = FontWeight.Bold, modifier = Modifier.weight(1f)) + Text("Google Maps (km)", fontWeight = FontWeight.Bold, modifier = Modifier.weight(2f)) + Text("ArcGIS (km)", fontWeight = FontWeight.Bold, modifier = Modifier.weight(2f)) + Text("Ratio", fontWeight = FontWeight.Bold, modifier = Modifier.weight(1f)) + } + + HorizontalDivider(modifier = Modifier.padding(vertical = 8.dp)) + + testZoomLevels.forEach { zoomLevel -> + val googleData = googleMapResults[zoomLevel] + val arcgisData = arcgisResults[zoomLevel] + val ratio = + if (googleData != null && arcgisData != null) { + val googleArea = googleData.widthKm * googleData.heightKm + val arcgisArea = arcgisData.widthKm * arcgisData.heightKm + if (arcgisArea > 0) googleArea / arcgisArea else 0.0 + } else { + null + } + + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.SpaceBetween, + ) { + Text( + text = String.format("%.1f", zoomLevel), + fontFamily = FontFamily.Monospace, + modifier = Modifier.weight(1f), + ) + Text( + text = + googleData?.let { + "${String.format("%.1f", it.widthKm)} × ${String.format("%.1f", it.heightKm)}" + } + ?: "-", + fontFamily = FontFamily.Monospace, + modifier = Modifier.weight(2f), + ) + Text( + text = + arcgisData?.let { + "${String.format("%.1f", it.widthKm)} × ${String.format("%.1f", it.heightKm)}" + } + ?: "-", + fontFamily = FontFamily.Monospace, + modifier = Modifier.weight(2f), + ) + Text( + text = ratio?.let { String.format("%.2f", it) } ?: "-", + fontFamily = FontFamily.Monospace, + modifier = Modifier.weight(1f), + ) + } + } + } + } +} + +@Composable +fun CalibrationRecommendations( + googleMapResults: Map, + arcgisResults: Map, +) { + if (googleMapResults.isEmpty() || arcgisResults.isEmpty()) return + + val averageRatio = calculateAverageRatio(googleMapResults, arcgisResults) + val currentZoom0Altitude = 198_506_928.2 // Use current value from ZoomAltitudeConverter + val recommendedZoom0Altitude = currentZoom0Altitude / averageRatio // Invert the ratio! + + Card( + modifier = Modifier.fillMaxWidth(), + colors = + CardDefaults.cardColors( + containerColor = MaterialTheme.colorScheme.primaryContainer, + ), + ) { + Column( + modifier = Modifier.padding(16.dp), + ) { + Text( + text = "Calibration Recommendations", + fontSize = 18.sp, + fontWeight = FontWeight.Bold, + color = MaterialTheme.colorScheme.onPrimaryContainer, + ) + + Spacer(modifier = Modifier.height(12.dp)) + + Text( + text = "Average Area Ratio (ArcGIS/Google): ${String.format("%.3f", averageRatio)}", + fontFamily = FontFamily.Monospace, + ) + + Text( + text = + if (averageRatio > 1.0) { + "ArcGIS shows ${String.format("%.1f", (averageRatio - 1.0) * 100)}% larger area (zoom too low)" + } else { + "ArcGIS shows ${ + String.format( + "%.1f", + (1.0 - averageRatio) * 100, + ) + }% smaller area (zoom too high)" + }, + fontSize = 12.sp, + color = MaterialTheme.colorScheme.onPrimaryContainer, + ) + + Text( + text = "Current DEFAULT_ZOOM0_ALTITUDE: ${String.format("%.0f", currentZoom0Altitude)}", + fontFamily = FontFamily.Monospace, + ) + + Text( + text = "Recommended DEFAULT_ZOOM0_ALTITUDE: ${String.format("%.0f", recommendedZoom0Altitude)}", + fontFamily = FontFamily.Monospace, + fontWeight = FontWeight.Bold, + color = MaterialTheme.colorScheme.primary, + ) + + Spacer(modifier = Modifier.height(8.dp)) + + val percentChange = ((recommendedZoom0Altitude - currentZoom0Altitude) / currentZoom0Altitude) * 100 + Text( + text = "Change: ${if (percentChange > 0) "+" else ""}${String.format("%.1f", percentChange)}%", + fontWeight = FontWeight.Medium, + ) + + Spacer(modifier = Modifier.height(12.dp)) + + Card( + colors = + CardDefaults.cardColors( + containerColor = MaterialTheme.colorScheme.surface, + ), + ) { + Column( + modifier = Modifier.padding(12.dp), + ) { + Text( + text = "Code to Update:", + fontWeight = FontWeight.Bold, + fontSize = 14.sp, + ) + + Spacer(modifier = Modifier.height(8.dp)) + + Text( + text = "const val DEFAULT_ZOOM0_ALTITUDE = ${String.format("%.1f", recommendedZoom0Altitude)}", + fontFamily = FontFamily.Monospace, + fontSize = 12.sp, + color = MaterialTheme.colorScheme.primary, + ) + + Text( + text = "// Location: ZoomAltitudeConverter.kt", + fontFamily = FontFamily.Monospace, + fontSize = 10.sp, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + } + } + } +} + +private fun calculateAverageRatio( + googleMapResults: Map, + arcgisResults: Map, +): Double { + val ratios = mutableListOf() + + googleMapResults.forEach { (zoomLevel, googleData) -> + arcgisResults[zoomLevel]?.let { arcgisData -> + val googleArea = googleData.widthKm * googleData.heightKm + val arcgisArea = arcgisData.widthKm * arcgisData.heightKm + if (arcgisArea > 0 && googleArea > 0) { + // Calculate the ratio of ArcGIS area to Google area + // If ArcGIS shows larger area, ratio > 1.0 (zoom conversion too low) + // If ArcGIS shows smaller area, ratio < 1.0 (zoom conversion too high) + val areaRatio = arcgisArea / googleArea + ratios.add(areaRatio) + } + } + } + + return if (ratios.isEmpty()) 1.0 else ratios.average() +} + +/** + * 表示領域の実寸(km)。ズーム較正はプロバイダ間で「同じズームのときの見えている + * 広さ」を比べるページなので、必要なのは幅と高さだけ。 + * + * 以前は表示領域サンプルと共有していたが、あちらを react と同じ「数値を並べるだけ」の + * 形に揃えた際に使わなくなったので、唯一の利用者であるここへ移した。 + */ +data class VisibleRegionInfo( + val widthKm: Double, + val heightKm: Double, +) + +private fun createVisibleRegionInfo(visibleRegion: com.mapconductor.core.map.VisibleRegion): VisibleRegionInfo { + val bounds = visibleRegion.bounds + if (bounds.isEmpty || bounds.southWest == null || bounds.northEast == null) { + return VisibleRegionInfo(widthKm = 0.0, heightKm = 0.0) + } + + val widthKm = + computeDistanceBetween( + bounds.southWest!!, + GeoPoint(bounds.southWest!!.latitude, bounds.northEast!!.longitude), + ) + val heightKm = + computeDistanceBetween( + bounds.southWest!!, + GeoPoint(bounds.northEast!!.latitude, bounds.southWest!!.longitude), + ) + + return VisibleRegionInfo(widthKm = widthKm, heightKm = heightKm) +} diff --git a/example-app/src/main/java/com/mapconductor/example/pages/marker/labelposition/MarkerLabelPositionPage.kt b/example-app/src/main/java/com/mapconductor/example/pages/marker/labelposition/MarkerLabelPositionPage.kt index fc210117..9f6ead83 100644 --- a/example-app/src/main/java/com/mapconductor/example/pages/marker/labelposition/MarkerLabelPositionPage.kt +++ b/example-app/src/main/java/com/mapconductor/example/pages/marker/labelposition/MarkerLabelPositionPage.kt @@ -1,103 +1,101 @@ -package com.mapconductor.example.pages.marker.labelposition - -import androidx.compose.material3.Text -import androidx.compose.runtime.Composable -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.remember -import androidx.compose.runtime.setValue -import androidx.compose.ui.graphics.Color -import androidx.compose.ui.text.font.FontFamily -import com.mapconductor.compose.info.InfoBubble -import com.mapconductor.compose.marker.Marker -import com.mapconductor.core.features.GeoPoint -import com.mapconductor.core.map.MapCameraPosition -import com.mapconductor.core.map.MapViewStateInterface -import com.mapconductor.core.marker.DefaultMarkerIcon -import com.mapconductor.core.marker.MarkerState -import com.mapconductor.core.marker.OnMarkerEventHandler -import com.mapconductor.example.MapViewContainer -import com.mapconductor.example.ui.DefaultMapViewItems -import com.mapconductor.example.ui.DemoMapPageScaffold - -// 信州大学(松本キャンパス)周辺に 3 × 3 で並べ、それぞれ違う labelPosition を付ける。 -// react-sdk の marker-label-position、ios-sdk の MarkerLabelPositionMapComponent と同じ配置。 -private val CENTER = GeoPoint.fromLatLong(36.2526, 137.9828) -private const val STEP_LATITUDE = 0.004 -private const val STEP_LONGITUDE = 0.007 - -private val POSITIONS = - listOf( - listOf("left top", "center top", "right top"), - listOf("left center", "center center", "right center"), - listOf("left bottom", "center bottom", "right bottom"), - ) - -@Composable -fun MarkerLabelPositionPage( - onToggleSidebar: () -> Unit = {}, -) { - val initCameraPosition = - MapCameraPosition( - position = CENTER, - zoom = 14.0, - ) - var selectedId by remember { mutableStateOf(null) } - var mapViewState by remember { mutableStateOf?>(null) } - val onMarkerClick: OnMarkerEventHandler = { markerState -> selectedId = markerState.id } - val markerStates = - remember { - POSITIONS.flatMapIndexed { rowIndex, row -> - row.mapIndexed { columnIndex, labelPosition -> - MarkerState( - id = labelPosition, - position = - GeoPoint.fromLatLong( - CENTER.latitude + (1 - rowIndex) * STEP_LATITUDE, - CENTER.longitude + (columnIndex - 1) * STEP_LONGITUDE, - ), - icon = - DefaultMarkerIcon( - label = if (labelPosition == "center center") "信" else "信州大学", - labelPosition = labelPosition, - debug = true, - ), - extra = labelPosition, - onClick = onMarkerClick, - ) - } - } - } - - DemoMapPageScaffold( - menuItems = DefaultMapViewItems(initCameraPosition), - onToggleSidebar = onToggleSidebar, - onMapViewStateChanged = { state -> - @Suppress("UNCHECKED_CAST") - mapViewState = state as MapViewStateInterface - }, - ) { - mapViewState?.let { - MapViewContainer( - state = mapViewState, - onMapClick = { selectedId = null }, - ) { - markerStates.forEach { markerState -> - Marker(markerState) - if (markerState.id == selectedId) { - InfoBubble( - marker = markerState, - bubbleColor = Color.White, - borderColor = Color.Black, - ) { - Text( - text = "labelPosition: \"${markerState.extra}\"", - fontFamily = FontFamily.Monospace, - ) - } - } - } - } - } - } -} +package com.mapconductor.example.pages.marker.labelposition + +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.text.font.FontFamily +import com.mapconductor.compose.info.InfoBubble +import com.mapconductor.compose.marker.Marker +import com.mapconductor.core.features.GeoPoint +import com.mapconductor.core.map.MapCameraPosition +import com.mapconductor.core.map.MapViewStateInterface +import com.mapconductor.core.marker.DefaultMarkerIcon +import com.mapconductor.core.marker.MarkerState +import com.mapconductor.core.marker.OnMarkerEventHandler +import com.mapconductor.example.MapViewContainer +import com.mapconductor.example.ui.DefaultMapViewItems +import com.mapconductor.example.ui.DemoMapPageScaffold + +// 信州大学(松本キャンパス)周辺に 3 × 3 で並べ、それぞれ違う labelPosition を付ける。 +// react-sdk の marker-label-position、ios-sdk の MarkerLabelPositionMapComponent と同じ配置。 +private val CENTER = GeoPoint.fromLatLong(36.2526, 137.9828) +private const val STEP_LATITUDE = 0.004 +private const val STEP_LONGITUDE = 0.007 + +private val POSITIONS = + listOf( + listOf("left top", "center top", "right top"), + listOf("left center", "center center", "right center"), + listOf("left bottom", "center bottom", "right bottom"), + ) + +@Composable +fun MarkerLabelPositionPage(onToggleSidebar: () -> Unit = {}) { + val initCameraPosition = + MapCameraPosition( + position = CENTER, + zoom = 14.0, + ) + var selectedId by remember { mutableStateOf(null) } + var mapViewState by remember { mutableStateOf?>(null) } + val onMarkerClick: OnMarkerEventHandler = { markerState -> selectedId = markerState.id } + val markerStates = + remember { + POSITIONS.flatMapIndexed { rowIndex, row -> + row.mapIndexed { columnIndex, labelPosition -> + MarkerState( + id = labelPosition, + position = + GeoPoint.fromLatLong( + CENTER.latitude + (1 - rowIndex) * STEP_LATITUDE, + CENTER.longitude + (columnIndex - 1) * STEP_LONGITUDE, + ), + icon = + DefaultMarkerIcon( + label = if (labelPosition == "center center") "信" else "信州大学", + labelPosition = labelPosition, + debug = true, + ), + extra = labelPosition, + onClick = onMarkerClick, + ) + } + } + } + + DemoMapPageScaffold( + menuItems = DefaultMapViewItems(initCameraPosition), + onToggleSidebar = onToggleSidebar, + onMapViewStateChanged = { state -> + @Suppress("UNCHECKED_CAST") + mapViewState = state as MapViewStateInterface + }, + ) { + mapViewState?.let { + MapViewContainer( + state = mapViewState, + onMapClick = { selectedId = null }, + ) { + markerStates.forEach { markerState -> + Marker(markerState) + if (markerState.id == selectedId) { + InfoBubble( + marker = markerState, + bubbleColor = Color.White, + borderColor = Color.Black, + ) { + Text( + text = "labelPosition: \"${markerState.extra}\"", + fontFamily = FontFamily.Monospace, + ) + } + } + } + } + } + } +} diff --git a/example-app/src/main/java/com/mapconductor/example/pages/marker/postoffice/PostOfficeViewModel.kt b/example-app/src/main/java/com/mapconductor/example/pages/marker/postoffice/PostOfficeViewModel.kt index 2e92b4b6..fda6c6b7 100644 --- a/example-app/src/main/java/com/mapconductor/example/pages/marker/postoffice/PostOfficeViewModel.kt +++ b/example-app/src/main/java/com/mapconductor/example/pages/marker/postoffice/PostOfficeViewModel.kt @@ -1,162 +1,161 @@ -package com.mapconductor.example.pages.marker.postoffice - -import androidx.lifecycle.ViewModel -import com.mapconductor.core.features.GeoPoint -import com.mapconductor.core.map.MapCameraPosition -import com.mapconductor.core.map.MapViewStateInterface -import com.mapconductor.core.marker.ImageIcon -import com.mapconductor.core.marker.MarkerState -import com.mapconductor.core.marker.MarkerTilingOptions -import com.mapconductor.postoffice.PostOffice -import com.mapconductor.postoffice.PostOfficeDataLoader -import java.lang.Thread.sleep -import kotlinx.coroutines.CoroutineScope -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.flow.MutableStateFlow -import kotlinx.coroutines.flow.StateFlow -import kotlinx.coroutines.flow.asStateFlow -import kotlinx.coroutines.launch - -interface PostOfficeViewModelInterface { - val initCameraPosition: MapCameraPosition - val selectedMarker: StateFlow - val markerList: StateFlow> - val mapViewState: StateFlow?> - val isMapLoaded: StateFlow - val isDataLoading: StateFlow - val markerTiling: MarkerTilingOptions - - fun onMapViewChanged(mapViewState: MapViewStateInterface<*>) - - fun onMarkerClick(clicked: MarkerState) - - fun onMapClick(clicked: GeoPoint) - - fun onMapLoaded(mapViewState: MapViewStateInterface<*>) - - fun onInfoClick(postOffice: PostOffice) - - // fun loadPostOfficeData() -} - -class PostOfficeViewModel( - private val postOfficeIcon: ImageIcon, - private val dataLoader: PostOfficeDataLoader, - private val coroutine: CoroutineScope = CoroutineScope(Dispatchers.Default), -) : ViewModel(), - PostOfficeViewModelInterface { - override val initCameraPosition = - MapCameraPosition( - position = - GeoPoint.fromLatLong( - latitude = 35.68049, - longitude = 139.76669, - ), - zoom = 10.0, - bearing = 0.0, - tilt = 0.0, - paddings = null, - ) - private val _markerList: MutableStateFlow> = MutableStateFlow(emptyList()) - override val markerList: StateFlow> = _markerList.asStateFlow() - - override val markerTiling: MarkerTilingOptions = - MarkerTilingOptions.Default.copy( - iconScaleCallback = { _, zoom -> - if (zoom > 12.0) { - return@copy 1.3 - } else if (zoom > 10.0) { - return@copy 1.0 - } else if (zoom > 8.0) { - return@copy 0.8 - } else if (zoom > 5.0) { - return@copy 0.5 - } else { - return@copy 0.2 - } - }, - ) - - private val _isMapLoaded: MutableStateFlow = MutableStateFlow(false) - override val isMapLoaded: StateFlow = _isMapLoaded.asStateFlow() - - private val _isDataLoading: MutableStateFlow = MutableStateFlow(false) - override val isDataLoading: StateFlow = _isDataLoading.asStateFlow() - - private var _mapViewState: MutableStateFlow?> = MutableStateFlow(null) - override val mapViewState: StateFlow?> = _mapViewState.asStateFlow() - - private var _selectedMarker: MutableStateFlow = MutableStateFlow(null) - override val selectedMarker: StateFlow = _selectedMarker.asStateFlow() - - private var cameraPosition: MapCameraPosition = initCameraPosition - - fun loadPostOfficeData() { - if (_markerList.value.isNotEmpty()) return - - coroutine.launch { - sleep(1000) - _isDataLoading.value = true - val postOffices = dataLoader.loadAllPostOffices() - - val markerStates = - postOffices.map { - MarkerState( - position = it.position, - id = it.hashCode().toString(), - icon = postOfficeIcon, - extra = it, - onClick = this@PostOfficeViewModel::onMarkerClick, - ) - } - _markerList.value = markerStates - _isDataLoading.value = false - } - } - - // Convenience: in case of error paths, ensure the dialog is hidden - private fun markLoadingFinished() { - if (_isDataLoading.value) { - _isDataLoading.value = false - } - } - - override fun onMarkerClick(clicked: MarkerState) { - this._selectedMarker.value = clicked - } - - override fun onMapClick(clicked: GeoPoint) { - this._selectedMarker.value = null - } - - override fun onMapLoaded(mapViewState: MapViewStateInterface<*>) { - coroutine.launch { - _isMapLoaded.value = true - _mapViewState.value?.moveCameraTo( - cameraPosition = cameraPosition, - ) - loadPostOfficeData() - } - } - - override fun onInfoClick(postOffice: PostOffice) { - _mapViewState.value?.moveCameraTo( - cameraPosition = - MapCameraPosition( - position = postOffice.position, - zoom = 18.0, - tilt = 30.0, - ), - durationMillis = 2000, - ) - } - - override fun onMapViewChanged(mapViewState: MapViewStateInterface<*>) { - cameraPosition = mapViewState.cameraPosition - - this._selectedMarker.value = null - _mapViewState.value = mapViewState - _isMapLoaded.value = false - } - -} +package com.mapconductor.example.pages.marker.postoffice + +import androidx.lifecycle.ViewModel +import com.mapconductor.core.features.GeoPoint +import com.mapconductor.core.map.MapCameraPosition +import com.mapconductor.core.map.MapViewStateInterface +import com.mapconductor.core.marker.ImageIcon +import com.mapconductor.core.marker.MarkerState +import com.mapconductor.core.marker.MarkerTilingOptions +import com.mapconductor.postoffice.PostOffice +import com.mapconductor.postoffice.PostOfficeDataLoader +import java.lang.Thread.sleep +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.launch + +interface PostOfficeViewModelInterface { + val initCameraPosition: MapCameraPosition + val selectedMarker: StateFlow + val markerList: StateFlow> + val mapViewState: StateFlow?> + val isMapLoaded: StateFlow + val isDataLoading: StateFlow + val markerTiling: MarkerTilingOptions + + fun onMapViewChanged(mapViewState: MapViewStateInterface<*>) + + fun onMarkerClick(clicked: MarkerState) + + fun onMapClick(clicked: GeoPoint) + + fun onMapLoaded(mapViewState: MapViewStateInterface<*>) + + fun onInfoClick(postOffice: PostOffice) + + // fun loadPostOfficeData() +} + +class PostOfficeViewModel( + private val postOfficeIcon: ImageIcon, + private val dataLoader: PostOfficeDataLoader, + private val coroutine: CoroutineScope = CoroutineScope(Dispatchers.Default), +) : ViewModel(), + PostOfficeViewModelInterface { + override val initCameraPosition = + MapCameraPosition( + position = + GeoPoint.fromLatLong( + latitude = 35.68049, + longitude = 139.76669, + ), + zoom = 10.0, + bearing = 0.0, + tilt = 0.0, + paddings = null, + ) + private val _markerList: MutableStateFlow> = MutableStateFlow(emptyList()) + override val markerList: StateFlow> = _markerList.asStateFlow() + + override val markerTiling: MarkerTilingOptions = + MarkerTilingOptions.Default.copy( + iconScaleCallback = { _, zoom -> + if (zoom > 12.0) { + return@copy 1.3 + } else if (zoom > 10.0) { + return@copy 1.0 + } else if (zoom > 8.0) { + return@copy 0.8 + } else if (zoom > 5.0) { + return@copy 0.5 + } else { + return@copy 0.2 + } + }, + ) + + private val _isMapLoaded: MutableStateFlow = MutableStateFlow(false) + override val isMapLoaded: StateFlow = _isMapLoaded.asStateFlow() + + private val _isDataLoading: MutableStateFlow = MutableStateFlow(false) + override val isDataLoading: StateFlow = _isDataLoading.asStateFlow() + + private var _mapViewState: MutableStateFlow?> = MutableStateFlow(null) + override val mapViewState: StateFlow?> = _mapViewState.asStateFlow() + + private var _selectedMarker: MutableStateFlow = MutableStateFlow(null) + override val selectedMarker: StateFlow = _selectedMarker.asStateFlow() + + private var cameraPosition: MapCameraPosition = initCameraPosition + + fun loadPostOfficeData() { + if (_markerList.value.isNotEmpty()) return + + coroutine.launch { + sleep(1000) + _isDataLoading.value = true + val postOffices = dataLoader.loadAllPostOffices() + + val markerStates = + postOffices.map { + MarkerState( + position = it.position, + id = it.hashCode().toString(), + icon = postOfficeIcon, + extra = it, + onClick = this@PostOfficeViewModel::onMarkerClick, + ) + } + _markerList.value = markerStates + _isDataLoading.value = false + } + } + + // Convenience: in case of error paths, ensure the dialog is hidden + private fun markLoadingFinished() { + if (_isDataLoading.value) { + _isDataLoading.value = false + } + } + + override fun onMarkerClick(clicked: MarkerState) { + this._selectedMarker.value = clicked + } + + override fun onMapClick(clicked: GeoPoint) { + this._selectedMarker.value = null + } + + override fun onMapLoaded(mapViewState: MapViewStateInterface<*>) { + coroutine.launch { + _isMapLoaded.value = true + _mapViewState.value?.moveCameraTo( + cameraPosition = cameraPosition, + ) + loadPostOfficeData() + } + } + + override fun onInfoClick(postOffice: PostOffice) { + _mapViewState.value?.moveCameraTo( + cameraPosition = + MapCameraPosition( + position = postOffice.position, + zoom = 18.0, + tilt = 30.0, + ), + durationMillis = 2000, + ) + } + + override fun onMapViewChanged(mapViewState: MapViewStateInterface<*>) { + cameraPosition = mapViewState.cameraPosition + + this._selectedMarker.value = null + _mapViewState.value = mapViewState + _isMapLoaded.value = false + } +} diff --git a/example-app/src/main/java/com/mapconductor/example/pages/marker/postofficecluster/MarkerClusterMapPageViewModel.kt b/example-app/src/main/java/com/mapconductor/example/pages/marker/postofficecluster/MarkerClusterMapPageViewModel.kt index e6e4ac66..030c3471 100644 --- a/example-app/src/main/java/com/mapconductor/example/pages/marker/postofficecluster/MarkerClusterMapPageViewModel.kt +++ b/example-app/src/main/java/com/mapconductor/example/pages/marker/postofficecluster/MarkerClusterMapPageViewModel.kt @@ -1,180 +1,179 @@ -package com.mapconductor.example.pages.marker.postofficecluster - -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.setValue -import androidx.lifecycle.ViewModel -import androidx.lifecycle.viewModelScope -import com.mapconductor.core.features.GeoPoint -import com.mapconductor.core.map.MapCameraPosition -import com.mapconductor.core.map.MapViewStateInterface -import com.mapconductor.core.marker.ImageIcon -import com.mapconductor.core.marker.MarkerRenderingStrategyInterface -import com.mapconductor.core.marker.MarkerState -import com.mapconductor.marker.clustering.MarkerCluster -import com.mapconductor.postoffice.PostOffice -import com.mapconductor.postoffice.PostOfficeDataLoader -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.delay -import kotlinx.coroutines.flow.MutableStateFlow -import kotlinx.coroutines.flow.StateFlow -import kotlinx.coroutines.flow.asStateFlow -import kotlinx.coroutines.launch - -interface MarkerClusterMapPageViewModelInterface { - val initCameraPosition: MapCameraPosition - val selectedMarker: StateFlow - val markerList: StateFlow> - val mapViewState: StateFlow?> - val isMapLoaded: StateFlow - val isDataLoading: StateFlow - - val renderingStrategy: StateFlow?> - var debugHullPolygons: Boolean - - fun onMapViewChanged(mapViewState: MapViewStateInterface<*>) - - fun onMarkerClick(clicked: MarkerState) - - fun onMapClick(clicked: GeoPoint) - - fun onMapLoaded(mapViewState: MapViewStateInterface<*>) - - fun onInfoClick(postOffice: PostOffice) - - fun onClusterClicked(cluster: MarkerCluster) -} - -class MarkerClusterMapPageViewModel( - private val postOfficeIcon: ImageIcon, - private val dataLoader: PostOfficeDataLoader, -) : ViewModel(), - MarkerClusterMapPageViewModelInterface { - override val initCameraPosition = - MapCameraPosition( - position = - GeoPoint.fromLatLong( - latitude = 35.68049, - longitude = 139.76669, - ), - zoom = 10.0, - bearing = 0.0, - tilt = 0.0, - paddings = null, - ) - private val _markerList: MutableStateFlow> = MutableStateFlow(emptyList()) - override val markerList: StateFlow> = _markerList.asStateFlow() - - private val _isMapLoaded: MutableStateFlow = MutableStateFlow(false) - override val isMapLoaded: StateFlow = _isMapLoaded.asStateFlow() - - private val _isDataLoading: MutableStateFlow = MutableStateFlow(false) - override val isDataLoading: StateFlow = _isDataLoading.asStateFlow() - - private var _mapViewState: MutableStateFlow?> = MutableStateFlow(null) - override val mapViewState: StateFlow?> = _mapViewState.asStateFlow() - - private var _selectedMarker: MutableStateFlow = MutableStateFlow(null) - override val selectedMarker: StateFlow = _selectedMarker.asStateFlow() - - private var cameraPosition: MapCameraPosition = initCameraPosition - - private val _renderingStrategy: MutableStateFlow?> = - MutableStateFlow(null) - override val renderingStrategy: StateFlow?> = _renderingStrategy.asStateFlow() - - override var debugHullPolygons by mutableStateOf(false) - - fun loadPostOfficeData() { - if (_markerList.value.isNotEmpty()) return - - viewModelScope.launch(Dispatchers.Default) { - _isDataLoading.value = true - try { - delay(1000) - val postOffices = dataLoader.loadAllPostOffices() - - val markerStates = - postOffices.map { - MarkerState( - position = it.position, - id = it.hashCode().toString(), - icon = postOfficeIcon, - extra = it, - onClick = this@MarkerClusterMapPageViewModel::onMarkerClick, - ) - } - _markerList.value = markerStates - } catch (t: Throwable) { - _markerList.value = emptyList() - } finally { - _isDataLoading.value = false - } - } - } - - // Convenience: in case of error paths, ensure the dialog is hidden - private fun markLoadingFinished() { - if (_isDataLoading.value) { - _isDataLoading.value = false - } - } - - override fun onMarkerClick(clicked: MarkerState) { - this._selectedMarker.value = clicked - } - - override fun onMapClick(clicked: GeoPoint) { - this._selectedMarker.value = null - } - - override fun onMapLoaded(mapViewState: MapViewStateInterface<*>) { - viewModelScope.launch(Dispatchers.Default) { - _isMapLoaded.value = true - _mapViewState.value?.moveCameraTo( - cameraPosition = cameraPosition, - ) - loadPostOfficeData() - } - } - - override fun onInfoClick(postOffice: PostOffice) { - _mapViewState.value?.moveCameraTo( - cameraPosition = - MapCameraPosition( - position = postOffice.position, - zoom = 18.0, - tilt = 30.0, - ), - durationMillis = 2000, - ) - } - - // クラスターをクリックしたら、クラスター内マーカーの重心へズームインする(React と同じロジック)。 - override fun onClusterClicked(cluster: MarkerCluster) { - val byId = _markerList.value.associateBy { it.id } - val positions = cluster.markerIds.mapNotNull { byId[it]?.position } - if (positions.isEmpty()) return - val lat = positions.sumOf { it.latitude } / positions.size - val lng = positions.sumOf { it.longitude } / positions.size - val currentZoom = _mapViewState.value?.cameraPosition?.zoom ?: 10.0 - _mapViewState.value?.moveCameraTo( - cameraPosition = - MapCameraPosition( - position = GeoPoint.fromLatLong(lat, lng), - zoom = minOf(currentZoom + 2.0, 18.0), - ), - durationMillis = 600, - ) - } - - override fun onMapViewChanged(mapViewState: MapViewStateInterface<*>) { - cameraPosition = mapViewState.cameraPosition - - renderingStrategy.value?.clear() - this._selectedMarker.value = null - _mapViewState.value = mapViewState - _isMapLoaded.value = false - } - -} +package com.mapconductor.example.pages.marker.postofficecluster + +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import androidx.lifecycle.ViewModel +import androidx.lifecycle.viewModelScope +import com.mapconductor.core.features.GeoPoint +import com.mapconductor.core.map.MapCameraPosition +import com.mapconductor.core.map.MapViewStateInterface +import com.mapconductor.core.marker.ImageIcon +import com.mapconductor.core.marker.MarkerRenderingStrategyInterface +import com.mapconductor.core.marker.MarkerState +import com.mapconductor.marker.clustering.MarkerCluster +import com.mapconductor.postoffice.PostOffice +import com.mapconductor.postoffice.PostOfficeDataLoader +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.launch + +interface MarkerClusterMapPageViewModelInterface { + val initCameraPosition: MapCameraPosition + val selectedMarker: StateFlow + val markerList: StateFlow> + val mapViewState: StateFlow?> + val isMapLoaded: StateFlow + val isDataLoading: StateFlow + + val renderingStrategy: StateFlow?> + var debugHullPolygons: Boolean + + fun onMapViewChanged(mapViewState: MapViewStateInterface<*>) + + fun onMarkerClick(clicked: MarkerState) + + fun onMapClick(clicked: GeoPoint) + + fun onMapLoaded(mapViewState: MapViewStateInterface<*>) + + fun onInfoClick(postOffice: PostOffice) + + fun onClusterClicked(cluster: MarkerCluster) +} + +class MarkerClusterMapPageViewModel( + private val postOfficeIcon: ImageIcon, + private val dataLoader: PostOfficeDataLoader, +) : ViewModel(), + MarkerClusterMapPageViewModelInterface { + override val initCameraPosition = + MapCameraPosition( + position = + GeoPoint.fromLatLong( + latitude = 35.68049, + longitude = 139.76669, + ), + zoom = 10.0, + bearing = 0.0, + tilt = 0.0, + paddings = null, + ) + private val _markerList: MutableStateFlow> = MutableStateFlow(emptyList()) + override val markerList: StateFlow> = _markerList.asStateFlow() + + private val _isMapLoaded: MutableStateFlow = MutableStateFlow(false) + override val isMapLoaded: StateFlow = _isMapLoaded.asStateFlow() + + private val _isDataLoading: MutableStateFlow = MutableStateFlow(false) + override val isDataLoading: StateFlow = _isDataLoading.asStateFlow() + + private var _mapViewState: MutableStateFlow?> = MutableStateFlow(null) + override val mapViewState: StateFlow?> = _mapViewState.asStateFlow() + + private var _selectedMarker: MutableStateFlow = MutableStateFlow(null) + override val selectedMarker: StateFlow = _selectedMarker.asStateFlow() + + private var cameraPosition: MapCameraPosition = initCameraPosition + + private val _renderingStrategy: MutableStateFlow?> = + MutableStateFlow(null) + override val renderingStrategy: StateFlow?> = _renderingStrategy.asStateFlow() + + override var debugHullPolygons by mutableStateOf(false) + + fun loadPostOfficeData() { + if (_markerList.value.isNotEmpty()) return + + viewModelScope.launch(Dispatchers.Default) { + _isDataLoading.value = true + try { + delay(1000) + val postOffices = dataLoader.loadAllPostOffices() + + val markerStates = + postOffices.map { + MarkerState( + position = it.position, + id = it.hashCode().toString(), + icon = postOfficeIcon, + extra = it, + onClick = this@MarkerClusterMapPageViewModel::onMarkerClick, + ) + } + _markerList.value = markerStates + } catch (t: Throwable) { + _markerList.value = emptyList() + } finally { + _isDataLoading.value = false + } + } + } + + // Convenience: in case of error paths, ensure the dialog is hidden + private fun markLoadingFinished() { + if (_isDataLoading.value) { + _isDataLoading.value = false + } + } + + override fun onMarkerClick(clicked: MarkerState) { + this._selectedMarker.value = clicked + } + + override fun onMapClick(clicked: GeoPoint) { + this._selectedMarker.value = null + } + + override fun onMapLoaded(mapViewState: MapViewStateInterface<*>) { + viewModelScope.launch(Dispatchers.Default) { + _isMapLoaded.value = true + _mapViewState.value?.moveCameraTo( + cameraPosition = cameraPosition, + ) + loadPostOfficeData() + } + } + + override fun onInfoClick(postOffice: PostOffice) { + _mapViewState.value?.moveCameraTo( + cameraPosition = + MapCameraPosition( + position = postOffice.position, + zoom = 18.0, + tilt = 30.0, + ), + durationMillis = 2000, + ) + } + + // クラスターをクリックしたら、クラスター内マーカーの重心へズームインする(React と同じロジック)。 + override fun onClusterClicked(cluster: MarkerCluster) { + val byId = _markerList.value.associateBy { it.id } + val positions = cluster.markerIds.mapNotNull { byId[it]?.position } + if (positions.isEmpty()) return + val lat = positions.sumOf { it.latitude } / positions.size + val lng = positions.sumOf { it.longitude } / positions.size + val currentZoom = _mapViewState.value?.cameraPosition?.zoom ?: 10.0 + _mapViewState.value?.moveCameraTo( + cameraPosition = + MapCameraPosition( + position = GeoPoint.fromLatLong(lat, lng), + zoom = minOf(currentZoom + 2.0, 18.0), + ), + durationMillis = 600, + ) + } + + override fun onMapViewChanged(mapViewState: MapViewStateInterface<*>) { + cameraPosition = mapViewState.cameraPosition + + renderingStrategy.value?.clear() + this._selectedMarker.value = null + _mapViewState.value = mapViewState + _isMapLoaded.value = false + } +} diff --git a/example-app/src/main/java/com/mapconductor/example/pages/offlinemap/OfflineMapPage.kt b/example-app/src/main/java/com/mapconductor/example/pages/offlinemap/OfflineMapPage.kt index 5f46d851..873c753b 100644 --- a/example-app/src/main/java/com/mapconductor/example/pages/offlinemap/OfflineMapPage.kt +++ b/example-app/src/main/java/com/mapconductor/example/pages/offlinemap/OfflineMapPage.kt @@ -243,9 +243,10 @@ fun OfflineMapPage( onMapViewStateChanged = { mapViewState = it }, ) { paddings -> Box( - modifier = modifier - .fillMaxSize() - .padding(paddings), + modifier = + modifier + .fillMaxSize() + .padding(paddings), contentAlignment = Alignment.Center, ) { mapViewState?.let { state -> diff --git a/example-app/src/main/java/com/mapconductor/example/pages/polygon/boston/BostonData.kt b/example-app/src/main/java/com/mapconductor/example/pages/polygon/boston/BostonData.kt index e2b9d0f1..86a63992 100644 --- a/example-app/src/main/java/com/mapconductor/example/pages/polygon/boston/BostonData.kt +++ b/example-app/src/main/java/com/mapconductor/example/pages/polygon/boston/BostonData.kt @@ -1,218 +1,218 @@ -package com.mapconductor.example.pages.polygon.boston - -import androidx.compose.ui.graphics.Color -import com.mapconductor.core.features.GeoPoint -import com.mapconductor.core.spherical.Spherical -import java.io.ByteArrayOutputStream -import java.nio.ByteBuffer -import java.nio.ByteOrder -import android.content.Context - -/** - * The polygons the Boston page draws. - * - * - [DOWNTOWN]: Overture building footprints of downtown in three nested areas. - * - [CITY_BUILDINGS] / [CITY_PARCELS]: the whole city: Overture buildings, and - * Analyze Boston Parcels 2025 joined with the FY2026 Property Assessment land use. - * - * All three are bundled (assets/boston). The React sample's - * `examples/basic/tools/boston/` builds them from the official sources (see its - * README). The files carry no ids: this is a polygon demo, and a polygon's id on - * the map is its index in the file. - * - * The binary layout is the same as the React sample's (bostonData.ts), MCPG v2: - * 'MCPG' u32 version=2 u32 count u8 fields u8 digits (little-endian) - * fields: 1 = height, 2 = land use, 4 = area, 8 = name, 16 = road class (what the file carries), - * 32 = lines: the shapes are polylines, not polygons (the roads file, see BostonRoadsData) - * digits: coordinates are integers of 10^-digits degree (buildings 6, parcels 5) - * per polygon, only the fields present, in this order: - * height varint, 0 = unknown, else the height in 0.1 m plus 1 - * land use u8, the index in [LandUse] (family … unknown) - * area u8, the smallest downtown area (0, 1 or 2) the building fits in - * name varint byte length (0 = none), UTF-8 - * road class u8, the index in RoadClass (highway … path) - * varint ringCount, per ring: varint n, n x (svarint dLat, svarint dLng) - * varint is LEB128 (7 bits at a time, low first); svarint is a zigzag varint. - * Coordinates are integers of 10^-digits degree, each the difference from the - * previous vertex across the whole file. A ring's closing vertex (the same as its first) - * is not stored: n counts the others, and the reader closes the ring again. - * With the lines bit a "ring" is an open polyline: every vertex is stored and - * the reader does not close it. - */ -enum class Dataset( - val label: String, - /** The file in assets. */ - val file: String, - val attribution: String, -) { - DOWNTOWN("Downtown", "boston/boston-downtown.bin", OVERTURE_ATTRIBUTION), - CITY_BUILDINGS("City buildings", "boston/boston-city-buildings.bin", OVERTURE_ATTRIBUTION), - CITY_PARCELS( - "City parcels", - "boston/boston-city-parcels.bin", - "City of Boston, Parcels 2025 and FY2026 Property Assessment (Analyze Boston) (ODC PDDL)", - ), -} - -private const val OVERTURE_ATTRIBUTION = - "© OpenStreetMap contributors, Esri Community Maps contributors, USGS, Microsoft — via Overture Maps Foundation (ODbL 1.0)" - -/** - * Land use of a parcel (Property Assessment `LU`, grouped) and how it is drawn; the same as the React sample. - * The order is the file's: a land use is stored as its index here. - */ -enum class LandUse( - val key: String, - val label: String, - val fill: Color, -) { - FAMILY("family", "1–3 family", Color(0x8CFACC15)), - APARTMENT("apartment", "Apartments", Color(0x8CF97316)), - CONDO("condo", "Condominium", Color(0x80EC4899)), - MIXED("mixed", "Residential + commercial", Color(0x80A855F7)), - COMMERCIAL("commercial", "Commercial", Color(0x8CEF4444)), - INDUSTRIAL("industrial", "Industrial", Color(0x9964748B)), - EXEMPT("exempt", "Exempt (public, institutions)", Color(0x803B82F6)), - VACANT("vacant", "Vacant land", Color(0x7322C55E)), - UNKNOWN("unknown", "No assessment (roads, islands)", Color(0x5994A3B8)), -} - -/** Where loading has got to, for the overlay. */ -sealed class LoadPhase { - data class Read( - val loaded: Long, - val total: Long?, - ) : LoadPhase() - - data object Decode : LoadPhase() - - data object Build : LoadPhase() - - data object Draw : LoadPhase() -} - -class BostonData( - val attribution: String, - val buildings: List, -) - -fun loadBostonData( - context: Context, - dataset: Dataset, - onProgress: (LoadPhase) -> Unit = {}, -): BostonData { - // openFd works only on an uncompressed asset; without it the progress has no total. - val length = runCatching { context.assets.openFd(dataset.file).use { it.length } }.getOrNull() - val bytes = readWithProgress(context.assets.open(dataset.file), length, onProgress) - onProgress(LoadPhase.Decode) - return BostonData(dataset.attribution, decodeMcpg(bytes, dataset.name.lowercase())) -} - -private fun readWithProgress( - input: java.io.InputStream, - total: Long?, - onProgress: (LoadPhase) -> Unit, -): ByteArray = - input.use { stream -> - val out = ByteArrayOutputStream(total?.toInt() ?: 1 shl 20) - val chunk = ByteArray(256 * 1024) - var loaded = 0L - onProgress(LoadPhase.Read(loaded, total)) - while (true) { - val n = stream.read(chunk) - if (n < 0) break - out.write(chunk, 0, n) - loaded += n - onProgress(LoadPhase.Read(loaded, total)) - } - out.toByteArray() - } - -private const val FIELD_HEIGHT = 1 -private const val FIELD_USE = 2 -private const val FIELD_AREA = 4 -private const val FIELD_NAME = 8 -private const val FIELD_CLASS = 16 -private const val FIELD_LINES = 32 - -/** Decodes an MCPG v2 file (see the top of this file); shape `i` gets the id "-". */ -internal fun decodeMcpg( - bytes: ByteArray, - idPrefix: String, -): List { - val header = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN) - val magic = String(bytes, 0, 4, Charsets.US_ASCII) - require(magic == "MCPG" && header.getInt(4) == 2) { "not an MCPG v2 file" } - val count = header.getInt(8) - val fields = bytes[12].toInt() and 0xFF - val scale = Math.pow(10.0, (bytes[13].toInt() and 0xFF).toDouble()) - var offset = 14 - val lines = (fields and FIELD_LINES) != 0 - - fun varint(): Int { - var value = 0 - var shift = 0 - while (true) { - val b = bytes[offset++].toInt() and 0xFF - value = value or ((b and 0x7F) shl shift) - if (b < 0x80) return value - shift += 7 - } - } - - fun svarint(): Int { - val v = varint() - return (v ushr 1) xor -(v and 1) - } - - var lat = 0 - var lng = 0 - return List(count) { i -> - var height: Double? = null - var use: LandUse? = null - var level = 0 - var name: String? = null - var roadClass: Int? = null - if ((fields and FIELD_HEIGHT) != 0) height = varint().takeIf { it > 0 }?.let { (it - 1) / 10.0 } - if ((fields and FIELD_USE) != 0) use = LandUse.entries[bytes[offset++].toInt() and 0xFF] - if ((fields and FIELD_AREA) != 0) level = bytes[offset++].toInt() and 0xFF - if ((fields and FIELD_NAME) != 0) { - val length = varint() - if (length > 0) name = String(bytes, offset, length, Charsets.UTF_8) - offset += length - } - if ((fields and FIELD_CLASS) != 0) roadClass = bytes[offset++].toInt() and 0xFF - val rings = - List(varint()) { - val n = varint() - // The closing vertex is not stored; it is the first one again. A line is open. - val ring = DoubleArray((if (lines) n else n + 1) * 2) - for (v in 0 until n) { - lat += svarint() - lng += svarint() - ring[v * 2] = lng / scale - ring[v * 2 + 1] = lat / scale - } - if (!lines) { - ring[n * 2] = ring[0] - ring[n * 2 + 1] = ring[1] - } - ring - } - Building( - id = "$idPrefix-$i", - level = level, - height = height, - name = name, - rings = rings, - use = use, - roadClass = roadClass - ) - } -} - -/** The area of [building] in square metres: its outline less its holes. */ -fun areaSquareMetres(building: Building): Double { - val rings = building.rings.map { ring -> List(ring.size / 2) { GeoPoint(ring[it * 2 + 1], ring[it * 2]) } } - return Spherical.computeArea(rings.first()) - rings.drop(1).sumOf { Spherical.computeArea(it) } -} +package com.mapconductor.example.pages.polygon.boston + +import androidx.compose.ui.graphics.Color +import com.mapconductor.core.features.GeoPoint +import com.mapconductor.core.spherical.Spherical +import java.io.ByteArrayOutputStream +import java.nio.ByteBuffer +import java.nio.ByteOrder +import android.content.Context + +/** + * The polygons the Boston page draws. + * + * - [DOWNTOWN]: Overture building footprints of downtown in three nested areas. + * - [CITY_BUILDINGS] / [CITY_PARCELS]: the whole city: Overture buildings, and + * Analyze Boston Parcels 2025 joined with the FY2026 Property Assessment land use. + * + * All three are bundled (assets/boston). The React sample's + * `examples/basic/tools/boston/` builds them from the official sources (see its + * README). The files carry no ids: this is a polygon demo, and a polygon's id on + * the map is its index in the file. + * + * The binary layout is the same as the React sample's (bostonData.ts), MCPG v2: + * 'MCPG' u32 version=2 u32 count u8 fields u8 digits (little-endian) + * fields: 1 = height, 2 = land use, 4 = area, 8 = name, 16 = road class (what the file carries), + * 32 = lines: the shapes are polylines, not polygons (the roads file, see BostonRoadsData) + * digits: coordinates are integers of 10^-digits degree (buildings 6, parcels 5) + * per polygon, only the fields present, in this order: + * height varint, 0 = unknown, else the height in 0.1 m plus 1 + * land use u8, the index in [LandUse] (family … unknown) + * area u8, the smallest downtown area (0, 1 or 2) the building fits in + * name varint byte length (0 = none), UTF-8 + * road class u8, the index in RoadClass (highway … path) + * varint ringCount, per ring: varint n, n x (svarint dLat, svarint dLng) + * varint is LEB128 (7 bits at a time, low first); svarint is a zigzag varint. + * Coordinates are integers of 10^-digits degree, each the difference from the + * previous vertex across the whole file. A ring's closing vertex (the same as its first) + * is not stored: n counts the others, and the reader closes the ring again. + * With the lines bit a "ring" is an open polyline: every vertex is stored and + * the reader does not close it. + */ +enum class Dataset( + val label: String, + /** The file in assets. */ + val file: String, + val attribution: String, +) { + DOWNTOWN("Downtown", "boston/boston-downtown.bin", OVERTURE_ATTRIBUTION), + CITY_BUILDINGS("City buildings", "boston/boston-city-buildings.bin", OVERTURE_ATTRIBUTION), + CITY_PARCELS( + "City parcels", + "boston/boston-city-parcels.bin", + "City of Boston, Parcels 2025 and FY2026 Property Assessment (Analyze Boston) (ODC PDDL)", + ), +} + +private const val OVERTURE_ATTRIBUTION = + "© OpenStreetMap contributors, Esri Community Maps contributors, USGS, Microsoft — via Overture Maps Foundation (ODbL 1.0)" + +/** + * Land use of a parcel (Property Assessment `LU`, grouped) and how it is drawn; the same as the React sample. + * The order is the file's: a land use is stored as its index here. + */ +enum class LandUse( + val key: String, + val label: String, + val fill: Color, +) { + FAMILY("family", "1–3 family", Color(0x8CFACC15)), + APARTMENT("apartment", "Apartments", Color(0x8CF97316)), + CONDO("condo", "Condominium", Color(0x80EC4899)), + MIXED("mixed", "Residential + commercial", Color(0x80A855F7)), + COMMERCIAL("commercial", "Commercial", Color(0x8CEF4444)), + INDUSTRIAL("industrial", "Industrial", Color(0x9964748B)), + EXEMPT("exempt", "Exempt (public, institutions)", Color(0x803B82F6)), + VACANT("vacant", "Vacant land", Color(0x7322C55E)), + UNKNOWN("unknown", "No assessment (roads, islands)", Color(0x5994A3B8)), +} + +/** Where loading has got to, for the overlay. */ +sealed class LoadPhase { + data class Read( + val loaded: Long, + val total: Long?, + ) : LoadPhase() + + data object Decode : LoadPhase() + + data object Build : LoadPhase() + + data object Draw : LoadPhase() +} + +class BostonData( + val attribution: String, + val buildings: List, +) + +fun loadBostonData( + context: Context, + dataset: Dataset, + onProgress: (LoadPhase) -> Unit = {}, +): BostonData { + // openFd works only on an uncompressed asset; without it the progress has no total. + val length = runCatching { context.assets.openFd(dataset.file).use { it.length } }.getOrNull() + val bytes = readWithProgress(context.assets.open(dataset.file), length, onProgress) + onProgress(LoadPhase.Decode) + return BostonData(dataset.attribution, decodeMcpg(bytes, dataset.name.lowercase())) +} + +private fun readWithProgress( + input: java.io.InputStream, + total: Long?, + onProgress: (LoadPhase) -> Unit, +): ByteArray = + input.use { stream -> + val out = ByteArrayOutputStream(total?.toInt() ?: 1 shl 20) + val chunk = ByteArray(256 * 1024) + var loaded = 0L + onProgress(LoadPhase.Read(loaded, total)) + while (true) { + val n = stream.read(chunk) + if (n < 0) break + out.write(chunk, 0, n) + loaded += n + onProgress(LoadPhase.Read(loaded, total)) + } + out.toByteArray() + } + +private const val FIELD_HEIGHT = 1 +private const val FIELD_USE = 2 +private const val FIELD_AREA = 4 +private const val FIELD_NAME = 8 +private const val FIELD_CLASS = 16 +private const val FIELD_LINES = 32 + +/** Decodes an MCPG v2 file (see the top of this file); shape `i` gets the id "-". */ +internal fun decodeMcpg( + bytes: ByteArray, + idPrefix: String, +): List { + val header = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN) + val magic = String(bytes, 0, 4, Charsets.US_ASCII) + require(magic == "MCPG" && header.getInt(4) == 2) { "not an MCPG v2 file" } + val count = header.getInt(8) + val fields = bytes[12].toInt() and 0xFF + val scale = Math.pow(10.0, (bytes[13].toInt() and 0xFF).toDouble()) + var offset = 14 + val lines = (fields and FIELD_LINES) != 0 + + fun varint(): Int { + var value = 0 + var shift = 0 + while (true) { + val b = bytes[offset++].toInt() and 0xFF + value = value or ((b and 0x7F) shl shift) + if (b < 0x80) return value + shift += 7 + } + } + + fun svarint(): Int { + val v = varint() + return (v ushr 1) xor -(v and 1) + } + + var lat = 0 + var lng = 0 + return List(count) { i -> + var height: Double? = null + var use: LandUse? = null + var level = 0 + var name: String? = null + var roadClass: Int? = null + if ((fields and FIELD_HEIGHT) != 0) height = varint().takeIf { it > 0 }?.let { (it - 1) / 10.0 } + if ((fields and FIELD_USE) != 0) use = LandUse.entries[bytes[offset++].toInt() and 0xFF] + if ((fields and FIELD_AREA) != 0) level = bytes[offset++].toInt() and 0xFF + if ((fields and FIELD_NAME) != 0) { + val length = varint() + if (length > 0) name = String(bytes, offset, length, Charsets.UTF_8) + offset += length + } + if ((fields and FIELD_CLASS) != 0) roadClass = bytes[offset++].toInt() and 0xFF + val rings = + List(varint()) { + val n = varint() + // The closing vertex is not stored; it is the first one again. A line is open. + val ring = DoubleArray((if (lines) n else n + 1) * 2) + for (v in 0 until n) { + lat += svarint() + lng += svarint() + ring[v * 2] = lng / scale + ring[v * 2 + 1] = lat / scale + } + if (!lines) { + ring[n * 2] = ring[0] + ring[n * 2 + 1] = ring[1] + } + ring + } + Building( + id = "$idPrefix-$i", + level = level, + height = height, + name = name, + rings = rings, + use = use, + roadClass = roadClass, + ) + } +} + +/** The area of [building] in square metres: its outline less its holes. */ +fun areaSquareMetres(building: Building): Double { + val rings = building.rings.map { ring -> List(ring.size / 2) { GeoPoint(ring[it * 2 + 1], ring[it * 2]) } } + return Spherical.computeArea(rings.first()) - rings.drop(1).sumOf { Spherical.computeArea(it) } +} diff --git a/example-app/src/main/java/com/mapconductor/example/pages/polygon/boston/BostonOverlays.kt b/example-app/src/main/java/com/mapconductor/example/pages/polygon/boston/BostonOverlays.kt index 42eb1a73..adb6d91e 100644 --- a/example-app/src/main/java/com/mapconductor/example/pages/polygon/boston/BostonOverlays.kt +++ b/example-app/src/main/java/com/mapconductor/example/pages/polygon/boston/BostonOverlays.kt @@ -1,140 +1,141 @@ -package com.mapconductor.example.pages.polygon.boston - -import androidx.compose.foundation.background -import androidx.compose.foundation.border -import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Box -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.Row -import androidx.compose.foundation.layout.fillMaxSize -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.layout.size -import androidx.compose.foundation.layout.width -import androidx.compose.foundation.shape.RoundedCornerShape -import androidx.compose.material3.CircularProgressIndicator -import androidx.compose.material3.LinearProgressIndicator -import androidx.compose.material3.Text -import androidx.compose.runtime.Composable -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.graphics.Color -import androidx.compose.ui.text.font.FontWeight -import androidx.compose.ui.unit.dp -import androidx.compose.ui.unit.sp -import java.util.Locale - -/** The land-use colours, two to a row. */ -@Composable -fun LandUseLegend(modifier: Modifier = Modifier) { - Column(modifier = modifier, verticalArrangement = Arrangement.spacedBy(2.dp)) { - LandUse.entries.chunked(2).forEach { row -> - Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp)) { - row.forEach { use -> - Row(modifier = Modifier.weight(1f), verticalAlignment = Alignment.CenterVertically) { - Box( - modifier = - Modifier - .size(10.dp) - .background(use.fill, RoundedCornerShape(2.dp)) - .border(1.dp, Color(0x80475569), RoundedCornerShape(2.dp)), - ) - Text(use.label, fontSize = 11.sp, modifier = Modifier.padding(start = 4.dp)) - } - } - } - } - } -} - -private const val MB = 1024.0 * 1024.0 - -/** Covers the map while a dataset loads, saying which phase it is in. */ -@Composable -fun LoadingOverlay( - phase: LoadPhase, - modifier: Modifier = Modifier, - /** What is loading, for the text: "polygons" or "roads". */ - shapes: String = "polygons", -) { - var fraction: Float? = null - val text = - when (phase) { - is LoadPhase.Read -> { - val loaded = String.format(Locale.US, "%.1f", phase.loaded / MB) - val total = phase.total?.takeIf { it > 0 } - if (total != null) { - fraction = (phase.loaded.toFloat() / total).coerceIn(0f, 1f) - "Loading data… $loaded / ${String.format(Locale.US, "%.1f", total / MB)} MB" - } else { - "Loading data… $loaded MB" - } - } - - LoadPhase.Decode -> "Reading the $shapes…" - LoadPhase.Build -> "Preparing the $shapes…" - LoadPhase.Draw -> "Drawing the map…" - } - Box( - modifier = modifier - .fillMaxSize() - .background(Color(0x590F172A)), - contentAlignment = Alignment.Center, - ) { - Column( - modifier = - Modifier - .width(260.dp) - .background(Color.White, RoundedCornerShape(10.dp)) - .padding(horizontal = 20.dp, vertical = 16.dp), - horizontalAlignment = Alignment.CenterHorizontally, - verticalArrangement = Arrangement.spacedBy(10.dp), - ) { - CircularProgressIndicator(modifier = Modifier.size(28.dp), strokeWidth = 3.dp, color = Color(0xFF2563EB)) - Text(text, fontSize = 14.sp, color = Color(0xFF0F172A)) - fraction?.let { - LinearProgressIndicator(progress = { - it - }, modifier = Modifier.fillMaxWidth(), color = Color(0xFF2563EB)) - } - } - } -} - -/** What a tapped polygon carries, shown in an InfoBubble at the tap. */ -@Composable -fun PolygonInfo(building: Building) { - val rows = mutableListOf>() - val use = building.use - if (use != null) { - rows += "Land use" to use.label - } else { - building.name?.let { rows += "Name" to it } - rows += "Height" to (building.height?.let { "$it m" } ?: "unknown") - } - rows += "Area" to formatArea(areaSquareMetres(building)) - val vertices = building.rings.sumOf { it.size / 2 } - rows += "Vertices" to (if (building.rings.size > 1) "$vertices (holes ${building.rings.size - 1})" else "$vertices") - Column { - rows.forEach { (key, value) -> - Row { - Text( - key, - fontSize = 12.sp, - fontWeight = FontWeight.SemiBold, - color = Color(0xFF475569), - modifier = Modifier.width(84.dp), - ) - Text(value, fontSize = 12.sp, color = Color(0xFF0F172A)) - } - } - } -} - -/** "1,234 m²", or hectares from 10,000 m² up. */ -fun formatArea(squareMetres: Double): String = - if (squareMetres >= 10_000) { - String.format(Locale.US, "%.2f ha", squareMetres / 10_000) - } else { - String.format(Locale.US, "%,.0f m²", squareMetres) - } +package com.mapconductor.example.pages.polygon.boston + +import androidx.compose.foundation.background +import androidx.compose.foundation.border +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.LinearProgressIndicator +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import java.util.Locale + +/** The land-use colours, two to a row. */ +@Composable +fun LandUseLegend(modifier: Modifier = Modifier) { + Column(modifier = modifier, verticalArrangement = Arrangement.spacedBy(2.dp)) { + LandUse.entries.chunked(2).forEach { row -> + Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp)) { + row.forEach { use -> + Row(modifier = Modifier.weight(1f), verticalAlignment = Alignment.CenterVertically) { + Box( + modifier = + Modifier + .size(10.dp) + .background(use.fill, RoundedCornerShape(2.dp)) + .border(1.dp, Color(0x80475569), RoundedCornerShape(2.dp)), + ) + Text(use.label, fontSize = 11.sp, modifier = Modifier.padding(start = 4.dp)) + } + } + } + } + } +} + +private const val MB = 1024.0 * 1024.0 + +/** Covers the map while a dataset loads, saying which phase it is in. */ +@Composable +fun LoadingOverlay( + phase: LoadPhase, + modifier: Modifier = Modifier, + /** What is loading, for the text: "polygons" or "roads". */ + shapes: String = "polygons", +) { + var fraction: Float? = null + val text = + when (phase) { + is LoadPhase.Read -> { + val loaded = String.format(Locale.US, "%.1f", phase.loaded / MB) + val total = phase.total?.takeIf { it > 0 } + if (total != null) { + fraction = (phase.loaded.toFloat() / total).coerceIn(0f, 1f) + "Loading data… $loaded / ${String.format(Locale.US, "%.1f", total / MB)} MB" + } else { + "Loading data… $loaded MB" + } + } + + LoadPhase.Decode -> "Reading the $shapes…" + LoadPhase.Build -> "Preparing the $shapes…" + LoadPhase.Draw -> "Drawing the map…" + } + Box( + modifier = + modifier + .fillMaxSize() + .background(Color(0x590F172A)), + contentAlignment = Alignment.Center, + ) { + Column( + modifier = + Modifier + .width(260.dp) + .background(Color.White, RoundedCornerShape(10.dp)) + .padding(horizontal = 20.dp, vertical = 16.dp), + horizontalAlignment = Alignment.CenterHorizontally, + verticalArrangement = Arrangement.spacedBy(10.dp), + ) { + CircularProgressIndicator(modifier = Modifier.size(28.dp), strokeWidth = 3.dp, color = Color(0xFF2563EB)) + Text(text, fontSize = 14.sp, color = Color(0xFF0F172A)) + fraction?.let { + LinearProgressIndicator(progress = { + it + }, modifier = Modifier.fillMaxWidth(), color = Color(0xFF2563EB)) + } + } + } +} + +/** What a tapped polygon carries, shown in an InfoBubble at the tap. */ +@Composable +fun PolygonInfo(building: Building) { + val rows = mutableListOf>() + val use = building.use + if (use != null) { + rows += "Land use" to use.label + } else { + building.name?.let { rows += "Name" to it } + rows += "Height" to (building.height?.let { "$it m" } ?: "unknown") + } + rows += "Area" to formatArea(areaSquareMetres(building)) + val vertices = building.rings.sumOf { it.size / 2 } + rows += "Vertices" to (if (building.rings.size > 1) "$vertices (holes ${building.rings.size - 1})" else "$vertices") + Column { + rows.forEach { (key, value) -> + Row { + Text( + key, + fontSize = 12.sp, + fontWeight = FontWeight.SemiBold, + color = Color(0xFF475569), + modifier = Modifier.width(84.dp), + ) + Text(value, fontSize = 12.sp, color = Color(0xFF0F172A)) + } + } + } +} + +/** "1,234 m²", or hectares from 10,000 m² up. */ +fun formatArea(squareMetres: Double): String = + if (squareMetres >= 10_000) { + String.format(Locale.US, "%.2f ha", squareMetres / 10_000) + } else { + String.format(Locale.US, "%,.0f m²", squareMetres) + } diff --git a/example-app/src/main/java/com/mapconductor/example/pages/polyline/basic/PolylinePageViewModel.kt b/example-app/src/main/java/com/mapconductor/example/pages/polyline/basic/PolylinePageViewModel.kt index fb510eaa..6c08bd4b 100644 --- a/example-app/src/main/java/com/mapconductor/example/pages/polyline/basic/PolylinePageViewModel.kt +++ b/example-app/src/main/java/com/mapconductor/example/pages/polyline/basic/PolylinePageViewModel.kt @@ -1,118 +1,117 @@ -package com.mapconductor.example.pages.polyline - -import androidx.compose.ui.graphics.Color -import androidx.compose.ui.unit.dp -import androidx.lifecycle.ViewModel -import com.mapconductor.core.features.GeoPoint -import com.mapconductor.core.map.MapCameraPosition -import com.mapconductor.core.map.MapViewStateInterface -import com.mapconductor.core.marker.DefaultMarkerIcon -import com.mapconductor.core.marker.MarkerState -import com.mapconductor.core.polyline.PolylineState -import kotlinx.coroutines.flow.MutableStateFlow -import kotlinx.coroutines.flow.StateFlow -import kotlinx.coroutines.flow.asStateFlow - -interface PolylinePageViewModelInterface { - val initCameraPosition: MapCameraPosition - val mapViewState: StateFlow?> - - val wayPointMarkers: List - val polylineState: PolylineState - - fun onMapViewChanged(state: MapViewStateInterface<*>) - - fun onMarkerDrag(dragged: MarkerState) -} - -class PolylinePageViewModel : - ViewModel(), - PolylinePageViewModelInterface { - override val initCameraPosition = - MapCameraPosition( - position = - GeoPoint.fromLatLong( - latitude = 21.382314, - longitude = -157.933097, - ), - zoom = 15.0, - bearing = 0.0, - tilt = 0.0, - paddings = null, - ) - - // Kept as a read-only list and replaced as a whole on every drag: PolylineState - // only hears assignments to its fields, so editing a list it already holds in - // place would never reach the map. - private var polylinePoints: List = - listOf( - GeoPoint.fromLatLong(21.382314, -157.933097), // Honolulu center - GeoPoint.fromLatLong(21.385314, -157.930097), // Northeast - GeoPoint.fromLatLong(21.387314, -157.935097), // Northwest - GeoPoint.fromLatLong(21.380314, -157.937097), // Southwest - GeoPoint.fromLatLong(21.378314, -157.930097), // Southeast - GeoPoint.fromLatLong(21.382314, -157.933097), // Back to center - ) - - override val wayPointMarkers: List = - polylinePoints.mapIndexed { index, point -> - val markerColor = - when { - index == 0 -> Color.Green - index == polylinePoints.size - 1 -> Color.Green - else -> Color.Yellow - } - val label = - when { - index == 0 -> "S" - index == polylinePoints.size - 1 -> "E" - else -> "$index" - } - MarkerState( - id = "waypoint_$index", - position = point, - icon = - DefaultMarkerIcon( - fillColor = markerColor, - strokeColor = Color.Black, - label = label, - ), - draggable = true, - extra = index, - onDragStart = this::onMarkerDrag, - onDrag = this::onMarkerDrag, - onDragEnd = this::onMarkerDrag, - ) - } - - override val polylineState = - PolylineState( - id = "example_polyline", - points = polylinePoints, - strokeColor = Color.Red, - strokeWidth = 4.dp, - geodesic = true, - ) - - private val _mapViewState = MutableStateFlow?>(null) - override val mapViewState: StateFlow?> = _mapViewState.asStateFlow() - - override fun onMapViewChanged(state: MapViewStateInterface<*>) { - mapViewState.value?.cameraPosition?.let { - state.moveCameraTo(it) - } - this._mapViewState.value = state - } - - override fun onMarkerDrag(dragged: MarkerState) { - (dragged.extra as? Int)?.let { index -> - if (index !in polylinePoints.indices) return - polylinePoints = - polylinePoints.mapIndexed { i, point -> - if (i == index) GeoPoint.from(dragged.position) else point - } - polylineState.points = polylinePoints - } - } - -} +package com.mapconductor.example.pages.polyline + +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.unit.dp +import androidx.lifecycle.ViewModel +import com.mapconductor.core.features.GeoPoint +import com.mapconductor.core.map.MapCameraPosition +import com.mapconductor.core.map.MapViewStateInterface +import com.mapconductor.core.marker.DefaultMarkerIcon +import com.mapconductor.core.marker.MarkerState +import com.mapconductor.core.polyline.PolylineState +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow + +interface PolylinePageViewModelInterface { + val initCameraPosition: MapCameraPosition + val mapViewState: StateFlow?> + + val wayPointMarkers: List + val polylineState: PolylineState + + fun onMapViewChanged(state: MapViewStateInterface<*>) + + fun onMarkerDrag(dragged: MarkerState) +} + +class PolylinePageViewModel : + ViewModel(), + PolylinePageViewModelInterface { + override val initCameraPosition = + MapCameraPosition( + position = + GeoPoint.fromLatLong( + latitude = 21.382314, + longitude = -157.933097, + ), + zoom = 15.0, + bearing = 0.0, + tilt = 0.0, + paddings = null, + ) + + // Kept as a read-only list and replaced as a whole on every drag: PolylineState + // only hears assignments to its fields, so editing a list it already holds in + // place would never reach the map. + private var polylinePoints: List = + listOf( + GeoPoint.fromLatLong(21.382314, -157.933097), // Honolulu center + GeoPoint.fromLatLong(21.385314, -157.930097), // Northeast + GeoPoint.fromLatLong(21.387314, -157.935097), // Northwest + GeoPoint.fromLatLong(21.380314, -157.937097), // Southwest + GeoPoint.fromLatLong(21.378314, -157.930097), // Southeast + GeoPoint.fromLatLong(21.382314, -157.933097), // Back to center + ) + + override val wayPointMarkers: List = + polylinePoints.mapIndexed { index, point -> + val markerColor = + when { + index == 0 -> Color.Green + index == polylinePoints.size - 1 -> Color.Green + else -> Color.Yellow + } + val label = + when { + index == 0 -> "S" + index == polylinePoints.size - 1 -> "E" + else -> "$index" + } + MarkerState( + id = "waypoint_$index", + position = point, + icon = + DefaultMarkerIcon( + fillColor = markerColor, + strokeColor = Color.Black, + label = label, + ), + draggable = true, + extra = index, + onDragStart = this::onMarkerDrag, + onDrag = this::onMarkerDrag, + onDragEnd = this::onMarkerDrag, + ) + } + + override val polylineState = + PolylineState( + id = "example_polyline", + points = polylinePoints, + strokeColor = Color.Red, + strokeWidth = 4.dp, + geodesic = true, + ) + + private val _mapViewState = MutableStateFlow?>(null) + override val mapViewState: StateFlow?> = _mapViewState.asStateFlow() + + override fun onMapViewChanged(state: MapViewStateInterface<*>) { + mapViewState.value?.cameraPosition?.let { + state.moveCameraTo(it) + } + this._mapViewState.value = state + } + + override fun onMarkerDrag(dragged: MarkerState) { + (dragged.extra as? Int)?.let { index -> + if (index !in polylinePoints.indices) return + polylinePoints = + polylinePoints.mapIndexed { i, point -> + if (i == index) GeoPoint.from(dragged.position) else point + } + polylineState.points = polylinePoints + } + } +} diff --git a/example-app/src/main/java/com/mapconductor/example/pages/polyline/boston/BostonRoadsPage.kt b/example-app/src/main/java/com/mapconductor/example/pages/polyline/boston/BostonRoadsPage.kt index f3ee6808..906ffa16 100644 --- a/example-app/src/main/java/com/mapconductor/example/pages/polyline/boston/BostonRoadsPage.kt +++ b/example-app/src/main/java/com/mapconductor/example/pages/polyline/boston/BostonRoadsPage.kt @@ -1,280 +1,280 @@ -package com.mapconductor.example.pages.polyline.boston - -import androidx.compose.foundation.background -import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Box -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.Row -import androidx.compose.foundation.layout.calculateEndPadding -import androidx.compose.foundation.layout.calculateStartPadding -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.height -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.layout.width -import androidx.compose.foundation.layout.widthIn -import androidx.compose.foundation.shape.RoundedCornerShape -import androidx.compose.material3.Button -import androidx.compose.material3.FilledTonalButton -import androidx.compose.material3.Text -import androidx.compose.runtime.Composable -import androidx.compose.runtime.LaunchedEffect -import androidx.compose.runtime.collectAsState -import androidx.compose.runtime.remember -import androidx.compose.runtime.withFrameNanos -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.graphics.Color -import androidx.compose.ui.platform.LocalContext -import androidx.compose.ui.text.font.FontWeight -import androidx.compose.ui.unit.LayoutDirection -import androidx.compose.ui.unit.dp -import androidx.compose.ui.unit.sp -import com.mapconductor.compose.MapViewScope -import com.mapconductor.compose.circle.Circle -import com.mapconductor.compose.info.InfoBubble -import com.mapconductor.compose.marker.Marker -import com.mapconductor.compose.polygon.Polygons -import com.mapconductor.compose.polyline.PolylineTiling -import com.mapconductor.compose.polyline.Polylines -import com.mapconductor.core.features.GeoPoint -import com.mapconductor.core.polygon.PolygonState -import com.mapconductor.example.MapViewContainer -import com.mapconductor.example.pages.polygon.boston.LoadingOverlay -import com.mapconductor.example.ui.DefaultMapViewItems -import com.mapconductor.example.ui.DemoMapPageScaffold -import com.mapconductor.example.ui.MessageCard -import java.util.Locale -import android.app.Activity - -@Composable -fun BostonRoadsPage( - modifier: Modifier = Modifier, - onToggleSidebar: () -> Unit = {}, -) { - val context = LocalContext.current - // `adb shell am start ... --es page boston-roads --es camera "42.3555,-71.0605,15" --es tiling off` - // opens a fixed view, so a measurement sees the same thing on every provider. - val viewModel = - remember { - val intent = (context as? Activity)?.intent - BostonRoadsViewModel( - context = context.applicationContext, - initCamera = intent?.getStringExtra("camera"), - initTiling = - when (intent?.getStringExtra("tiling")) { - "off" -> false - "on" -> true - else -> null - }, - initOverlap = intent?.getStringExtra("overlap") == "on", - ) - } - - DemoMapPageScaffold( - menuItems = DefaultMapViewItems(viewModel.initCameraPosition), - onToggleSidebar = onToggleSidebar, - onMapViewStateChanged = viewModel::onMapViewChanged, - ) { paddingValues -> - val mapViewState = viewModel.mapViewState.collectAsState() - val states = viewModel.polylineStates.collectAsState() - val tiling = viewModel.tiling.collectAsState() - val overlap = viewModel.overlap.collectAsState() - val loadError = viewModel.loadError.collectAsState() - val stats = viewModel.stats.collectAsState() - val tap = viewModel.tap.collectAsState() - val progress = viewModel.progress.collectAsState() - - // Two frames after the list reaches Polylines(), for the stats. The loading overlay waits for onAdded. - LaunchedEffect(states.value) { - val shown = states.value - withFrameNanos {} - withFrameNanos {} - viewModel.onDrawn(shown) - } - - mapViewState.value?.let { - MapViewContainer( - state = it, - modifier = modifier.padding(paddingValues), - onMapClick = viewModel::onMapClick, - ) { - // Before Polylines(): read when the roads are handed over. - PolylineTiling(viewModel.tilingOptions(tiling.value)) - Polylines(states.value) - if (overlap.value) OverlapCheck() - val shownTap = tap.value - val road = shownTap?.road - val point = shownTap?.point - if (road != null && point != null) { - InfoBubble(position = point, borderWidth = 1.dp, borderColor = Color(0x33000000)) { - RoadInfo(road) - } - } - } - } - - progress.value?.let { LoadingOverlay(it, modifier = Modifier.padding(paddingValues), shapes = "roads") } - - Column( - modifier = - Modifier - .align(Alignment.TopStart) - .padding(top = paddingValues.calculateTopPadding() + 16.dp, start = 16.dp), - verticalArrangement = Arrangement.spacedBy(8.dp), - ) { - Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { - listOf(true to "Tiles", false to "Native").forEach { (tiled, label) -> - if (tiling.value == tiled) { - Button(onClick = {}) { Text(label) } - } else { - FilledTonalButton(onClick = { viewModel.setTiling(tiled) }) { Text(label) } - } - } - if (overlap.value) { - Button(onClick = { viewModel.setOverlap(false) }) { Text("Overlap check") } - } else { - FilledTonalButton(onClick = { viewModel.setOverlap(true) }) { Text("Overlap check") } - } - } - } - - MessageCard( - title = - stats.value?.let { "Boston roads: ${it.roads} polylines, ${it.points} points" } - ?: "Boston roads", - isCardOpen = true, - maxHeight = 300.dp, - modifier = - Modifier - .align(Alignment.BottomStart) - .widthIn(max = 480.dp) - .padding( - bottom = paddingValues.calculateBottomPadding() + 16.dp, - start = paddingValues.calculateStartPadding(LayoutDirection.Ltr) + 16.dp, - end = paddingValues.calculateEndPadding(LayoutDirection.Ltr) + 16.dp, - ), - ) { - loadError.value?.let { Text(it) } - RoadClassLegend(modifier = Modifier.padding(vertical = 4.dp)) - stats.value?.let { - val how = if (it.tiled) "tiles" else "native" - val frame = it.frameMillis?.let { ms -> ", next frame $ms ms" } ?: "" - val added = it.addedMillis?.let { ms -> ", on the map $ms ms" } ?: "" - Text("[$how] Load ${it.loadMillis} ms, states ${it.buildMillis} ms$frame$added") - } - tap.value?.let { tap -> - val road = tap.road - Text( - if (road == null) { - "No road here" - } else { - "${road.name ?: road.roadClass.label} · ${road.roadClass.label} · ${ - formatLength( - lengthMetres( - road - ) - ) - }" - }, - ) - } - Text(ROADS_ATTRIBUTION, fontSize = 11.sp) - } - } -} - -/** The road classes: a line as wide and as coloured as on the map, two to a row. */ -@Composable -fun RoadClassLegend(modifier: Modifier = Modifier) { - Column(modifier = modifier, verticalArrangement = Arrangement.spacedBy(2.dp)) { - RoadClass.entries.chunked(2).forEach { row -> - Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp)) { - row.forEach { roadClass -> - Row(modifier = Modifier.weight(1f), verticalAlignment = Alignment.CenterVertically) { - Box( - modifier = - Modifier - .width(18.dp) - .height(roadClass.width.dp) - .background(roadClass.color, RoadedEnds), - ) - Text(roadClass.label, fontSize = 11.sp, modifier = Modifier.padding(start = 6.dp)) - } - } - if (row.size == 1) Box(modifier = Modifier.weight(1f)) - } - } - } -} - -private val RoadedEnds = RoundedCornerShape(50) - -/** What a tapped road carries, shown in an InfoBubble at the point on the road nearest the tap. */ -@Composable -fun RoadInfo(road: Road) { - val rows = mutableListOf>() - rows += "Class" to road.roadClass.label - road.name?.let { rows += "Name" to it } - rows += "Length" to formatLength(lengthMetres(road)) - rows += "Points" to "${road.path.size / 2}" - Column { - rows.forEach { (key, value) -> - Row { - Text( - key, - fontSize = 12.sp, - fontWeight = FontWeight.SemiBold, - color = Color(0xFF475569), - modifier = Modifier.width(64.dp), - ) - Text(value, fontSize = 12.sp, color = Color(0xFF0F172A)) - } - } - } -} - -/** "123 m", or kilometres from 1,000 m up. */ -fun formatLength(metres: Double): String = - if (metres >= 1000) { - String.format(Locale.US, "%.2f km", metres / 1000) - } else { - String.format(Locale.US, "%,.0f m", metres) - } - -/** - * The stacking check: over the roads downtown, a grid of 2,500 small polygons - * (enough to be drawn as polygon tiles), a circle and a marker. From the bottom - * the map shows polygon tiles, the circle, the road tiles, then the marker. - */ -@Composable -private fun MapViewScope.OverlapCheck() { - val polygons = - remember { - List(2500) { i -> - val lat = 42.3500 + (i / 50) * 0.0002 - val lng = -71.0660 + (i % 50) * 0.0002 - PolygonState( - points = - listOf( - GeoPoint(lat, lng), - GeoPoint(lat, lng + 0.00016), - GeoPoint(lat + 0.00016, lng + 0.00016), - GeoPoint(lat + 0.00016, lng), - ), - id = "overlap-$i", - fillColor = Color(0xCC7C3AED), - strokeColor = Color(0xFF4C1D95), - strokeWidth = 1.dp, - ) - } - } - Polygons(polygons) - Circle( - center = GeoPoint(42.3550, -71.0610), - radiusMeters = 250.0, - id = "overlap-circle", - fillColor = Color(0xCC0EA5E9), - strokeColor = Color(0xFF0369A1), - ) - Marker(position = GeoPoint(42.3550, -71.0610), id = "overlap-marker") -} +package com.mapconductor.example.pages.polyline.boston + +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.calculateEndPadding +import androidx.compose.foundation.layout.calculateStartPadding +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.layout.widthIn +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material3.Button +import androidx.compose.material3.FilledTonalButton +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.collectAsState +import androidx.compose.runtime.remember +import androidx.compose.runtime.withFrameNanos +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.LayoutDirection +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import com.mapconductor.compose.MapViewScope +import com.mapconductor.compose.circle.Circle +import com.mapconductor.compose.info.InfoBubble +import com.mapconductor.compose.marker.Marker +import com.mapconductor.compose.polygon.Polygons +import com.mapconductor.compose.polyline.PolylineTiling +import com.mapconductor.compose.polyline.Polylines +import com.mapconductor.core.features.GeoPoint +import com.mapconductor.core.polygon.PolygonState +import com.mapconductor.example.MapViewContainer +import com.mapconductor.example.pages.polygon.boston.LoadingOverlay +import com.mapconductor.example.ui.DefaultMapViewItems +import com.mapconductor.example.ui.DemoMapPageScaffold +import com.mapconductor.example.ui.MessageCard +import java.util.Locale +import android.app.Activity + +@Composable +fun BostonRoadsPage( + modifier: Modifier = Modifier, + onToggleSidebar: () -> Unit = {}, +) { + val context = LocalContext.current + // `adb shell am start ... --es page boston-roads --es camera "42.3555,-71.0605,15" --es tiling off` + // opens a fixed view, so a measurement sees the same thing on every provider. + val viewModel = + remember { + val intent = (context as? Activity)?.intent + BostonRoadsViewModel( + context = context.applicationContext, + initCamera = intent?.getStringExtra("camera"), + initTiling = + when (intent?.getStringExtra("tiling")) { + "off" -> false + "on" -> true + else -> null + }, + initOverlap = intent?.getStringExtra("overlap") == "on", + ) + } + + DemoMapPageScaffold( + menuItems = DefaultMapViewItems(viewModel.initCameraPosition), + onToggleSidebar = onToggleSidebar, + onMapViewStateChanged = viewModel::onMapViewChanged, + ) { paddingValues -> + val mapViewState = viewModel.mapViewState.collectAsState() + val states = viewModel.polylineStates.collectAsState() + val tiling = viewModel.tiling.collectAsState() + val overlap = viewModel.overlap.collectAsState() + val loadError = viewModel.loadError.collectAsState() + val stats = viewModel.stats.collectAsState() + val tap = viewModel.tap.collectAsState() + val progress = viewModel.progress.collectAsState() + + // Two frames after the list reaches Polylines(), for the stats. The loading overlay waits for onAdded. + LaunchedEffect(states.value) { + val shown = states.value + withFrameNanos {} + withFrameNanos {} + viewModel.onDrawn(shown) + } + + mapViewState.value?.let { + MapViewContainer( + state = it, + modifier = modifier.padding(paddingValues), + onMapClick = viewModel::onMapClick, + ) { + // Before Polylines(): read when the roads are handed over. + PolylineTiling(viewModel.tilingOptions(tiling.value)) + Polylines(states.value) + if (overlap.value) OverlapCheck() + val shownTap = tap.value + val road = shownTap?.road + val point = shownTap?.point + if (road != null && point != null) { + InfoBubble(position = point, borderWidth = 1.dp, borderColor = Color(0x33000000)) { + RoadInfo(road) + } + } + } + } + + progress.value?.let { LoadingOverlay(it, modifier = Modifier.padding(paddingValues), shapes = "roads") } + + Column( + modifier = + Modifier + .align(Alignment.TopStart) + .padding(top = paddingValues.calculateTopPadding() + 16.dp, start = 16.dp), + verticalArrangement = Arrangement.spacedBy(8.dp), + ) { + Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { + listOf(true to "Tiles", false to "Native").forEach { (tiled, label) -> + if (tiling.value == tiled) { + Button(onClick = {}) { Text(label) } + } else { + FilledTonalButton(onClick = { viewModel.setTiling(tiled) }) { Text(label) } + } + } + if (overlap.value) { + Button(onClick = { viewModel.setOverlap(false) }) { Text("Overlap check") } + } else { + FilledTonalButton(onClick = { viewModel.setOverlap(true) }) { Text("Overlap check") } + } + } + } + + MessageCard( + title = + stats.value?.let { "Boston roads: ${it.roads} polylines, ${it.points} points" } + ?: "Boston roads", + isCardOpen = true, + maxHeight = 300.dp, + modifier = + Modifier + .align(Alignment.BottomStart) + .widthIn(max = 480.dp) + .padding( + bottom = paddingValues.calculateBottomPadding() + 16.dp, + start = paddingValues.calculateStartPadding(LayoutDirection.Ltr) + 16.dp, + end = paddingValues.calculateEndPadding(LayoutDirection.Ltr) + 16.dp, + ), + ) { + loadError.value?.let { Text(it) } + RoadClassLegend(modifier = Modifier.padding(vertical = 4.dp)) + stats.value?.let { + val how = if (it.tiled) "tiles" else "native" + val frame = it.frameMillis?.let { ms -> ", next frame $ms ms" } ?: "" + val added = it.addedMillis?.let { ms -> ", on the map $ms ms" } ?: "" + Text("[$how] Load ${it.loadMillis} ms, states ${it.buildMillis} ms$frame$added") + } + tap.value?.let { tap -> + val road = tap.road + Text( + if (road == null) { + "No road here" + } else { + "${road.name ?: road.roadClass.label} · ${road.roadClass.label} · ${ + formatLength( + lengthMetres( + road, + ), + ) + }" + }, + ) + } + Text(ROADS_ATTRIBUTION, fontSize = 11.sp) + } + } +} + +/** The road classes: a line as wide and as coloured as on the map, two to a row. */ +@Composable +fun RoadClassLegend(modifier: Modifier = Modifier) { + Column(modifier = modifier, verticalArrangement = Arrangement.spacedBy(2.dp)) { + RoadClass.entries.chunked(2).forEach { row -> + Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp)) { + row.forEach { roadClass -> + Row(modifier = Modifier.weight(1f), verticalAlignment = Alignment.CenterVertically) { + Box( + modifier = + Modifier + .width(18.dp) + .height(roadClass.width.dp) + .background(roadClass.color, RoadedEnds), + ) + Text(roadClass.label, fontSize = 11.sp, modifier = Modifier.padding(start = 6.dp)) + } + } + if (row.size == 1) Box(modifier = Modifier.weight(1f)) + } + } + } +} + +private val RoadedEnds = RoundedCornerShape(50) + +/** What a tapped road carries, shown in an InfoBubble at the point on the road nearest the tap. */ +@Composable +fun RoadInfo(road: Road) { + val rows = mutableListOf>() + rows += "Class" to road.roadClass.label + road.name?.let { rows += "Name" to it } + rows += "Length" to formatLength(lengthMetres(road)) + rows += "Points" to "${road.path.size / 2}" + Column { + rows.forEach { (key, value) -> + Row { + Text( + key, + fontSize = 12.sp, + fontWeight = FontWeight.SemiBold, + color = Color(0xFF475569), + modifier = Modifier.width(64.dp), + ) + Text(value, fontSize = 12.sp, color = Color(0xFF0F172A)) + } + } + } +} + +/** "123 m", or kilometres from 1,000 m up. */ +fun formatLength(metres: Double): String = + if (metres >= 1000) { + String.format(Locale.US, "%.2f km", metres / 1000) + } else { + String.format(Locale.US, "%,.0f m", metres) + } + +/** + * The stacking check: over the roads downtown, a grid of 2,500 small polygons + * (enough to be drawn as polygon tiles), a circle and a marker. From the bottom + * the map shows polygon tiles, the circle, the road tiles, then the marker. + */ +@Composable +private fun MapViewScope.OverlapCheck() { + val polygons = + remember { + List(2500) { i -> + val lat = 42.3500 + (i / 50) * 0.0002 + val lng = -71.0660 + (i % 50) * 0.0002 + PolygonState( + points = + listOf( + GeoPoint(lat, lng), + GeoPoint(lat, lng + 0.00016), + GeoPoint(lat + 0.00016, lng + 0.00016), + GeoPoint(lat + 0.00016, lng), + ), + id = "overlap-$i", + fillColor = Color(0xCC7C3AED), + strokeColor = Color(0xFF4C1D95), + strokeWidth = 1.dp, + ) + } + } + Polygons(polygons) + Circle( + center = GeoPoint(42.3550, -71.0610), + radiusMeters = 250.0, + id = "overlap-circle", + fillColor = Color(0xCC0EA5E9), + strokeColor = Color(0xFF0369A1), + ) + Marker(position = GeoPoint(42.3550, -71.0610), id = "overlap-marker") +} diff --git a/example-app/src/main/java/com/mapconductor/example/pages/polyline/click/PolylineClickPageViewModel.kt b/example-app/src/main/java/com/mapconductor/example/pages/polyline/click/PolylineClickPageViewModel.kt index a9ac1b94..2aaf3607 100644 --- a/example-app/src/main/java/com/mapconductor/example/pages/polyline/click/PolylineClickPageViewModel.kt +++ b/example-app/src/main/java/com/mapconductor/example/pages/polyline/click/PolylineClickPageViewModel.kt @@ -1,87 +1,86 @@ -package com.mapconductor.example.pages.polyline - -import androidx.compose.ui.graphics.Color -import androidx.compose.ui.unit.dp -import androidx.lifecycle.ViewModel -import com.mapconductor.core.features.GeoPoint -import com.mapconductor.core.map.MapCameraPosition -import com.mapconductor.core.map.MapViewStateInterface -import com.mapconductor.core.marker.DefaultMarkerIcon -import com.mapconductor.core.marker.MarkerAnimation -import com.mapconductor.core.marker.MarkerState -import com.mapconductor.core.polyline.PolylineEvent -import com.mapconductor.core.polyline.PolylineState -import kotlinx.coroutines.flow.MutableStateFlow -import kotlinx.coroutines.flow.StateFlow -import kotlinx.coroutines.flow.asStateFlow - -interface PolylineClickPageViewModelInterface { - val initCameraPosition: MapCameraPosition - val mapViewState: StateFlow?> - - val markers: StateFlow> - val polylineState: PolylineState - - fun onMapViewChanged(state: MapViewStateInterface<*>) - - fun onPolylineClicked(clicked: PolylineEvent) -} - -class PolylineClickPageViewModel : - ViewModel(), - PolylineClickPageViewModelInterface { - override val initCameraPosition = - MapCameraPosition( - position = - GeoPoint.fromLatLong(35.548852, 139.784086), - zoom = 4.0, - bearing = 0.0, - tilt = 0.0, - paddings = null, - ) - - private val polylinePoints = - listOf( - GeoPoint.fromLatLong(35.548852, 139.784086), // HND_AIR_PORT - GeoPoint.fromLatLong(37.615223, -122.389979), // SFO_AIR_PORT - GeoPoint.fromLatLong(21.324513, -157.925074), // HNL_AIR_PORT - ) - - private var _markers: MutableStateFlow> = MutableStateFlow(emptyList()) - - override val markers: StateFlow> = _markers.asStateFlow() - - override val polylineState = - PolylineState( - id = "example_polyline", - points = polylinePoints, - strokeColor = Color.Red, - strokeWidth = 4.dp, - geodesic = true, - onClick = this::onPolylineClicked, - ) - - private val _mapViewState = MutableStateFlow?>(null) - override val mapViewState: StateFlow?> = _mapViewState.asStateFlow() - - override fun onMapViewChanged(state: MapViewStateInterface<*>) { - _markers.value = emptyList() - mapViewState.value?.cameraPosition?.let { - state.moveCameraTo(it) - } - this._mapViewState.value = state - } - - override fun onPolylineClicked(clicked: PolylineEvent) { - _markers.value = _markers.value + - MarkerState( - position = clicked.clicked, - animation = MarkerAnimation.Drop, - icon = - DefaultMarkerIcon( - fillColor = clicked.state.strokeColor, - ), - ) - } - -} +package com.mapconductor.example.pages.polyline + +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.unit.dp +import androidx.lifecycle.ViewModel +import com.mapconductor.core.features.GeoPoint +import com.mapconductor.core.map.MapCameraPosition +import com.mapconductor.core.map.MapViewStateInterface +import com.mapconductor.core.marker.DefaultMarkerIcon +import com.mapconductor.core.marker.MarkerAnimation +import com.mapconductor.core.marker.MarkerState +import com.mapconductor.core.polyline.PolylineEvent +import com.mapconductor.core.polyline.PolylineState +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow + +interface PolylineClickPageViewModelInterface { + val initCameraPosition: MapCameraPosition + val mapViewState: StateFlow?> + + val markers: StateFlow> + val polylineState: PolylineState + + fun onMapViewChanged(state: MapViewStateInterface<*>) + + fun onPolylineClicked(clicked: PolylineEvent) +} + +class PolylineClickPageViewModel : + ViewModel(), + PolylineClickPageViewModelInterface { + override val initCameraPosition = + MapCameraPosition( + position = + GeoPoint.fromLatLong(35.548852, 139.784086), + zoom = 4.0, + bearing = 0.0, + tilt = 0.0, + paddings = null, + ) + + private val polylinePoints = + listOf( + GeoPoint.fromLatLong(35.548852, 139.784086), // HND_AIR_PORT + GeoPoint.fromLatLong(37.615223, -122.389979), // SFO_AIR_PORT + GeoPoint.fromLatLong(21.324513, -157.925074), // HNL_AIR_PORT + ) + + private var _markers: MutableStateFlow> = MutableStateFlow(emptyList()) + + override val markers: StateFlow> = _markers.asStateFlow() + + override val polylineState = + PolylineState( + id = "example_polyline", + points = polylinePoints, + strokeColor = Color.Red, + strokeWidth = 4.dp, + geodesic = true, + onClick = this::onPolylineClicked, + ) + + private val _mapViewState = MutableStateFlow?>(null) + override val mapViewState: StateFlow?> = _mapViewState.asStateFlow() + + override fun onMapViewChanged(state: MapViewStateInterface<*>) { + _markers.value = emptyList() + mapViewState.value?.cameraPosition?.let { + state.moveCameraTo(it) + } + this._mapViewState.value = state + } + + override fun onPolylineClicked(clicked: PolylineEvent) { + _markers.value = _markers.value + + MarkerState( + position = clicked.clicked, + animation = MarkerAnimation.Drop, + icon = + DefaultMarkerIcon( + fillColor = clicked.state.strokeColor, + ), + ) + } +} diff --git a/example-app/src/main/java/com/mapconductor/example/pages/rasterlayer/RasterHeaderProbePage.kt b/example-app/src/main/java/com/mapconductor/example/pages/rasterlayer/RasterHeaderProbePage.kt index 43c151dc..b53fb66c 100644 --- a/example-app/src/main/java/com/mapconductor/example/pages/rasterlayer/RasterHeaderProbePage.kt +++ b/example-app/src/main/java/com/mapconductor/example/pages/rasterlayer/RasterHeaderProbePage.kt @@ -1,84 +1,85 @@ -package com.mapconductor.example.pages.rasterlayer - -import androidx.compose.foundation.layout.fillMaxSize -import androidx.compose.foundation.layout.padding -import androidx.compose.runtime.Composable -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.remember -import androidx.compose.runtime.setValue -import androidx.compose.ui.Modifier -import com.mapconductor.core.features.GeoPoint -import com.mapconductor.core.map.MapCameraPosition -import com.mapconductor.core.map.MapViewStateInterface -import com.mapconductor.core.raster.RasterLayerSource -import com.mapconductor.core.raster.RasterLayerState -import com.mapconductor.example.ui.DefaultMapViewItems -import com.mapconductor.example.ui.DemoMapPageScaffold - -/** - * `RasterHeaderInstrumentedTest` が使う計測ページ。 - * - * `RasterLayerState` の `userAgent` / `extraHeaders` が**実際にタイル要求に載るか**を - * プロバイダごとに確かめる。タイルの取得はプロバイダのネイティブ SDK が握っているので、 - * 送り出す側のコードを読んでも「載っているか」は分からない。受け取る側を立てて - * 届いたヘッダをそのまま読む。 - * - * タイルの配信元 URL は [probeTemplate] にテストが入れる。Android の計装テストは - * アプリと**同じプロセス**で動くので、テスト側で立てたサーバの URL をそのまま渡せる。 - * - * ページを別に用意しているのは、通常の `RasterLayerMapPage` は地理院タイルを見に行く - * ためで、計測には使えないから。プロバイダの選択は `--es provider ` に従う - * ([DemoMapPageScaffold] が見る既存の仕組み)。 - */ -@Composable -fun RasterHeaderProbePage( - modifier: Modifier = Modifier, - onToggleSidebar: () -> Unit = {}, -) { - val camera = - remember { - MapCameraPosition( - position = GeoPoint(latitude = 35.681236, longitude = 139.767125), - zoom = 8.0, - ) - } - val rasterLayerState = - remember { - RasterLayerState( - source = - RasterLayerSource.UrlTemplate( - template = probeTemplate ?: "http://127.0.0.1:1/tiles/{z}/{x}/{y}.png", - tileSize = 256, - ), - userAgent = probeUserAgent, - extraHeaders = probeExtraHeaders, - id = "raster_header_probe", - ) - } - - var mapViewState by remember { mutableStateOf?>(null) } - - DemoMapPageScaffold( - menuItems = DefaultMapViewItems(camera), - onToggleSidebar = onToggleSidebar, - onMapViewStateChanged = { mapViewState = it }, - ) { paddings -> - RasterLayerMapComponent( - mapViewState = mapViewState, - rasterLayerState = rasterLayerState, - modifier = modifier - .fillMaxSize() - .padding(paddings), - ) - } -} - -/** テストが立てた計測サーバの URL テンプレート。 */ -var probeTemplate: String? = null - -/** 送信を期待する User-Agent。 */ -var probeUserAgent: String = RasterLayerState.DEFAULT_USER_AGENT - -/** 送信を期待する追加ヘッダ。 */ -var probeExtraHeaders: Map? = null +package com.mapconductor.example.pages.rasterlayer + +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.padding +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import com.mapconductor.core.features.GeoPoint +import com.mapconductor.core.map.MapCameraPosition +import com.mapconductor.core.map.MapViewStateInterface +import com.mapconductor.core.raster.RasterLayerSource +import com.mapconductor.core.raster.RasterLayerState +import com.mapconductor.example.ui.DefaultMapViewItems +import com.mapconductor.example.ui.DemoMapPageScaffold + +/** + * `RasterHeaderInstrumentedTest` が使う計測ページ。 + * + * `RasterLayerState` の `userAgent` / `extraHeaders` が**実際にタイル要求に載るか**を + * プロバイダごとに確かめる。タイルの取得はプロバイダのネイティブ SDK が握っているので、 + * 送り出す側のコードを読んでも「載っているか」は分からない。受け取る側を立てて + * 届いたヘッダをそのまま読む。 + * + * タイルの配信元 URL は [probeTemplate] にテストが入れる。Android の計装テストは + * アプリと**同じプロセス**で動くので、テスト側で立てたサーバの URL をそのまま渡せる。 + * + * ページを別に用意しているのは、通常の `RasterLayerMapPage` は地理院タイルを見に行く + * ためで、計測には使えないから。プロバイダの選択は `--es provider ` に従う + * ([DemoMapPageScaffold] が見る既存の仕組み)。 + */ +@Composable +fun RasterHeaderProbePage( + modifier: Modifier = Modifier, + onToggleSidebar: () -> Unit = {}, +) { + val camera = + remember { + MapCameraPosition( + position = GeoPoint(latitude = 35.681236, longitude = 139.767125), + zoom = 8.0, + ) + } + val rasterLayerState = + remember { + RasterLayerState( + source = + RasterLayerSource.UrlTemplate( + template = probeTemplate ?: "http://127.0.0.1:1/tiles/{z}/{x}/{y}.png", + tileSize = 256, + ), + userAgent = probeUserAgent, + extraHeaders = probeExtraHeaders, + id = "raster_header_probe", + ) + } + + var mapViewState by remember { mutableStateOf?>(null) } + + DemoMapPageScaffold( + menuItems = DefaultMapViewItems(camera), + onToggleSidebar = onToggleSidebar, + onMapViewStateChanged = { mapViewState = it }, + ) { paddings -> + RasterLayerMapComponent( + mapViewState = mapViewState, + rasterLayerState = rasterLayerState, + modifier = + modifier + .fillMaxSize() + .padding(paddings), + ) + } +} + +/** テストが立てた計測サーバの URL テンプレート。 */ +var probeTemplate: String? = null + +/** 送信を期待する User-Agent。 */ +var probeUserAgent: String = RasterLayerState.DEFAULT_USER_AGENT + +/** 送信を期待する追加ヘッダ。 */ +var probeExtraHeaders: Map? = null diff --git a/example-app/src/main/java/com/mapconductor/example/pages/rasterlayer/RasterLayerPageViewModel.kt b/example-app/src/main/java/com/mapconductor/example/pages/rasterlayer/RasterLayerPageViewModel.kt index afa63452..b7464812 100644 --- a/example-app/src/main/java/com/mapconductor/example/pages/rasterlayer/RasterLayerPageViewModel.kt +++ b/example-app/src/main/java/com/mapconductor/example/pages/rasterlayer/RasterLayerPageViewModel.kt @@ -1,92 +1,91 @@ -package com.mapconductor.example.pages.rasterlayer - -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.setValue -import androidx.lifecycle.ViewModel -import com.mapconductor.core.features.GeoPoint -import com.mapconductor.core.map.MapCameraPosition -import com.mapconductor.core.map.MapViewStateInterface -import com.mapconductor.core.raster.RasterLayerState -import kotlinx.coroutines.flow.MutableStateFlow -import kotlinx.coroutines.flow.StateFlow -import kotlinx.coroutines.flow.asStateFlow - -interface RasterLayerPageViewModelInterface { - val initCameraPosition: MapCameraPosition - val mapViewState: StateFlow?> - var opacity: Float - - val availableLayers: List - val selectedLayer: GsiLayer - - val rasterLayerState: RasterLayerState - - fun selectLayer(layer: GsiLayer) - - fun onMapViewChanged(state: MapViewStateInterface<*>) -} - -class RasterLayerPageViewModel( - layers: List, - initialLayer: GsiLayer, -) : ViewModel(), - RasterLayerPageViewModelInterface { - init { - require(layers.isNotEmpty()) { "At least one GSI layer must be injected" } - require(layers.distinctBy(GsiLayer::id).size == layers.size) { - "Injected GSI layer IDs must be unique" - } - require(layers.any { it.id == initialLayer.id }) { - "The initial GSI layer must be included in the injected layers" - } - } - - override val availableLayers = layers.toList() - - override val initCameraPosition = - MapCameraPosition( - position = - GeoPoint.fromLatLong( - latitude = 35.6812, - longitude = 139.7671, - ), - zoom = 7.0, - bearing = 0.0, - tilt = 0.0, - paddings = null, - ) - - override var opacity by mutableStateOf(0.75f) - - override var selectedLayer by - mutableStateOf( - availableLayers.first { it.id == initialLayer.id }, - ) - private set - - override val rasterLayerState: RasterLayerState - get() = - RasterLayerState( - id = "rasterLayer", - source = selectedLayer.source, - opacity = opacity, - ) - - private val _mapViewState = MutableStateFlow?>(null) - override val mapViewState: StateFlow?> = _mapViewState.asStateFlow() - - override fun selectLayer(layer: GsiLayer) { - selectedLayer = - availableLayers.firstOrNull { it.id == layer.id } - ?: throw IllegalArgumentException("Unknown GSI layer: ${layer.id}") - } - - override fun onMapViewChanged(state: MapViewStateInterface<*>) { - mapViewState.value?.cameraPosition?.let { - state.moveCameraTo(it) - } - this._mapViewState.value = state - } - -} +package com.mapconductor.example.pages.rasterlayer + +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import androidx.lifecycle.ViewModel +import com.mapconductor.core.features.GeoPoint +import com.mapconductor.core.map.MapCameraPosition +import com.mapconductor.core.map.MapViewStateInterface +import com.mapconductor.core.raster.RasterLayerState +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow + +interface RasterLayerPageViewModelInterface { + val initCameraPosition: MapCameraPosition + val mapViewState: StateFlow?> + var opacity: Float + + val availableLayers: List + val selectedLayer: GsiLayer + + val rasterLayerState: RasterLayerState + + fun selectLayer(layer: GsiLayer) + + fun onMapViewChanged(state: MapViewStateInterface<*>) +} + +class RasterLayerPageViewModel( + layers: List, + initialLayer: GsiLayer, +) : ViewModel(), + RasterLayerPageViewModelInterface { + init { + require(layers.isNotEmpty()) { "At least one GSI layer must be injected" } + require(layers.distinctBy(GsiLayer::id).size == layers.size) { + "Injected GSI layer IDs must be unique" + } + require(layers.any { it.id == initialLayer.id }) { + "The initial GSI layer must be included in the injected layers" + } + } + + override val availableLayers = layers.toList() + + override val initCameraPosition = + MapCameraPosition( + position = + GeoPoint.fromLatLong( + latitude = 35.6812, + longitude = 139.7671, + ), + zoom = 7.0, + bearing = 0.0, + tilt = 0.0, + paddings = null, + ) + + override var opacity by mutableStateOf(0.75f) + + override var selectedLayer by + mutableStateOf( + availableLayers.first { it.id == initialLayer.id }, + ) + private set + + override val rasterLayerState: RasterLayerState + get() = + RasterLayerState( + id = "rasterLayer", + source = selectedLayer.source, + opacity = opacity, + ) + + private val _mapViewState = MutableStateFlow?>(null) + override val mapViewState: StateFlow?> = _mapViewState.asStateFlow() + + override fun selectLayer(layer: GsiLayer) { + selectedLayer = + availableLayers.firstOrNull { it.id == layer.id } + ?: throw IllegalArgumentException("Unknown GSI layer: ${layer.id}") + } + + override fun onMapViewChanged(state: MapViewStateInterface<*>) { + mapViewState.value?.cameraPosition?.let { + state.moveCameraTo(it) + } + this._mapViewState.value = state + } +} diff --git a/example-app/src/main/java/com/mapconductor/example/pages/startup/StartUpPage.kt b/example-app/src/main/java/com/mapconductor/example/pages/startup/StartUpPage.kt index 403afcb8..e26170cc 100644 --- a/example-app/src/main/java/com/mapconductor/example/pages/startup/StartUpPage.kt +++ b/example-app/src/main/java/com/mapconductor/example/pages/startup/StartUpPage.kt @@ -1,113 +1,112 @@ -package com.mapconductor.example.pages.startup - -import androidx.compose.foundation.Image -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.Spacer -import androidx.compose.foundation.layout.calculateStartPadding -import androidx.compose.foundation.layout.fillMaxSize -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.layout.size -import androidx.compose.foundation.rememberScrollState -import androidx.compose.foundation.verticalScroll -import androidx.compose.material3.Button -import androidx.compose.material3.Scaffold -import androidx.compose.material3.Text -import androidx.compose.runtime.Composable -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.res.painterResource -import androidx.compose.ui.res.stringResource -import androidx.compose.ui.text.font.FontWeight -import androidx.compose.ui.unit.LayoutDirection -import androidx.compose.ui.unit.dp -import androidx.compose.ui.unit.sp -import com.mapconductor.example.R - -@Composable -fun StartUpPage(onToggleSidebar: () -> Unit = {}) { - Scaffold { paddingValues -> - Column( - modifier = - Modifier - .fillMaxSize() - .padding( - horizontal = paddingValues.calculateStartPadding(layoutDirection = LayoutDirection.Ltr) + 10.dp, - vertical = paddingValues.calculateBottomPadding(), - ) - .verticalScroll(rememberScrollState()), - ) { - Image( - painter = painterResource(R.drawable.mapcat), - contentDescription = "MapConductor", - modifier = Modifier.align(Alignment.CenterHorizontally), - ) - - Text( - text = "MAP CONDUCTOR", - fontWeight = FontWeight.Bold, - fontSize = 42.sp, - modifier = Modifier.align(Alignment.CenterHorizontally), - ) - Text( - text = "UNIFIED MAP SDK API", - fontSize = 26.sp, - modifier = Modifier.align(Alignment.CenterHorizontally), - ) - Spacer( - modifier = Modifier.size(10.dp), - ) - Text( - text = stringResource(R.string.demo_application), - fontSize = 22.sp, - modifier = Modifier.align(Alignment.CenterHorizontally), - ) - Spacer( - modifier = Modifier.size(30.dp), - ) - Text( - text = stringResource(R.string.startup_abstract).trimIndent(), - ) - - Text( - text = stringResource(R.string.feature), - fontSize = 18.sp, - modifier = - Modifier.padding( - top = 20.dp, - bottom = 10.dp, - ), - ) - Column { - Text( - text = stringResource(R.string.feature_multi_provider).trimIndent(), - modifier = Modifier.padding(10.dp), - ) - Text( - text = stringResource(R.string.feature_unigied_interface).trimIndent(), - modifier = Modifier.padding(10.dp), - ) - Text( - text = stringResource(R.string.feature_high_performance).trimIndent(), - modifier = Modifier.padding(10.dp), - ) - Text( - text = stringResource(R.string.feature_reactive_state).trimIndent(), - modifier = Modifier.padding(10.dp), - ) - Text( - text = stringResource(R.string.feature_jetpack_compose).trimIndent(), - modifier = Modifier.padding(10.dp), - ) - } - Button( - modifier = - Modifier - .fillMaxSize() - .padding(20.dp), - onClick = onToggleSidebar, - ) { - Text(text = "Open menu") - } - } - } -} +package com.mapconductor.example.pages.startup + +import androidx.compose.foundation.Image +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.calculateStartPadding +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.verticalScroll +import androidx.compose.material3.Button +import androidx.compose.material3.Scaffold +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.res.painterResource +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.LayoutDirection +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import com.mapconductor.example.R + +@Composable +fun StartUpPage(onToggleSidebar: () -> Unit = {}) { + Scaffold { paddingValues -> + Column( + modifier = + Modifier + .fillMaxSize() + .padding( + horizontal = paddingValues.calculateStartPadding(layoutDirection = LayoutDirection.Ltr) + 10.dp, + vertical = paddingValues.calculateBottomPadding(), + ).verticalScroll(rememberScrollState()), + ) { + Image( + painter = painterResource(R.drawable.mapcat), + contentDescription = "MapConductor", + modifier = Modifier.align(Alignment.CenterHorizontally), + ) + + Text( + text = "MAP CONDUCTOR", + fontWeight = FontWeight.Bold, + fontSize = 42.sp, + modifier = Modifier.align(Alignment.CenterHorizontally), + ) + Text( + text = "UNIFIED MAP SDK API", + fontSize = 26.sp, + modifier = Modifier.align(Alignment.CenterHorizontally), + ) + Spacer( + modifier = Modifier.size(10.dp), + ) + Text( + text = stringResource(R.string.demo_application), + fontSize = 22.sp, + modifier = Modifier.align(Alignment.CenterHorizontally), + ) + Spacer( + modifier = Modifier.size(30.dp), + ) + Text( + text = stringResource(R.string.startup_abstract).trimIndent(), + ) + + Text( + text = stringResource(R.string.feature), + fontSize = 18.sp, + modifier = + Modifier.padding( + top = 20.dp, + bottom = 10.dp, + ), + ) + Column { + Text( + text = stringResource(R.string.feature_multi_provider).trimIndent(), + modifier = Modifier.padding(10.dp), + ) + Text( + text = stringResource(R.string.feature_unigied_interface).trimIndent(), + modifier = Modifier.padding(10.dp), + ) + Text( + text = stringResource(R.string.feature_high_performance).trimIndent(), + modifier = Modifier.padding(10.dp), + ) + Text( + text = stringResource(R.string.feature_reactive_state).trimIndent(), + modifier = Modifier.padding(10.dp), + ) + Text( + text = stringResource(R.string.feature_jetpack_compose).trimIndent(), + modifier = Modifier.padding(10.dp), + ) + } + Button( + modifier = + Modifier + .fillMaxSize() + .padding(20.dp), + onClick = onToggleSidebar, + ) { + Text(text = "Open menu") + } + } + } +} diff --git a/example-app/src/main/java/com/mapconductor/example/pages/vectorstyle/VectorStylePage.kt b/example-app/src/main/java/com/mapconductor/example/pages/vectorstyle/VectorStylePage.kt index c3562a51..f5471c20 100644 --- a/example-app/src/main/java/com/mapconductor/example/pages/vectorstyle/VectorStylePage.kt +++ b/example-app/src/main/java/com/mapconductor/example/pages/vectorstyle/VectorStylePage.kt @@ -187,9 +187,10 @@ fun VectorStylePage( onMapViewStateChanged = { mapViewState = it }, ) { paddings -> Box( - modifier = modifier - .fillMaxSize() - .padding(paddings), + modifier = + modifier + .fillMaxSize() + .padding(paddings), contentAlignment = Alignment.Center, ) { mapViewState?.let { state -> diff --git a/example-app/src/main/java/com/mapconductor/example/pages/vectortile/VectorTilePage.kt b/example-app/src/main/java/com/mapconductor/example/pages/vectortile/VectorTilePage.kt index 1872a13e..f88d5f35 100644 --- a/example-app/src/main/java/com/mapconductor/example/pages/vectortile/VectorTilePage.kt +++ b/example-app/src/main/java/com/mapconductor/example/pages/vectortile/VectorTilePage.kt @@ -137,9 +137,10 @@ fun VectorTilePage( onMapViewStateChanged = { mapViewState = it }, ) { paddings -> Box( - modifier = modifier - .fillMaxSize() - .padding(paddings), + modifier = + modifier + .fillMaxSize() + .padding(paddings), contentAlignment = Alignment.Center, ) { VectorTileMapComponent( @@ -222,8 +223,7 @@ fun VectorTilePage( .background( palette.getValue(category.key), RoundedCornerShape(6.dp), - ) - .border(1.dp, Color(0x33000000), RoundedCornerShape(6.dp)) + ).border(1.dp, Color(0x33000000), RoundedCornerShape(6.dp)) .clickable { picking = category.key }, ) } diff --git a/example-app/src/main/java/com/mapconductor/example/ui/MapViewStatePanel.kt b/example-app/src/main/java/com/mapconductor/example/ui/MapViewStatePanel.kt index 3d96fbab..e93a6254 100644 --- a/example-app/src/main/java/com/mapconductor/example/ui/MapViewStatePanel.kt +++ b/example-app/src/main/java/com/mapconductor/example/ui/MapViewStatePanel.kt @@ -1,38 +1,37 @@ -package com.mapconductor.example.ui - -import androidx.compose.foundation.background -import androidx.compose.foundation.layout.BoxScope -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.wrapContentHeight -import androidx.compose.material3.Text -import androidx.compose.runtime.Composable -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.graphics.Color -import com.mapconductor.core.map.MapCameraPosition -import com.mapconductor.core.toFixed - -@Composable -fun BoxScope.MapViewStatePanel(camera: MapCameraPosition?) { - Column( - modifier = - Modifier - .align(Alignment.TopEnd) - .background( - Color( - red = 0.9f, - green = 0.9f, - blue = 0.9f, - alpha = 0.75f, - ), - ) - .wrapContentHeight() - .fillMaxWidth(), - ) { - Text("LatLng: (${camera?.position?.toUrlValue()})", color = Color.Black) - Text("Zoom: ${camera?.zoom?.toFixed(2)}", color = Color.Black) - Text("bearing: ${camera?.bearing?.toInt()}", color = Color.Black) - Text("tilt: ${camera?.tilt?.toInt()}", color = Color.Black) - } -} +package com.mapconductor.example.ui + +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.BoxScope +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.wrapContentHeight +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import com.mapconductor.core.map.MapCameraPosition +import com.mapconductor.core.toFixed + +@Composable +fun BoxScope.MapViewStatePanel(camera: MapCameraPosition?) { + Column( + modifier = + Modifier + .align(Alignment.TopEnd) + .background( + Color( + red = 0.9f, + green = 0.9f, + blue = 0.9f, + alpha = 0.75f, + ), + ).wrapContentHeight() + .fillMaxWidth(), + ) { + Text("LatLng: (${camera?.position?.toUrlValue()})", color = Color.Black) + Text("Zoom: ${camera?.zoom?.toFixed(2)}", color = Color.Black) + Text("bearing: ${camera?.bearing?.toInt()}", color = Color.Black) + Text("tilt: ${camera?.tilt?.toInt()}", color = Color.Black) + } +} diff --git a/local.defaults.properties b/local.defaults.properties index 82b6f9c8..6b438199 100644 --- a/local.defaults.properties +++ b/local.defaults.properties @@ -3,3 +3,6 @@ HERE_ACCESS_KEY_SECRET=HERE_ACCESS_KEY_SECRET GOOGLE_MAPS_API_KEY=GOOGLE_MAPS_API_KEY ARCGIS_API_KEY=ARCGIS_API_KEY MAPBOX_ACCESS_TOKEN=MAPBOX_ACCESS_TOKEN +TOMTOM_API_KEY=TOMTOM_API_KEY +MAPTILER_API_KEY=MAPTILER_API_KEY +LONGDO_API_KEY=LONGDO_API_KEY