Capa GeoJSON
android-geojson-layer es un módulo independiente para mostrar datos GeoJSON sin depender de la implementación del mapa.
Como se renderiza como una capa ráster basada en mosaicos, puede usarse con cualquier SDK de mapas, incluidos Google Maps, Mapbox, MapLibre, ArcGIS y HERE.
Instalación
dependencies { implementation(platform("com.mapconductor:mapconductor-bom:1.1.7")) implementation("com.mapconductor:core") implementation("com.mapconductor:geojson-layer")
// 使用する地図 SDK を選択 implementation("com.mapconductor:for-googlemaps")}Uso básico
Crea una lista de objetos GeoJSONFeature y pásala a GeoJSONLayer dentro del bloque content de cualquier MapView.
val layerState = remember { GeoJSONLayerState() }val features = remember { listOf( GeoJSONFeature( geometry = GeoJSONGeometry.Point(longitude = 139.76, latitude = 35.68), properties = mapOf("name" to "東京駅"), ), GeoJSONFeature( geometry = GeoJSONGeometry.LineString( coordinates = listOf( LonLat(139.76, 35.68), LonLat(139.77, 35.69), ) ), ), GeoJSONFeature( geometry = GeoJSONGeometry.Polygon( rings = listOf( listOf( LonLat(139.75, 35.67), LonLat(139.77, 35.67), LonLat(139.77, 35.69), LonLat(139.75, 35.69), LonLat(139.75, 35.67), // 始点と終点を同じにする ) ) ), ), )}
MapView(...) { GeoJSONLayer( state = layerState, features = features, )}Referencia de API
Composable GeoJSONLayer
@Composablefun MapViewScope.GeoJSONLayer( state: GeoJSONLayerState = remember { GeoJSONLayerState() }, features: List<GeoJSONFeature> = emptyList(), tileSize: Int = 512, disableTileServerCache: Boolean = false, content: @Composable () -> Unit = {},)state: ElGeoJSONLayerStateque administra el estado de visualización, los estilos y el manejo de clics de la capa.features: Una lista de objetosGeoJSONFeaturepara renderizar como datos estáticos o por lote.tileSize: El tamaño de mosaico de la capa ráster.disableTileServerCache: Especifica si se deshabilita la caché del lado del servidor de mosaicos.content: Un bloque para colocar features que funcionan con el estado de Compose, comoGeoJSONFeatureState.
GeoJSONLayerState
class GeoJSONLayerState( opacity: Float = 1.0f, strokeColor: Int = Color.argb(255, 30, 136, 229), // 青系 fillColor: Int = Color.argb(128, 30, 136, 229), // 半透明青系 strokeWidth: Float = 2f, pointRadius: Float = 8f, visible: Boolean = true, minZoom: Int = 0, maxZoom: Int = 22, val onClick: ((feature: GeoJSONFeature, position: GeoPoint) -> Unit)? = null,) { fun processClick(geoPoint: GeoPoint): Boolean}processClick(geoPoint) se llama desde el manejador de clics del mapa para ejecutar hit testing de features. Cuando se encuentra una feature objetivo, llama a onClick y devuelve true.
Parámetros de GeoJSONLayerState
opacity: La opacidad de toda la capa.strokeColor: El color predeterminado de líneas y contornos de polígonos.fillColor: El color predeterminado de relleno de polígonos.strokeWidth: El valor predeterminado del ancho de línea.pointRadius: El radio predeterminado para Point / MultiPoint.visible: Especifica si la capa está visible.minZoom: El nivel de zoom mínimo en el que se muestra la capa.maxZoom: El nivel de zoom máximo en el que se muestra la capa.onClick: Callback que se invoca cuando el hit testing encuentra una feature.
GeoJSONFeature
data class GeoJSONFeature( val id: String? = null, val geometry: GeoJSONGeometry, val properties: Map<String, Any?> = emptyMap(), val strokeColor: Int? = null, // nullの場合は GeoJSONLayerState のデフォルトを使用 val fillColor: Int? = null, val strokeWidth: Float? = null, val pointRadius: Float? = null, val visible: Boolean = true,)GeoJSONFeature es adecuado para datos estáticos o datos cargados por lote. Al renderizar datasets grandes, es más eficiente pasar los datos al parámetro features de GeoJSONLayer.
Tipos de geometría
sealed class GeoJSONGeometry { data class Point(val longitude: Double, val latitude: Double) data class MultiPoint(val points: List<Point>) data class LineString(val coordinates: List<LonLat>) data class MultiLineString(val lines: List<List<LonLat>>) data class Polygon(val rings: List<List<LonLat>>) // rings[0]=外周, rings[1..]=穴 data class MultiPolygon(val polygons: List<List<List<LonLat>>>) data class GeometryCollection(val geometries: List<GeoJSONGeometry>) object Empty}
data class LonLat(val longitude: Double, val latitude: Double)En Polygon, rings[0] se trata como el anillo exterior y rings[1..] como huecos. Usa LonLat(longitude, latitude) para especificar coordenadas.
Parseo de archivos grandes
GeoJSONParser proporciona un método para parsear un InputStream completo de una vez y también parseo en streaming que procesa una feature a la vez.
object GeoJSONParser { // InputStream 全体をパースして List<GeoJSONFeature> を返す fun parseStream(inputStream: InputStream): List<GeoJSONFeature>
// 1フィーチャずつコールバック — 大容量ファイル(10MB+)向け fun streamParse(inputStream: InputStream, onFeature: (GeoJSONFeature) -> Unit)}// 大容量 GeoJSON ファイルのパースval features = GeoJSONParser.parseStream(assets.open("data.geojson"))
// 1フィーチャずつ処理(メモリ効率が良い)GeoJSONParser.streamParse(assets.open("large-data.geojson")) { feature -> // 1件ずつ処理}Eventos de clic / hit testing
Llamar a GeoJSONLayerState.processClick() desde el manejador onMapClick de MapView permite encontrar features GeoJSON en la posición tocada.
val layerState = remember { GeoJSONLayerState( onClick = { feature, position -> println("フィーチャが見つかった場合: ${feature.properties["name"]}") } )}
MapView( onMapClick = { geoPoint -> // タップ位置のフィーチャを検索 val handled = layerState.processClick(geoPoint) if (!handled) { // GeoJSON フィーチャ以外のタップ処理 } }) { GeoJSONLayer(state = layerState, features = features)}Features reactivas (GeoJSONFeatureState)
GeoJSONFeatureState es una feature que se coloca dentro del bloque content de GeoJSONLayer y admite actualizaciones de estado de Compose. Es útil para una pequeña cantidad de features que cambian con frecuencia, pero para datasets grandes se recomienda pasar objetos GeoJSONFeature mediante el parámetro features.
val featureState = remember { GeoJSONFeatureState( geometry = GeoJSONGeometry.Point(longitude = 139.76, latitude = 35.68), properties = mapOf("name" to "動的ポイント"), )}
// 動的に変化するフィーチャ(Compose state)LaunchedEffect(userLocation) { featureState.geometry = GeoJSONGeometry.Point( longitude = userLocation.longitude, latitude = userLocation.latitude, )}
MapView(...) { GeoJSONLayer(state = layerState) { // content ブロック内に GeoJSONFeatureState を配置 GeoJSONFeatureCompose(state = featureState) }}Personalización de estilos
Los estilos predeterminados de toda la capa pueden especificarse con GeoJSONLayerState. Si se configura strokeColor o fillColor en una GeoJSONFeature individual, el estilo específico de esa feature tiene prioridad.
val layerState = remember { GeoJSONLayerState( strokeColor = Color.rgb(255, 87, 34), // オレンジ fillColor = Color.argb(100, 255, 87, 34), // 半透明オレンジ strokeWidth = 3f, pointRadius = 12f, opacity = 0.9f, )}