## version-6.0 ### 3D Models # 3D Models > !3D Model Mapper :::tip Note that the MapView class instantiates the Models class and exposes it as MapView.models. Use MapView.models to utilize Models's methods. ::: ## Adding 3D Models to a Map Adding 3D models to a map can be a great way to represent landmarks to help users find key locations. They could also be used to show the location of assets or represent furniture to provide a rich indoor layout. Mappedin SDKs support models in Graphics Library Transmission Format (GLTF) and GL Transmission Format Binary (GLB) format. Models with nested meshes are not supported and should not be used. 3D Models can be added to the map using the MapView.models.add() method. The `add` method requires a Coordinate to place the model and a URL of the model file. Optionally, the model's interactivity, rotation, scale and more can also be set using the `options` parameter, which accepts a AddModelOptions. Models can be updated by calling the MapView.updateState() method. :::tip A complete example demonstrating 3D models can be found in the Mappedin Android Github repo: ModelsDemoActivity.kt ::: The following code samples demonstrate adding a 3D model to the map. ```kotlin val modelUrl = "https://appassets.androidplatform.net/assets/3d_assets/model.glb" val rotation = listOf( 0.0, 0.0, 197.0, ) val scale = AddModelOptions.Scale.PerAxis( 1.0, 1.0, 1.0, ) val coordinate = Coordinate(45, -75) val opts = AddModelOptions( interactive = true, rotation = rotation, scale = scale, verticalOffset = 0.0, visibleThroughGeometry = false, ) // Add the model mapView.models.add(coordinate, modelUrl, opts) { result -> result.onSuccess { Log.d("ModelsDemoActivity", "Successfully added model") } result.onFailure { error -> Log.e("ModelsDemoActivity", "Failed to add model: ${error.message}") } } ``` ## Mappedin 3D Model Library The Mappedin 3D Assets Library is a collection of 3D models that can be used to represent landmarks, assets, and furniture on a map. It is optimized for use with Mappedin SDKs. These models are used in the 3D Model Mapper tool, which allows you to place models on a map and customize their appearance. The ModelsDemoActivity.kt example demonstrates how to use the JSON file exported from the 3D Model Mapper to add 3D models to a map. These models are available in the Mappedin Android Demo Project in Github within the assets/3d_assets directory. ### Model List The Mappedin 3D Assets Library contains the following models. Each model's default blue color and white Mappedin logo color can be customized when adding it to the map. Bathtub Bed Bookshelf Box Cardboard Can Garbage Can Recycling Car Chair Computer Couch Couch Curved Couch Outward Curve Desk Desk Chair Dryer EV Charger Floor Lamp Fountain High Bench Hot Tub Kitchen Sink Kiosk Plant 1 Plant 2 Privacy Booth Refrigerator Round Table Self Checkout Shipping Container Shopping Shelves Stove Toilet Tree Pine Tree Pine Short Truck TV Vending Machine Washer Whiteboard Wood Stove ### Annotations # Annotations > Map annotations add visual or textual elements to maps, providing extra information about specific locations or features. Map makers can choose from many annotations included in Mappedin Maker to add to a map and access them using Mappedin SDKs. :::tip A complete example demonstrating Annotations with icons can be found in the Mappedin Android Github repo: MarkersDemoActivity.kt ::: Annotations are organized into the following groups. These are just a few examples of annotations, each group contains many more. | Annotation Group | Examples | | ----------------- | -------------------------------------------- | | Access Features | Keybox, roof access | | Building Sides | Alpha, bravo, charlie, delta | | Equipment Rooms | Boiler Room, Sprinkler control room | | Fire Ratings | Fire and smoke wall 1 hour, firewall 3 hours | | Fire Safety | Fire Blanket, Fire Hose Reel | | General Systems | Emergency Generator, Smoke Control Panel | | Hazards | Biohazard, Explosive | | Safety | Accessible Elevator, Eyewash Station | | Utility Shutoff | Gas Valve, Main Water Valve | | Ventilation | Chimney, Exhaust Fan | | Water Connections | Sprinkler FDC, Public Hydrant | | Water Systems | Fire Pump, Pressurized Water Tank | Incorporating annotations help provide a safer space for all. It allows users to easily locate key elements in the map. !Mappedin v6 Annotations ## Using Annotations An app may choose to display all annotations, annotations of a specific group or no annotations at all. The following code sample logs the name of each annotation. ```kotlin mapView.mapData.getByType(com.mappedin.models.MapDataType.ANNOTATION) { r -> r.onSuccess { annotations -> // Add markers for all annotations that have icons. annotations.forEach { annotation -> Log.d("Annotation", annotation.name) } } } ``` ## Annotation Icons Mappedin provides a set of icons to represent annotations. The example below demonstrates using these icons and placing them as Markers on the map. `Annotation.icon.url` contains the URL of the icon to use. :::tip A complete example demonstrating Annotations with icons can be found in the Mappedin Android Github repo: MarkersDemoActivity.kt ::: ```kotlin {12} mapView.mapData.getByType(com.mappedin.models.MapDataType.ANNOTATION) { r -> r.onSuccess { annotations -> val opts = AddMarkerOptions( interactive = AddMarkerOptions.Interactive.True, placement = AddMarkerOptions.Placement.Single(MarkerPlacement.CENTER), rank = AddMarkerOptions.Rank.Tier(CollisionRankingTier.HIGH), ) // Add markers for all annotations that have icons. annotations.forEach { annotation -> val iconUrl = annotation.icon?.url val markerHtml = """ """.trimIndent() mapView.markers.add(annotation, markerHtml, opts) { } } // Remove markers that are clicked on. mapView.on(Events.Click) { clickPayload -> val clickedMarker = clickPayload?.markers?.firstOrNull() ?: return@on mapView.markers.remove(clickedMarker) { } } } } ``` ### API Reference # API Reference ## Latest Version Mappedin SDK for Android v6.2.0-alpha.2 ## Previous Versions v6.2.0-alpha.1v6.1.0-alpha.1v6.0.0-alpha.1 ### Areas & Shapes # Areas & Shapes > ## Areas An Area represents a logical region on the map. They do not represent a physical attribute like a wall or desk, but rather a region that can be used to trigger events, display information, or affect wayfinding. An area is made up of a polygon stored as a GeoJSON Feature, which can be accessed using Area.geoJSON. The Feature can be passed to other methods in Mappedin SDKs. :::tip A complete example demonstrating Areas and Shapes can be found in the Mappedin Android Github repo: AreaShapesDemoActivity.kt ::: Shapes.add() accepts an FeatureCollection and can be used to display one or more areas on the map. The code snippet below demonstrates how to get an `Area` and create a `Shape` and add it to the map with a `Label`. ```kotlin private fun loadAreasAndShapes() { // Get current floor for zone avoidance mapView.currentFloor { floorResult -> floorResult.onSuccess { floor -> currentFloor = floor // Get all areas mapView.mapData.getByType(MapDataType.AREA) { result -> result.onSuccess { areas -> // Find the Forklift Area forkLiftArea = areas.find { it.name == "Forklift Area" } forkLiftArea?.let { area -> createShapeFromArea( area, "Maintenance Area", "red", 0.7, 0.2, 0.1, ) } // Find the Maintenance Area maintenanceArea = areas.find { it.name == "Maintenance Area" } maintenanceArea?.let { area -> createShapeFromArea( area, "Forklift Area", "orange", 0.7, 0.2, 1.0, ) } // Get origin and destination for paths setupPathEndpoints() } } } } } private fun createShapeFromArea( area: Area, labelText: String, color: String, opacity: Double, altitude: Double, height: Double, ) { // Get the GeoJSON Feature from the area val feature = area.geoJSON ?: return // Create a FeatureCollection containing the single Feature val featureCollection = FeatureCollection(features = listOf(feature)) // Draw the shape using the strongly-typed API mapView.shapes.add( featureCollection, PaintStyle(color = color, opacity = opacity, altitude = altitude, height = height), ) {} // Label the area mapView.labels.add(area, labelText) {} } ``` Within Mappedin Maker, it is possible to create an area and set it to be off limits for wayfinding. This means that the area will be excluded from the route calculation and directions will be rerouted around the area. This is useful for creating areas that are permanently off limits. At runtime, it is also possible to use an area as an exclusion zone for wayfinding. This is useful for creating areas that are temporarily off limits. Below is a code snippet that demonstrates how to use an `Area` to define a region that a wayfinding route should avoid at runtime. Refer to the Dynamic Routing section of the Wayfinding Guide for an interactive example that demonstrates clicking to set an exclusion zone. DirectionZone is the type of the GetDirectionsOptions.zones property that is passed to MapData.getDirections, MapData.getDirectionsMultiDestination() and MapData.getDistance(). These zones can be used to affect the route calculation by excluding a polygon from the route. :::tip A complete example demonstrating Areas and Shapes can be found in the Mappedin Android Github repo: AreaShapesDemoActivity.kt ::: The following code snippet demonstrates how to use an `Area` to define a region that a wayfinding route should avoid. ```kotlin private fun drawPath(avoidZone: Boolean) { // Remove existing paths mapView.paths.removeAll() val originTarget = origin val destinationTarget = destination if (originTarget == null || destinationTarget == null || maintenanceArea == null) { return } // Create NavigationTargets val from = when (originTarget) { is com.mappedin.models.MapObject -> NavigationTarget.MapObjectTarget(originTarget) else -> return } val to = when (destinationTarget) { is com.mappedin.models.Door -> NavigationTarget.DoorTarget(destinationTarget) else -> return } // Create zone for avoidance if needed val options = if (avoidZone && maintenanceArea?.geoJSON != null && currentFloor != null) { val feature = maintenanceArea!!.geoJSON!! if (feature.geometry != null) { val zone = DirectionZone( cost = Double.MAX_VALUE, floor = currentFloor, geometry = feature, ) GetDirectionsOptions(zones = listOf(zone)) } else { null } } else { null } // Get directions mapView.mapData.getDirections(from, to, options) { result -> result.onSuccess { directions -> if (directions != null) { android.util.Log.d("AreaShapes", "Got directions! Distance: ${directions.distance}m") // Draw the path val pathColor = if (avoidZone) "cornflowerblue" else "green" mapView.paths.add( directions.coordinates, AddPathOptions(color = pathColor), ) {} } else { android.util.Log.w("AreaShapes", "getDirections returned null - no path found!") } } result.onFailure { error -> android.util.Log.e("AreaShapes", "getDirections failed: ${error.message}", error) } } } ``` ## Shapes The Shapes class draws 3 dimensional shapes on top of a map. The shapes are created using GeoJSON geometry, which could be a Polygon, MultiPolygon (array of polygons) or a LineString. :::tip Access the Shapes class through the MapView class using MapView.shapes. ::: Shapes are added by calling Shapes.add() and removed individually by calling Shapes.remove() and passing in the Shape object to be removed. All shapes can be removed at once by calling Shapes.removeAll(). The following code example adds a shape to the map. ```kotlin mapView.shapes.add( shapeGeometry, PaintStyle( color = "red", altitude = 0.2, height = 2.0, opacity = 0.7, ), ) { result -> result.onSuccess { createdShape -> shape = createdShape } } ``` ### Building & Floor Selection # Building & Floor Selection > ## Floor Selection When mapping a building with multiple floors, each floor has its own unique map. These are represented by the Floor class, which are accessed using MapData.getByType(). The currently displayed Floor can be accessed using MapView.currentFloor. :::tip A complete example demonstrating Building and Floor Selection can be found in the Mappedin Android Github repo: BuildingFloorSelectionDemoActivity.kt ::: ### Changing Floors When initialized, MapView displays the Floor with the elevation that's closest to 0. This can be overridden by setting Show3DMapOptions.initialFloor to a Floor.id and passing it to MapView.show3dMap(). ```kotlin // Setting the initial floor to Floor.id 'm_123456789'. mapView.show3dMap(Show3DMapOptions(initialFloor = "m_123456789")) { r -> r.onSuccess { // Successfully initialized the map view. } r.onFailure { // Failed to initialize the map view. } } ``` The Floor displayed in a MapView can also be changed during runtime by calling MapView.setFloor() and passing in a Floor.id. ```kotlin // Set the floor to Floor.id 'm_987654321'. mapView.setFloor("m_987654321") { result -> result.onSuccess { Log.d("MappedinDemo", "Floor changed successfully") } } ``` ### Listening for Floor Changes Mappedin SDK for Android provides the ability to listen for floor changes on a MapView. The code below listens for the `floor-change` event and logs the new floor and building name to the console. ```kotlin mapView.on(Events.FloorChange) { payload -> payload?.let { Log.d( "MappedinDemo", "Floor changed to: ${it.floor.name} in building: ${it.floor.floorStack?.name}", ) } } ``` ## Building Selection Mappedin Maps can contain one to many buildings with each building having one to many floors. Each building has its floors organized into a FloorStack object. When multiple buildings are present, there are multiple FloorStack objects, one for each building. A FloorStack contains one to many Floor objects, each representing the map of each level of the building. The FloorStack object is accessed by using MapData.getByType(). ```kotlin // Get all floor stacks mapView.mapData.getByType(MapDataType.FLOOR_STACK) { result -> result.onSuccess { stacks -> floorStacks = stacks?.sortedBy { it.name } ?: emptyList() // Get all floors mapView.mapData.getByType(MapDataType.FLOOR) { floorsResult -> floorsResult.onSuccess { floors -> allFloors = floors ?: emptyList() Log.d("MappedinDemo", "Floors: $floors") } } } } ``` ## Determine If a Coordinate Is Inside a Building The FloorStack object has a geoJSON property that can be used to determine if a coordinate is inside a building. The code below listens for a click event on the map and determines if the clicked coordinate is inside a building. If it is, the building name is logged to the console. If it is not, a message is logged to the console. ```kotlin // Filter to get only buildings (type == "Building") buildings = floorStacks.filter { it.type == FloorStack.FloorStackType.BUILDING } mapView.on(Events.Click) { payload -> payload?.let { clickPayload -> val coordinate = clickPayload.coordinate val matchingBuildings = mutableListOf() // This demonstrates how to detect if a coordinate is within a building. // For click events, this can be detected by checking the ClickEvent.floors. // Checking the coordinate is for demonstration purposes and useful for non click events. buildings.forEach { building -> if (isCoordinateWithinFeature(coordinate, building.geoJSON)) { matchingBuildings.add(building.name) } } runOnUiThread { val message = if (matchingBuildings.isNotEmpty()) { "Coordinate is within building: ${matchingBuildings.joinToString(", ")}" } else { "Coordinate is not within any building" } Toast.makeText(this@BuildingFloorSelectionDemoActivity, message, Toast.LENGTH_SHORT).show() } } } /** * Check if a coordinate is within a GeoJSON Feature. * This implements point-in-polygon checking similar to @turf/boolean-contains. */ private fun isCoordinateWithinFeature( coordinate: Coordinate, feature: Feature?, ): Boolean { val geometry = feature?.geometry ?: return false val point = listOf(coordinate.longitude, coordinate.latitude) return when (geometry) { is Geometry.Polygon -> isPointInPolygon(point, geometry.coordinates) is Geometry.MultiPolygon -> geometry.coordinates.any { polygon -> isPointInPolygon(point, polygon) } else -> false } } /** * Check if a point is inside a polygon using the ray-casting algorithm. * The polygon is represented as a list of linear rings (first is outer, rest are holes). */ private fun isPointInPolygon( point: List, polygon: List>>, ): Boolean { if (polygon.isEmpty()) return false // Check if point is inside the outer ring val outerRing = polygon[0] if (!isPointInRing(point, outerRing)) { return false } // Check if point is inside any hole (if so, it's not in the polygon) for (i in 1 until polygon.size) { if (isPointInRing(point, polygon[i])) { return false } } return true } /** * Check if a point is inside a linear ring using the ray-casting algorithm. * This counts how many times a ray from the point crosses the polygon boundary. */ private fun isPointInRing( point: List, ring: List>, ): Boolean { if (ring.size < 4) return false // A valid ring needs at least 4 points (3 + closing point) val x = point[0] val y = point[1] var inside = false var j = ring.size - 1 for (i in ring.indices) { val xi = ring[i][0] val yi = ring[i][1] val xj = ring[j][0] val yj = ring[j][1] val intersect = ((yi > y) != (yj > y)) && (x < (xj - xi) * (y - yi) / (yj - yi) + xi) if (intersect) { inside = !inside } j = i } return inside } ``` :::tip A complete example demonstrating Building and Floor Selection can be found in the Mappedin Android Github repo: BuildingFloorSelectionDemoActivity.kt ::: ### Camera # Camera > Controlling the view of the map allows apps to create visually rich experiences using Mappedin SDKs. This guide shows how to focus the map view on targets, move the camera and listen to camera events. :::tip A complete example demonstrating Camera can be found in the Mappedin Android Github repo: CameraDemoActivity.kt ::: !Mappedin v6 Camera :::tip Note that the MapView class instantiates the Camera class and exposes it as MapView.Camera. Use MapView.Camera to utilize Camera's methods. ::: ## Focus the Camera on Targets Mappedin SDK for Android built in functionality to focus the camera on one ore more targets using a single or array of FocusTarget objects. When multiple targets are used, the SDK will ensure that all targets are visible. The following sample code acts on the click event to focus on the Space the user clicked on. Note that the Space must be set to interactive to allow it to be clickable. Refer to the Interactivity guide for more information on how to set a space to interactive. ```kotlin // Focus the camera on the click location. mapView.on(Events.Click) { clickPayload -> clickPayload?.coordinate?.let { coordinate -> mapView.camera.focusOn(coordinate) } } ``` ## Controlling the Camera To control the camera, set it with new pitch, bearing or zoom using Camera.set(). It accepts a CameraTarget object that contains bearing, center coordinate, pitch and zoom level. These parameters are all optional, allowing the camera to by moved by adjusting one or more of these values. ### CameraTarget - **bearing:** Bearing for the camera target in degrees. - **center:** Center `Coordinate` for the camera target. - **pitch:** Pitch for the camera target in degrees. - **zoomLevel:** Zoom level for the camera target in mercator zoom levels. ```kotlin mapView.Camera.set( CameraTarget( bearing = 30, pitch = 80, zoomLevel = 19.5, center = e.coordinate, ) ) ``` ## Animation The camera can also be animated into position using the same transforms described in the Controlling the Camera section above. This is done using the Camera.animateTo() method. Similar to Camera.set(), the `animateTo` method accepts a CameraTarget object, but it is optional. This allows the camera to changed by adjusting its `bearing`, `pitch` or `zoomLevel` without specifying a new target to move to. In addition, `animateTo` also accepts CameraAnimationOptions that allow setting of the duration of the animation in milliseconds and setting the easing curve. The next code snippet animates to the center of the camera's current position and zooms in to a zoom level of 21.0, pitches the camera to 60.0 degrees and rotates the camera to 180.0 degrees over 3000 milliseconds using the easing function `ease-in-out`. ```kotlin mapView.camera.center { result -> result.onSuccess { center -> center?.let { val transform = CameraTarget( center = it, zoomLevel = 21.0, pitch = 60.0, bearing = 180.0 ) val options = CameraAnimationOptions(duration = 3000, easing = EasingFunction.EASE_IN_OUT) mapView.camera.animateTo(transform, options) {} } } } ``` The types of easing animations are defined in EasingFunction. ### EasingFunction - **Linear:** This function implies a constant rate of change. It means the animation proceeds at the same speed from start to end. There's no acceleration or deceleration, giving a very mechanical feel. - **Ease-in:** This function causes the animation to start slowly and then speed up as it progresses. Initially, there's gradual acceleration, and as the function moves forward, the rate of change increases. - **Ease-out:** Contrary to ease-in, ease-out makes the animation start quickly and then slow down towards the end. It begins with a faster rate of change and gradually decelerates. - **Ease-in-out:** This function combines both ease-in and ease-out. The animation starts slowly, speeds up in the middle, and then slows down again towards the end. It offers a balance of acceleration and deceleration. ## Resetting The Camera While there is no method in Mappedin SDKs to reset the camera to its default position, this can be easily built into an app. To do so, store the camera position after the map is shown and then use those values to reposition the camera at a later time. The code sample below stores the initial camera position. When a user clicks on a location it first focuses on that space. The next click will return the camera to its original position. ```kotlin private var defaultPitch: Double? = null private var defaultZoomLevel: Double? = null private var defaultBearing: Double? = null private var defaultCenter: Coordinate? = null ... // Store default camera values mapView.camera.pitch { result -> result.onSuccess { defaultPitch = it } } mapView.camera.zoomLevel { result -> result.onSuccess { defaultZoomLevel = it } } mapView.camera.bearing { result -> result.onSuccess { defaultBearing = it } } mapView.camera.center { result -> result.onSuccess { defaultCenter = it } } ... // Set the camera to the default position val transform = CameraTarget( zoomLevel = defaultZoomLevel, pitch = defaultPitch, bearing = defaultBearing, center = defaultCenter ) mapView.camera.set(transform) {} ``` ## Listening to Camera Events There are several camera events that can be acted on by setting a listener with mapView.on('camera-change'). The camera-change event contains a CameraTransform object. CameraTransform provides the bearing, center coordinate, pitch and zoom level. ```kotlin // Log camera change events to the console. mapView.on(Events.CameraChange) { cameraTransform -> cameraTransform?.let { Log.d( "MappedinDemo", "Camera changed to bearing: ${it.bearing}, pitch: ${it.pitch}, zoomLevel: ${it.zoomLevel}, center: Lat: ${it.center.latitude}, Lon: ${it.center.longitude}", ) } } ``` :::tip A complete example demonstrating Camera can be found in the Mappedin Android Github repo: CameraDemoActivity.kt ::: ### Connections # Connections > Map connections are pathways in multi-floor and multi-building maps that enable vertical or horizontal movement between levels, spaces or buildings. They include stairs, elevators, and escalators, providing essential links for seamless navigation and spatial continuity across the map. The Connection includes details such as name, description, floors, coordinates and more. Connection contains an array of `coordinates`, with each `coordinate` representing the location of the connection on a specific floor. In the case of an elevator, each `coordinate` would have `latitude` and `longitude` values that are the same with different `floorIds`. Stairs may have `coordinates` with the same or different `latitude` and `longitude` values on each floor, depending on whether a building's stairs are vertically aligned. The following sample code retrieves all connections from the map and logs the name of each connection. ```kotlin mapView.mapData.getByType(MapDataType.CONNECTION) { result -> result.onSuccess { connections -> Log.d("MapData", "Found ${connections.size} connections") connections.forEach { connection -> Log.d("MapData", "Connection: ${connection.name}") } } } ``` ### Enterprise Data # Enterprise Data > :::note > The Enterprise Data classes described in this guide are populated in Mappedin CMS, which requires a Solutions Tier subscription. ::: ## Enterprise Locations An EnterpriseLocation contains metadata about a location, such as its name, description, logo, phone number, social medial links, hours of operation and more. They can be accessed using the MapData.getByType() method as shown below. ```kotlin mapView.mapData.getByType(MapDataType.ENTERPRISE_LOCATION) { result -> result.onSuccess { enterpriseLocations -> } } ``` ## Enterprise Categories An EnterpriseCategory groups one or more EnterpriseLocation. These allow similar locations to be sorted in a logical fashion. For example a mall may group locations into Food Court, Footwear and Women's Fashion. They can be accessed using the MapData.getByType() method as shown below. ```kotlin mapView.mapData.getByType(MapDataType.ENTERPRISE_CATEGORY) { result -> result.onSuccess { enterpriseCategories -> } } ``` EnterpriseCategory can contain one or more sub EnterpriseCategory that are accessed from its `children` member. ## Enterprise Venue The EnterpriseVenue class holds metadata about the map, which includes the map name, supported languages, default language, top locations and more. It can be accessed using the MapData.getByType() method as shown below. ```kotlin mapView.mapData.getByType(MapDataType.ENTERPRISE_VENUE) { result -> result.onSuccess { enterpriseVenue -> } } ``` ## Search :::tip Note that the MapData class instantiates the Search class and exposes it as MapView.mapData.search. Use MapView.mapData.search to utilize Search' methods. ::: The Search functionality allows users to search for locations, categories, and other points of interest within the venue. :::tip A complete example demonstrating Search can be found in the Mappedin Android Github repo: SearchDemoActivity.kt ::: Here are two ways to enable search: 1. Enable Search on map initialization: ```kotlin // See Trial API key Terms and Conditions // https://developer.mappedin.com/docs/demo-keys-and-maps val options = GetMapDataWithCredentialsOptions( key = "5eab30aa91b055001a68e996", secret = "RJyRXKcryCMy4erZqqCbuB1NbR66QTGNXVE0x3Pg6oCIlUR1", mapId = "mappedin-demo-mall", search = SearchOptions(enabled = true) ) mapView.getMapData(options) { result -> ``` 2. Enable Search via method: ```kotlin mapView.mapData.search.enable { result -> result.onSuccess { runOnUiThread { setupSearch() } } } ``` ### Search Query Use Search.query to search for locations based on a string input: - EnterpriseLocationOptions: Specific places such as stores, restaurants, or washrooms. - EnterpriseCategoryOptions: Groups of locations, such as "Food Court" or "Electronics." - PlaceOptions: Any main objects that can be searched for such as Space, Door, PointOfInterest Search query returns a list of matching SearchResult based on the input string. SearchResult include information about the type of match, the score (relevance), and detailed metadata about the matching items. #### Example Search Query ```kotlin mapView.mapData.search.query(item.suggestion.suggestion) { result -> result.onSuccess { searchResult -> // Handle search results } } ``` ### Search Suggestions Use Search.suggest to fetch real-time suggestions based on partial input. This is useful for creating an autocomplete feature for a search bar. #### Example Code ```kotlin mapView.mapData.search.suggest(query) { result -> result.onSuccess { suggestions -> // Handle suggestions } } ``` :::tip A complete example demonstrating Search can be found in the Mappedin Android Github repo: SearchDemoActivity.kt ::: ### Getting Started # Getting Started > Mappedin SDK for Android helps to deliver the rich indoor mapping experience of a venue, inside Android apps. The Mappedin SDK for Android is a native interface to Mappedin JS. The SDK is a dependency built using Kotlin, and it automatically handles any authentication, network communication, fetching of map data, its display, and basic user interaction, such as panning, tapping, and zooming. The SDK allows a developer to build their own interactions. Additional layers can be rendered on top of the map. :::info Mappedin SDK for Android is supported on Android versions 8.0 and above. ::: ## Coding with AI Mappedin SDK for Android provides an llms-mappedin-android.txt file that can be used to help with coding when using Large Language Models (LLMs). ## Android Studio Project Setup ### Add Permissions Add the following permissions to the `AndroidManifest.xml` in the `application` tag. ```xml ``` Ensure that hardware acceleration is not turned off by setting it to `true`. ```xml ``` Ensure that the application has a large heap by setting it to `true`. ```xml ``` ### Add Application Dependency to Gradle Add the Mappedin SDK dependency to the application's `build.gradle`, `settings.gradle` or `libs.versions.toml` and sync the changes to download the SDK. The latest version can be found in in Maven Central. #### build.gradle or settings.gradle ``` implementation 'com.mappedin.sdk:mappedin:6.2.0-alpha.2' ``` #### libs.versions.toml ``` [versions] mappedin = "6.2.0-alpha.2" [libraries] mappedin = { module = "com.mappedin.sdk:mappedin", version.ref = "mappedin" } ``` :::tip The Mappedin Android Github repository contains a reference project that demonstrates how to use the Mappedin SDK for Android. ::: ### Display a Map The core class of the Mappedin SDK for Android is MapView, which is responsible for instantiating an Android WebView that loads Mappedin JS. MapView is the core class of which all other views and data models can be accessed. #### Load Map Data Call MapView.getMapData to load map data from Mappedin servers. This function must be called first and map data must be loaded before any other Mappedin functions can be called. ```kotlin // See Trial API key Terms and Conditions // https://developer.mappedin.com/docs/demo-keys-and-maps val options = GetMapDataWithCredentialsOptions( key = "mik_yeBk0Vf0nNJtpesfu560e07e5", secret = "mis_2g9ST8ZcSFb5R9fPnsvYhrX3RyRwPtDGbMGweCYKEq385431022", mapId = "64ef49e662fd90fe020bee61", ) // Load the map data. mapView.getMapData(options) { result -> result.onSuccess { Log.d("MappedinDemo", "getMapData success") } } ``` #### Show a Map Call MapView.show3dMap to display the map. ```kotlin mapView.show3dMap(Show3DMapOptions()) { result -> result.onSuccess { Log.d("MappedinDemo", "show3dMap success") } } ``` The following sample code combines the loading of map data and the display of the map and includes a function to be called when the map is ready. ```kotlin package com.mappedin.demo import android.os.Bundle import android.util.Log import android.view.Gravity import android.view.ViewGroup import android.widget.FrameLayout import android.widget.ProgressBar import androidx.appcompat.app.AppCompatActivity import com.mappedin.MapView import com.mappedin.models.GetMapDataWithCredentialsOptions import com.mappedin.models.Show3DMapOptions class DisplayMapDemoActivity : AppCompatActivity() { private lateinit var mapView: MapView private lateinit var loadingIndicator: ProgressBar override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) title = "Display a Map" // Create a FrameLayout to hold both the map view and loading indicator val container = FrameLayout(this) mapView = MapView(this) container.addView( mapView.view, ViewGroup.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, ), ) // Add loading indicator loadingIndicator = ProgressBar(this) val loadingParams = FrameLayout.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, ) loadingParams.gravity = Gravity.CENTER container.addView(loadingIndicator, loadingParams) setContentView(container) // See Trial API key Terms and Conditions // https://developer.mappedin.com/docs/demo-keys-and-maps val options = GetMapDataWithCredentialsOptions( key = "mik_yeBk0Vf0nNJtpesfu560e07e5", secret = "mis_2g9ST8ZcSFb5R9fPnsvYhrX3RyRwPtDGbMGweCYKEq385431022", mapId = "64ef49e662fd90fe020bee61", ) // Load the map data. mapView.getMapData(options) { result -> result .onSuccess { Log.d("MappedinDemo", "getMapData success") // Display the map. mapView.show3dMap(Show3DMapOptions()) { r -> r.onSuccess { runOnUiThread { loadingIndicator.visibility = android.view.View.GONE } onMapReady(mapView) } r.onFailure { runOnUiThread { loadingIndicator.visibility = android.view.View.GONE } Log.e("MappedinDemo", "show3dMap error: $it") } } }.onFailure { Log.e("MappedinDemo", "getMapData error: $it") } } } // Place your code to be called when the map is ready here. private fun onMapReady(mapView: MapView) { Log.d("MappedinDemo", "show3dMap success - Map displayed") } } ``` #### Result The app should display something that looks like this in the Android Emulator: And zooming in to have a closer look: ## Create a Key & Secret ## Debug Mode Use Debug Mode to get a closer look at how various map components behave and interact. Here's how to enable it: ### 1. Enable Debug Mode To activate the debug interface, call the following function in your code: ```kotlin mapView.enableDebug() ``` MapView.enableDebug displays a panel on the right side of the map, revealing several tools and controls for direct interaction with the map's elements. ### 2. Navigating the Debug Panel The debug panel provides access to a variety of controls: **Geometry Controls** - Adjust individual geometry settings, such as color, opacity, visibility. These controls make it easy to see how different elements respond to changes. **Interactivity** - Use toggles to turn interactivity on/off - Change colors and hover effects to highlight specific areas **Scene Controls** - Manage the overall scene settings, such as scaling, positioning, and group management. Toggle the visibility of groups or containers within the scene - Adjust padding, scale, and watermark positioning - Markers & Labels — Add, remove, or edit markers and labels directly through the panel **Camera Controls** - Fine-tune camera settings, including zoom levels, pitch, and center position - Set minimum and maximum zoom levels - Adjust the focus to a specific area or level !enable debug ### Images, Textures & Colors # Images, Textures & Colors > !Images and Textures Images, textures and colors can enhance the fidelity of an indoor map. They can be used to add custom branding, highlight important features, or provide additional information to users. Images can be placed on any Anchorable target on the map and given a `verticalOffset` to control the height at which the image is displayed. Textures can be applied to the top or sides of a MapObject, Space, Door or Wall. ## Requirements & Considerations JPEG and PNG images are supported for both images and textures. It's important to consider the size of all unique image files displayed on a map at one time. Using many unique images may cause instability on mobile devices with limited GPU memory. Mappedin SDKs will cache and reuse images that have the same URL, resulting in reduced memory usage. The following calculations illustrates how much memory is used for a given image: **Formula:** `width * height * 4 bytes/pixel = memory used` **512 x 512 Pixel Image:** `512px * 512px * 4 bytes/pixel = 1MB` **4096 x 4096 Pixel Image:** `4096px * 4096px * 4 bytes/pixel = 64MB` ## Creating Images for Spaces When creating images to be used as the floor of a space, it's important that the image dimensions match the space to avoid it leaking into adjacent spaces. An SVG export of the map can be useful to determine the correct dimensions. The following steps demonstrate how to create an image that matches a space's dimensions using Figma. Similar steps could be used in other image editing tools that support the SVG format. 1. Log into Mappedin Maker and select the map you want to create an image for. 2. Click on the **Download** button and choose `Download as SVG`. 3. Import the SVG into Figma (**File** > **Place Image**). 4. Select the geometry to create the image for by clicking near the center of it (not the edge). 5. Choose **File** > **Place** Image to place the image you want to use as the floor. 6. Click the geometry to fill. 7. Click **Export** (bottom right). 8. Choose format (PNG or JPEG), size and export. The exported image should match the dimensions of the space. ## Images The Image3D class is accessed through MapView.image3D and used to add and remove images to and from the map. Images can be placed on any Door, Space, or Coordinate. AddImageOptions is used to configure the image and specifies its width, height, rotation, vertical offset and whether the image is rotated to face the camera. The following example places an image on a Space named "Arena". :::tip A complete example demonstrating Images can be found in the Mappedin Android Github repo: Image3DDemoActivity.kt ::: ```kotlin mapView.mapData.getByType(com.mappedin.models.MapDataType.SPACE) { r -> r.onSuccess { spaces -> // Find the Arena Floor space val arenaFloor = spaces.find { it.name == "Arena Floor" } // Add the default hockey image to the arena floor arenaFloor?.let { floor -> val imageResource = getImageResource(0) val opts = AddImageOptions( width = 1014 * pixelsToMeters, height = 448 * pixelsToMeters, rotation = 239.0, verticalOffset = 1.0, flipImageToFaceCamera = false, ) mapView.image3D.add(floor, imageResource, opts) { } } } } // Helper function to get the image resource. private fun getImageResource(position: Int): String = when (position) { 0 -> "https://appassets.androidplatform.net/assets/arena_hockey.png" 1 -> "https://appassets.androidplatform.net/assets/arena_basketball.png" 2 -> "https://appassets.androidplatform.net/assets/arena_concert.png" else -> "https://appassets.androidplatform.net/assets/arena_hockey.png" } ``` ## Textures & Colors Walls, doors, floors and objects can be given textures or colors, which can be applied individually to the top or sides. The GeometryState is used to configure the texture and color, which is applied by calling MapView.updateState(). When applying textures to walls it is important to set Show3DMapOptions.shadingAndOutlines to false when calling MapView.show3dMap. This will prevent lines from being drawn between the top and side textures. Be sure to review the Requirements & Considerations section before applying textures. :::tip A complete example demonstrating Colors & Textures can be found in the Mappedin Android Github repo: ColorsAndTexturesDemoActivity.kt ::: ### Doors The top and sides of a door can be given textures or colors. The example below demonstrates how to set the color of all interior and exterior doors. Doors can also be made visible on an individual basis by passing in a Door object to MapView.updateState(). ```kotlin // Make interior doors visible, sides brown and top yellow mapView.updateState( Doors.INTERIOR, DoorsUpdateState( visible = true, color = "brown", topColor = "yellow", opacity = 0.6, ), ) // Make exterior doors visible, sides black and top blue mapView.updateState( Doors.EXTERIOR, DoorsUpdateState( visible = true, color = "black", topColor = "blue", opacity = 0.6, ), ) ``` ### Objects Objects can be given textures or colors, which can be applied individually to the top and sides. The following example demonstrates how to set the texture of the side and color of the top of all objects. ```kotlin // Update all objects with side texture and top color mapView.mapData.getByType(MapDataType.MAP_OBJECT) { result -> result.onSuccess { objects -> for (obj in objects) { mapView.updateState( obj, GeometryUpdateState( texture = GeometryUpdateState.Texture(url = objectSideURL), topColor = "#9DB2BF", ), ) } } result.onFailure { error -> Log.e("MappedinDemo", "Error getting objects: $error") } } ``` ### Spaces The floor of a space can be given a texture or color. When creating an image for the floor of a space, it's important that the image dimensions match the space to avoid it leaking into adjacent spaces. Refer to the Creating Images for Spaces section for more information. The following example demonstrates how to set the texture of the floor for all spaces. ```kotlin // Update all spaces with floor texture mapView.mapData.getByType(MapDataType.SPACE) { result -> result.onSuccess { spaces -> for (space in spaces) { mapView.updateState( space, GeometryUpdateState( topTexture = GeometryUpdateState.Texture(url = floorURL), ), ) } } result.onFailure { error -> Log.e("MappedinDemo", "Error getting spaces: $error") } } ``` ### Walls The exterior and interior walls of a building can be targeted with different textures and colors. The following example demonstrates how to set the texture of an exterior wall and the colors of interior walls. Note that both types of walls support textures and colors. ```kotlin // Update interior walls with colors mapView.updateState( Walls.INTERIOR, WallsUpdateState( color = "#526D82", topColor = "#27374D", ), ) // Update exterior walls with textures mapView.updateState( Walls.EXTERIOR, WallsUpdateState( texture = WallsTexture(url = exteriorWallURL), topTexture = WallsTexture(url = exteriorWallURL), ), ) ``` ### Interactivity # Interactivity > This guide explains how to enhance a map's interactivity by making components clickable. Interactivity can greatly improve the user experience and user engagement with a map. :::tip A complete example demonstrating interactivity can be found in the Mappedin Android Github repo: InteractivityDemoActivity.kt ::: !Mappedin v6 Interactivity ## Interactive Spaces A Space can be set to interactive to allow a user to click on it. When interactivity is enabled for a space, it enables a hover effect that highlights the space when the cursor is moved over the space. The following code enables interactivity for all spaces: ```kotlin // Set all spaces to be interactive so they can be clicked mapView.mapData.getByType(MapDataType.SPACE) { result -> result.onSuccess { spaces -> spaces.forEach { space -> mapView.updateState(space, mapOf("interactive" to true)) { } } } } ``` ## Interactive Labels A Label added to the map can be set to interactive to allow users to click on it and have the click event captured by an app. The code sample below adds a label to each space with a name and sets the label's interactivity to true. ```kotlin // Set all spaces to be interactive so they can be clicked mapView.mapData.getByType(.space) { [weak self] (result: Result<[Space], Error>) in guard let self = self else { return } if case .success(let spaces) = result { spaces.forEach { space in self.mapView.updateState(target: space, state: ["interactive": true]) { _ in } } } } ``` After enabling interactivity, click events on the label can be captured using Mapview.on(Events.Click). The Events object passed into the `on` method contains an array of labels that were clicked. The following code sample captures the click event and checks if the user clicked on a label. If they did, it logs the id of the label that was clicked and removes it from the map. ```kotlin mapView.on(Events.Click) { clickPayload -> val text = clickPayload?.labels?.firstOrNull()?.text text?.let { Log.d("MappedinDemo", "removing label: $it") } clickPayload?.labels?.firstOrNull()?.let { mapView.labels.remove(it) } } ``` ## Interactive Markers A Marker can be set to interactive, allowing it to be clickable and have an app act on the click event. The `interactive` property of a Marker can be set to `true`, `false` or `pointer-events-auto`. - `false` - The Marker is not interactive. - `true` - The Marker is interactive and the click event is captured by the `mapView.on(Events.Click)` event handler. - `pointer-events-auto` - The Marker is interactive and mouse events are passed to the Marker's HTML content. The code sample below adds a marker for each annotation and sets the marker's interactivity to true. ```kotlin mapView.mapData.getByType(com.mappedin.models.MapDataType.ANNOTATION) { r -> r.onSuccess { annotations -> val opts = AddMarkerOptions( interactive = AddMarkerOptions.Interactive.True, placement = AddMarkerOptions.Placement.Single(MarkerPlacement.CENTER), rank = AddMarkerOptions.Rank.Tier(CollisionRankingTier.HIGH), ) // Add markers for all annotations that have icons. annotations.forEach { annotation -> val iconUrl = annotation.icon?.url val markerHtml = """
${annotation.name}
""".trimIndent() mapView.markers.add(annotation, markerHtml, opts) { } } } } ``` After enabling interactivity, click events on the label can be captured using Mapview.on(Events.Click). The Events object passed into the `on` method contains an array of markers that were clicked. The following code sample captures the click event and checks if the user clicked on a marker. If they did, it logs the id of the marker that was clicked and removes it from the map. ```kotlin // Remove markers that are clicked on. mapView.on(Events.Click) { clickPayload -> val clickedMarker = clickPayload?.markers?.firstOrNull() ?: return@on mapView.markers.remove(clickedMarker) { } } ``` ## Handling Click Events Mappedin SDK for Android enables capturing and responding to click events through its event handling system. After enabling interactivity, click events can be captured using Mapview.on(Events.Click). The Events `click` event passes ClickPayload that contains the objects the user clicked on. It allows developers to obtain information about user interactions with various elements on the map, such as: 1. **coordinate** - A Coordinate object that contains the latitude and longitude of the point where the user clicked. 2. **facades** - An array of Facade objects that were clicked. 3. **floors** - An array of Floor objects. If the map contains multiple floors, floors under the click point are included. 4. **labels** - An array of Label objects that were clicked. 5. **markers** - An array of Marker objects that were clicked. 6. **models** - An array of Model objects that were clicked. 7. **objects** - An array of MapObject objects that were clicked. 8. **paths** - An array of Path objects that were clicked. 9. **pointerEvent** - A PointerEvent object that contains the pointer event data. 10. **shapes** - An array of Shape objects that were clicked. 11. **spaces** - An array of Space objects that were clicked. Use `Mapview.on(Events.Click)` to capture click events as shown below. ```kotlin // Set up click listener mapView.on(Events.CLICK) { event -> val clickPayload = event as? ClickPayload ?: return@on handleClick(clickPayload) } private fun handleClick(clickPayload: ClickPayload) { val title: String val message = StringBuilder() // Use the map name as the title (from floors) title = clickPayload.floors?.firstOrNull()?.name ?: "Map Click" // If a label was clicked, add its text to the message val labels = clickPayload.labels if (!labels.isNullOrEmpty()) { message.append("Label Clicked: ") message.append(labels.first().text) message.append("\n") } // If a space was clicked, add its location name to the message val spaces = clickPayload.spaces if (!spaces.isNullOrEmpty()) { val space = spaces.first() message.append("Space clicked: ") message.append(space.name) message.append("\n") } // If a path was clicked, add it to the message if (!clickPayload.paths.isNullOrEmpty()) { message.append("You clicked a path.\n") } // Add the coordinates clicked to the message message.append("Coordinate Clicked: \nLatitude: ") message.append(clickPayload.coordinate.latitude) message.append("\nLongitude: ") message.append(clickPayload.coordinate.longitude) Log.d("MappedinDemo", "title: $title, message: $message") } ``` :::tip A complete example demonstrating interactivity can be found in the Mappedin Android Github repo: InteractivityDemoActivity.kt ::: ### Labels # Labels > Labels display text and images anchored to specific points on a map. They rotate, show, or hide based on priority and zoom level, providing information about location names, points of interest, and more. Effective labels help apps convey additional information, such as room names, points of interest, main entrances, or other useful contextual details. :::tip A complete example demonstrating Labels can be found in the Mappedin Android Github repo: LabelsDemoActivity.kt ::: !Mappedin v6 Labels :::tip Note that the MapView class instantiates the Labels class and exposes it as MapView.labels. Use MapView.labels to utilize Labels' methods. ::: ## Adding & Removing Individual Labels Labels can be added individually to a map by calling Labels.add(). A label can be added to any Anchorable target. Refer to the Labels.add() documentation for the complete list of targets. The following code sample adds an interactive (clickable) label to each space that has a name: ```kotlin mapView.mapData.getByType(MapDataType.SPACE) { result -> result.onSuccess { spaces -> for (space in spaces) { if (space.name.isNotEmpty()) { val color = colors.random() val appearance = LabelAppearance( color = color, icon = space.images.firstOrNull()?.url ?: svgIcon, ) mapView.labels.add( target = space, text = space.name, options = AddLabelOptions(labelAppearance = appearance, interactive = true), ) } } } } ``` Labels can be removed by using the Labels.remove(label) method, passing in the label to be removed as shown below: ```kotlin mapView.labels.remove(label) ``` ## Interactive Labels Labels added to the map can be set to interactive to allow users to click on them. For more information, refer to the Interactive Labels section of the Interactivity Guide. ## Label Icons Icons can be added to labels in `SVG`, `PNG`, `JPEG` and `WebP` formats. Icons are clipped in a circle to prevent overflow. Three clipping methods of `contain`, `fill` and `cover` can be set in the LabelAppearance.iconFit parameter with `contain` being the default. | Fill | Contain | Cover (default) | | ----------------------------------------------------------- | ----------------------------------------------------------------- | ------------------------------------------------------------- | | !Floating Label fill | !Floating Label contain | !Floating Label cover | The LabelAppearance.iconPadding property sets the amount of space between the icon and the border. The icon may shrink based on this value. | `padding: 0` | `padding: 10` | | ------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------- | | !Floating Label fill with 0 padding | !Floating Label fill with 10 padding | Label icons can be configured to be shown or hidden based on the current zoom level using LabelAppearance.iconVisibleAtZoomLevel. A value below 0 will result in the icon always being hidden. Setting this value to 0 ensures icons show up at maxZoom (fully zoomed in) and 1 configures them to always be displayed. ## Label Appearance Labels can have their appearance styled to match the visual theme of an app or to make groups of labels easily distinguishable from one another. The following declaration of LabelAppearance describes these customisable attributes. | Option | Type | Description | Default | |--------|------|-------------|---------| | `margin` | `number` | Margin around the label text and pin in pixels. This will affect label density. Minimum is 6px. | 6 | | `maxLines` | `number` | Number of lines to display when text spans multiple lines. | 2 | | `textSize` | `number` | Text size in pixels | 11.5 | | `maxWidth` | `number` | Maximum width of text in pixels. | 150 | | `lineHeight` | `number` | Line height sets the height of a line box. It's commonly used to set the distance between lines of text. | 1.2 | | `color` | ColorString | A ColorString for the label text and pin. | `#333` | | `outlineColor` | ColorString | A ColorString for the outline around the label text and pin. | `white` | | `textColor` | ColorString | A ColorString representing just the text color. Defaults to the same as `color`. | - | | `textOutlineColor` | ColorString | A ColorString representing just the text outline. Defaults to the same as `outlineColor`. | - | | `pinColor` | ColorString | A ColorString representing just the pin color. Defaults to the same as `color`. | - | | `pinOutlineColor` | ColorString | A ColorString representing just the pin outline. Defaults to the same as `outlineColor`. | - | | `pinColorInactive` | ColorString | A ColorString representing just the pin color when the label is inactive. Defaults to the same as `pinColor`. | - | | `pinOutlineColorInactive` | ColorString | A ColorString representing just the pin outline when the label is inactive. Defaults to the same as `pinOutlineColor`. | - | | `icon` | `string` | An icon to be placed inside the label pin. Can be an SVG string or a path to a PNG or JPEG. | - | | `iconSize` | `number` | Size of the icon in pixels. Requires `icon` to be set. | 20 | | `iconScale` | `number` \| Interpolation | Scale the icon uniformly. Specify a number or an Interpolation object. | 1 | | `iconPadding` | `number` | Padding between the icon and the marker's border in pixels. | 2 | | `iconFit` | `'fill'` \| `'contain'` \| `'cover'` | How the icon should fit inside the marker. Options: `fill` (stretch to fill), `cover` (maintain aspect ratio and fill), `contain` (maintain aspect ratio and fit inside). | `cover` | | `iconOverflow` | `'visible'` \| `'hidden'` | Whether the icon should overflow the circle of the marker. Options: `visible`, `hidden`. | `hidden` | | `iconVisibleAtZoomLevel` | `number` | Defines the zoom level at which the icon becomes visible. Infinity ensures never visible, -Infinity ensures always visible. | -Infinity | The code sample below demonstrates how to use some label styling options. Labels are added to each space with a name using the space's image if one is set, or a default SVG icon if one is not. It also sets the label text color to a random color from a list of colors. ```kotlin val svgIcon = """ """.trimIndent() val colors = listOf("#FF610A", "#4248ff", "#891244", "#219ED4") mapView.mapData.getByType(MapDataType.SPACE) { result -> result.onSuccess { spaces -> for (space in spaces) { if (space.name.isNotEmpty()) { val color = colors.random() val appearance = LabelAppearance( color = color, icon = space.images.firstOrNull()?.url ?: svgIcon, ) mapView.labels.add( target = space, text = space.name, options = AddLabelOptions(labelAppearance = appearance, interactive = true), ) } } } } ``` ## Label Ranking Ranking can be added to labels to control which label will be shown when more than one label occupies the same space. The label with the highest rank will be shown. If labels do not overlap, ranking will have no effect. Rank values are low, medium, high, and always-visible and are defined in CollisionRankingTier. The code below add a label with a high ranking where a user clicks on the map. ```kotlin mapView.on(Events.Click) { clickPayload -> mapView.labels.add( target = clickPayload.coordinate, text = "I'm a high ranking label!", options = AddLabelOptions(rank = CollisionRankingTier.HIGH), ) } ``` ## Enabling and Disabling Labels Labels can be dynamically enabled or disabled using `mapView.updateState()`. When a label is disabled, it will be hidden from view but remain in the map's memory. This is useful for managing label visibility based on conditions like zoom level or user interaction, without the overhead of repeatedly adding and removing labels. For Mappedin JS, use `mapView.getState()` to check a label's current state, which returns the label's current properties including its enabled status. Here's an example on how to enable/disable labels on click: ```kotlin private var label: Label? = null ... mapView.on(Events.Click) { clickPayload -> if (label == null) { // Add the label if it doesn't exist. mapView.labels.add( target = clickPayload.coordinate, text = "Click to Toggle", onResult = { it.onSuccess { label = it } }, ) } else { // Toggle the label. label?.let { currentLabel -> mapView.getState( currentLabel, onResult = { result -> result.onSuccess { state -> state?.let { mapView.updateState( currentLabel, LabelUpdateState(enabled = !it.enabled), ) } } }, ) } } } ``` :::tip A complete example demonstrating Labels can be found in the Mappedin Android Github repo: LabelsDemoActivity.kt ::: ### Location Profiles & Categories # Location Profiles & Categories > A Location refers to something that represents a physical position on the map, such as an annotation, area, connection (e.g. stairs or elevator), door, point of interest or space. Locations may have a LocationProfile attached to them. The profiles contain information about the location such as its name, description, social media links, opening hours, logo and more. A LocationProfile can have zero to many LocationCategory attached to it. A LocationCategory may have a child or parent category. For example, the parent `Food & Drink` LocationCategory has children such as `Bar`, `Cafe`, `Food Court` and `Mediterranean Cuisine`. !Location Profiles & Categories :::tip A complete example demonstrating location profiles and categories can be found in the Mappedin Android Github repo: LocationsDemoActivity.kt ::: ## LocationProfile A LocationProfile can be accessed by using the `locationProfiles` property of a location. For example, use Space.locationProfiles to access every LocationProfile of a space. Every LocationProfile can also be access using the MapData.getByType() method as shown below. ```kotlin mapView.mapData.getByType(MapDataType.LOCATION_PROFILE) { result -> result.onSuccess { locationProfiles -> } } ``` ## LocationCategory To access the LocationCategory of a LocationProfile, use the LocationProfile.categories property, which contains a list of IDs of its LocationCategory. Then use the MapData.getById() method to get the LocationCategory by its ID. Note that a LocationCategory can have either parent or child categories. These are accessible using the LocationCategory.parent and LocationCategory.children properties respectively. Every LocationCategory can also be access using the MapData.getByType() method as shown below. ```kotlin mapView.mapData.getByType(MapDataType.LOCATION_CATEGORY) { result -> result.onSuccess { locationCategories -> } } ``` :::tip A complete example demonstrating location profiles and categories can be found in the Mappedin Android Github repo: LocationsDemoActivity.kt ::: ### Markers # Markers > Mappedin SDK for Android allows adding and removing Marker on a map. Markers are elements containing HTML that the Mappedin SDK anchors to any Anchorable target. They are automatically rotated and repositioned when the camera moves. :::tip A complete example demonstrating Markers can be found in the Mappedin Android Github repo: MarkersDemoActivity.kt ::: !Mappedin JS v6 Markers :::tip Note that the MapView class instantiates the Markers class and exposes it as MapView.markers. Use MapView.markers to utilize Markers' methods. ::: ## Creating Markers Markers are added to the map by referencing a target that can be a Door, Space, Coordinate or any Anchorable target. The following code sample adds a marker to a coordinate. ```kotlin val opts = AddMarkerOptions( interactive = AddMarkerOptions.Interactive.True, placement = AddMarkerOptions.Placement.Single(MarkerPlacement.CENTER), rank = AddMarkerOptions.Rank.Tier(CollisionRankingTier.HIGH), ) val markerHtml = """
This is a Marker!
""".trimIndent() mapView.markers.add(coordinate, markerHtml, opts) { } ``` ## Placement Marker placement is set using the `options` argument of Markers.add(). Options accepts a AddMarkerOptions value, which has a member named `placement`. When provided, the point of the Marker described by the Placement is placed next to the target. For example, using `MarkerPlacement.CENTER` will place the Marker's center at the target. Both a single placement and an array of placements can be provided. When an array is provided, the Marker is placed at the first target that has space available to display the Marker. Placement positions are defined in MarkerPlacement which contains 9 values. The placement points are as follows, with the default being center. ### MarkerPlacement - `CENTER` - `TOP` - `LEFT` - `BOTTOM` - `RIGHT` - `top-left` - `TOP_RIGHT` - `BOTTOM_LEFT` - `BOTTOM_RIGHT` Marker content can be styled using CSS that references the placement of the marker. This can allow the creation of a tooltip or bubble-style marker that points to its target. This is done by using the CSS Selector: ```css .mappedin-marker[data-placement='']; ``` Where `` is the placement position. Here is an example of adding a triangle pointer to the Marker's target of `left`: ```CSS .marker:before { content: ''; width: 0; height: 0; top: calc(50% - 10px); left: -10px; z-index: 1; position: absolute; border-bottom: 10px solid transparent; border-top: 10px solid transparent; z-index: -1; } .mappedin-marker[data-placement="left"] .marker:before { left: auto; right: -5px; border-left: 10px solid #333333; } ``` ## Removing Markers Markers can be removed individually by using the Markers.remove(marker) method, passing in the marker to be removed as shown below. ```kotlin mapView.markers.remove(marker) { } ``` To remove all markers from a map, call Markers.removeAll(). ```kotlin mapView.markers.removeAll() { } ``` ## Marker Rank Ranking can be added to markers to control which marker will be shown when more than one marker occupies the same space. The marker with the highest rank will be shown. If markers do not overlap, ranking will have no effect. Rank values low, medium, high and always-visible as defined in CollisionRankingTier. The code below adds markers where a user clicks on the map. The marker rank is cycled with each click. If the user clicks and adds multiple markers in the same location, the marker with the highest rank is shown and lower ranking markers are hidden. ```kotlin // Ranks for marker collision priority - cycles through medium, high, always-visible private val ranks = listOf(CollisionRankingTier.MEDIUM, CollisionRankingTier.HIGH, CollisionRankingTier.ALWAYS_VISIBLE) private var rankIndex = 0 ... // Act on the click event and add a marker with a cycling rank. // Observe how higher ranking markers are shown when they collide with lower ranking markers. mapView.on(Events.Click) { clickPayload -> val currentRank = ranks[rankIndex] val rankName = currentRank.value val markerTemplate = """

Marker Rank: $rankName

""".trimIndent() // Add a marker with the current rank at the clicked coordinate. mapView.markers.add( target = clickPayload.coordinate, html = markerTemplate, options = AddMarkerOptions(rank = AddMarkerOptions.Rank.Tier(currentRank)) ) // Cycle to the next rank rankIndex++ if (rankIndex == ranks.size) { rankIndex = 0 } } ``` ## Moving Markers Markers can be repositioned after they have been added to a map. There are two ways of doing this: - Markers.setPosition() instantly repositions a Marker - Markers.animateTo() animates a Marker to a new position The Marker's position can be set to a Coordinate, Space or Door. The `animateTo` method takes an `options` parameter of AnimationOptions that defines the animation duration and EasingFunction, which can be EasingFunction.LINEAR, EasingFunction.EASE_IN, EasingFunction.EASE_OUT or EasingFunction.EASE_IN_OUT. - **Linear**: This function implies a constant rate of change. It means the animation proceeds at the same speed from start to end. There's no acceleration or deceleration, giving a very mechanical feel. - **Ease In**: This function causes the animation to start slowly and then speed up as it progresses. Initially, there's gradual acceleration, and as the function moves forward, the rate of change increases. - **Ease Out**: Contrary to ease-in, ease-out makes the animation start quickly and then slow down towards the end. It begins with a faster rate of change and gradually decelerates. - **Ease In Out**: This function combines both ease-in and ease-out. The animation starts slowly, speeds up in the middle, and then slows down again towards the end. It offers a balance of acceleration and deceleration. The code samples below displays a custom Marker when the map is first clicked. When the map is clicked again, the Marker is animated to the clicked location using the default animation options. ```kotlin private var marker: Marker? = null ... mapView.on(Events.Click) { clickPayload -> if (marker != null) { // Animate existing marker to new position mapView.markers.animateTo(marker!!, clickPayload.coordinate) } else { // Add new marker at clicked position val options = AddMarkerOptions( interactive = AddMarkerOptions.Interactive.True, placement = AddMarkerOptions.Placement.Single(MarkerPlacement.RIGHT) ) mapView.markers.add(clickPayload.coordinate, "Marker", options) { result -> result.onSuccess { newMarker -> marker = newMarker } } } } ``` ## Enabling and Disabling Markers Markers can be dynamically enabled or disabled using MapView.updateState(). When a marker is disabled, it will be hidden from view but remain in the map's memory. This is useful for managing marker visibility based on conditions like zoom level or user interaction, without the overhead of repeatedly adding and removing markers. Use MapView.getState() to check a marker's current state, which returns the marker's current properties including its enabled status. Here's an example on how to enable/disable markers on click: ```kotlin private var marker: Marker? = null ... mapView.on(Events.Click) { clickPayload -> if (marker == null) { // First click - add marker Log.d("MappedinDemo", "Adding marker at: $clickPayload.coordinate") mapView.markers.add( clickPayload.coordinate, "
Enabled Marker!
" ) { result -> result.onSuccess { newMarker -> marker = newMarker } } } else { // Get current state of marker mapView.getState(marker!!) { result -> result.onSuccess { markerState -> Log.d("MappedinDemo", "Current Marker State: $markerState") // Toggle enabled state val newState = !(markerState?.enabled ?: true) mapView.updateState(marker!!, MarkerUpdateState(enabled = newState)) Log.d("MappedinDemo", "Marker is now ${if (newState) "enabled" else "disabled"}") } } } } ``` :::tip A complete example demonstrating Markers can be found in the Mappedin Android Github repo: MarkersDemoActivity.kt ::: ### Migration Guide # Migration Guide Mappedin SDK for Android version 6.0 is a major release that includes a number of changes to the SDK. It uses a GeoJSON-based rendering engine, rebuilt from the ground up. It works in unison with MapLibre which enables outdoor base maps as well as data visualization features. By using GeoJSON as the core data format, v6 can integrate with existing external data sources. This guide explains the steps needed to migrate from version 5. ## Initialization Changes The options for getting a map have changed. `getVenue()` has been replaced by `getMapData()`. v5 Initialization ```kotlin // See Trial API key Terms and Conditions // https://developer.mappedin.com/api-keys/ mapView.loadVenue( MPIOptions.Init( "5eab30aa91b055001a68e996", "RJyRXKcryCMy4erZqqCbuB1NbR66QTGNXVE0x3Pg6oCIlUR1", "mappedin-demo-mall", ), MPIOptions.ShowVenue( shadingAndOutlines = true, multiBufferRendering = true, outdoorView = MPIOptions.OutdoorView(enabled = true), ), ) { Log.e(javaClass.simpleName, "Error loading map view") } ``` v6 Initialization ```kotlin // See Trial API key Terms and Conditions // https://developer.mappedin.com/docs/demo-keys-and-maps val options = GetMapDataWithCredentialsOptions( key = "5eab30aa91b055001a68e996", secret = "RJyRXKcryCMy4erZqqCbuB1NbR66QTGNXVE0x3Pg6oCIlUR1", mapId = "mappedin-demo-mall", ) // Load the map data. mapView.getMapData(options) { result -> result .onSuccess { Log.d("MappedinDemo", "getMapData success") // Display the map. mapView.show3dMap(Show3DMapOptions()) { r -> r.onSuccess { Log.d("MappedinDemo", "show3dMap success") } r.onFailure { Log.e("MappedinDemo", "show3dMap error: $it") } } }.onFailure { Log.e("MappedinDemo", "getMapData error: $it") } } ``` ## Component Access `MPIData.` has been replaced by `MapData.getByType()` For example: In v5 access nodes using `MPIData.nodes`, which contains an array of `Node` objects. In v6 access nodes using `mapData.getByType(MapDataType.Node)`, which returns an array of `Node` objects. `Mappedin.getCollectionItemById` is replaced by `mapData.getById(, id)` The following classes have been redesigned. Refer to the chart below for a mapping of similar classes. | v5 Component | v6 Component | | ----------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------- | | MPIPolygon | Space | | MPIMapGroup | FloorStack | | MPIMap | Floor | | MPICoordinate | Coordinate | | MPINode | Node | MPIState no longer exists. ## UI Components MPIFloatingLabelsManager has been replaced with Labels. MPIFloatingLabelsManager.labelAllLocations() will be replaced with `MapView.auto()`. MPIMarkerManager has been replaced with Markers. Tooltips have not been carried over from v5 and Markers should be used instead. ## Updating UI Components `setPolygonColor`, `clearPolygonColor` and other methods of changing the state of UI objects on the map is now performed using MapView.updateState(), which also supports `initial` for returning properties to their original state. MPICameraManager.animate() has been renamed to Camera.animateTo(). MPIMarkerManager.animate() has been renamed to Markers.animateTo(). ## Interactivity MapView.addInteractivePolygonsForAllLocations() has been replaced by updating the state of each space to be interactive as shown below. ```kotlin // Set all spaces to be interactive so they can be clicked mapView.mapData.getByType(MapDataType.SPACE) { result -> result.onSuccess { spaces -> spaces.forEach { space -> mapView.updateState(space, GeometryUpdateState(interactive = true)) { } } } } ``` Event names passed from `MapView.on()` have been changed: | v5 Event | v6 Event | | --------------------------------------------------------------- | --------------------- | | `E_SDK_EVENT.CLICK` | `Events.Click` | | `E_SDK_EVENT.MAP_CHANGED , E_SDK_EVENT.MAP_CHANGED_WITH_REASON` | `Events.FloorChange` | | `E_SDK_EVENT.OUTDOOR_VIEW_LOADED` | `Events.OutdoorViewLoaded` | ## Stacked Maps Stacked Maps APIs have been replaced with Multi Floor View along with the ability to control the visibility and altitude of floors. Refer to the Multi Floor View and Stacked Maps guides for more information. ## Map Metadata Classes containing enterprise map metadata have been renamed. | v5 Component | v6 Component | | ------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------- | | MPICategory | EnterpriseCategory | | MPILocation | EnterpriseLocation | | MPIVenue | EnterpriseVenue | ## Wayfinding & Directions MapData.getDirections() only supports getting directions between two locations. For multi destination directions, use MapData.getDirectionsMultiDestination(). MPIJourneyManager is now Navigation. ## Camera v5 MPICameraManager.tilt in radians is replaced by v6 Camera.pitch in degrees. `Camera.minPitch` and `Camera.maxPitch` are now available to set the minimum and maximum pitch values. v5 MPICameraManager.rotation in radians is replace in v6 by Camera.bearing in degrees Clockwise rotation is now positive. v5 `Camera.zoom`, `Camera.minZoom` and `Camera.maxZoom` used meters from ground level. In v6 these now use mercator zoom level units. The following camera methods and accessors have been renamed. | v5 Method | v6 Method | | ------------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------- | | MPICameraManager.position() | Camera.center() | | MPICameraManager.setSafeAreaInsets() | Camera.setScreenOffsets() | | MPICameraManager.safeAreaInsets() | Camera.screenOffsets() | | MPICameraListener | MapView.on(...) | ## Search MPISearchManager has been changed to Search. The results returned in SearchResult are more structured: ```kotlin data class SearchResult( val enterpriseCategories: List? = null, val enterpriseLocations: List? = null, val places: List ) ``` ## Multi Language The methods to work with maps in multiple languages have been changed. v6 ```kotlin // Specify a non default language when getting map data val options = GetMapDataWithCredentialsOptions( key = "5eab30aa91b055001a68e996", secret = "RJyRXKcryCMy4erZqqCbuB1NbR66QTGNXVE0x3Pg6oCIlUR1", mapId = "mappedin-demo-mall", language = "en" ) // Get supported languages mapData.getByType(MapDataType.ENTERPRISE_VENUE) { result -> result.onSuccess { venue -> venue.languages.forEach { language -> Log.d("MapData", "Language: ${language}") } } } // Change language mapData.changeLanguage("es") { result -> result.onSuccess { Log.d("MapData", "Map language changed to Spanish") } } ``` ## Blue Dot Blue Dot will be coming soon in v6.0. ## Dynamic Focus Dynamic Focus will be coming soon in v6.0. ### Multi Floor View & Stacked Maps # Multi Floor View & Stacked Maps > ## Multi Floor View Multi Floor View is a feature that displays all floors in a building stacked vertically below the active floor, allowing users to see the building's vertical structure and navigate between floors. The active floor is fully rendered while lower floors appear as semi-transparent footprints. !MultiFloor View :::tip A complete example demonstrating Multi Floor View can be found in the Mappedin Android Github repo: MultiFloorViewDemoActivity.kt ::: Multi Floor View is enabled by default. It can be controlled using the Show3DMapOptions.multiFloorView option when initializing the map view as shown in the code sample below. In this example, the map view is initialized with the `initialFloor` set to `m_952cd353abcb1a13`, which is ID of the 10th floor of the building. Other Multi Floor View options are defined in MultiFloorViewOptions and include the ability to set the gap between floors as well as whether the camera should move when the active floor changes. ### Code Sample ```kotlin // Display the map with multi-floor view enabled. val show3dMapOptions = Show3DMapOptions( multiFloorView = Show3DMapOptions.MultiFloorViewOptions( enabled = true, floorGap = 10.0, updateCameraElevationOnFloorChange = true, ) ) mapView.show3dMap(show3dMapOptions) { r -> r.onSuccess { Log.d("MappedinDemo", "show3dMap success") } r.onFailure { Log.e("MappedinDemo", "show3dMap error: $it") } } ``` It is possible to set multiple floors to be visible at once, which can be useful for overlaying data within the building, such as the locations of security cameras or other assets. This can be done by setting the visible property to true for each floor that should be shown, using FloorUpdateState as shown in the code sample below. ```kotlin // Get all floors and find the ones needed. mapView.mapData.getByType(MapDataType.FLOOR) { result -> result.onSuccess { floors -> // Set the current floor to the one with elevation 9. val floor9 = floors.find { it.elevation == 9.0 } if (floor9 != null) { mapView.setFloor(floor9.id) { Log.d("MappedinDemo", "Set floor to elevation 9: ${floor9.name}") } } // Show the 6th floor (elevation 6) as well. val floor6 = floors.find { it.elevation == 6.0 } if (floor6 != null) { mapView.updateState( floor6, FloorUpdateState( geometry = FloorUpdateState.Geometry(visible = true) ) ) { Log.d("MappedinDemo", "Made floor with elevation 6 visible: ${floor6.name}") } } } result.onFailure { Log.e("MappedinDemo", "Failed to get floors: $it") } } ``` When displaying multiple floors, by default content such as labels, markers, paths and images are only visible on the active floor. These can be displayed on additional visible floors by enabling them for the floor using FloorUpdateState as shown below. ```kotlin mapView.updateState( floor, FloorUpdateState( visible = true, altitude = 0.0, geometry = FloorUpdateState.Geometry(visible = true), images = FloorUpdateState.Images(visible = true), labels = FloorUpdateState.Labels(enabled = true), markers = FloorUpdateState.Markers(enabled = true), paths = FloorUpdateState.Paths(visible = true) ) ) { result -> result.onSuccess { // Handle success } result.onFailure { // Handle failure } } ``` ## Stacked Maps Stacked Maps consist of individual layers that represent different floors of a multi-story building. These layers are conceptually or digitally stacked to create a complete view of the structure, allowing users to visualize, navigate, and interact with multiple floors in an integrated way. !Stacked Maps :::tip A complete example demonstrating Stacked Maps can be found in the Mappedin Android Github repo: StackedMapsDemoActivity.kt ::: Stacked Maps can be enabled by setting the visibility of floors that should appear in the stack to `true` and altering their altitude defined in FloorUpdateState, so that each floor is raised above the previous floor. There are two ways to modify the visibility and altitude of a floor: 1. MapView.animateState() gradually moves the floor to the new altitude over a specified duration of time. 2. MapView.updateState() instantly snaps the floor to the new altitude. Alternative visualization methods can also be created by using variations of this technique. For example, an app may wish to only show the top and bottom floors of a building, or only show the floors that are currently accessible to the user by setting the visibility of the floors to `true` or `false` based on the app's requirements. When displaying multiple floors, by default content such as labels, markers, paths and images are only visible on the active floor. These can be displayed on additional visible floors by enabling them for the floor using FloorUpdateState as shown below. ```kotlin mapView.updateState( floor, FloorUpdateState( images = FloorUpdateState.Images(visible = true), labels = FloorUpdateState.Labels(enabled = true), markers = FloorUpdateState.Markers(enabled = true), paths = FloorUpdateState.Paths(visible = true) ) ) { result -> result.onSuccess { // Handle success } result.onFailure { // Handle failure } } ``` When using Stacked Maps with Dynamic Focus (coming soon) or Navigation, the `MapView.manualFloorVisibility` property should be set to `true` to ensure that the floors remain visible. Otherwise they could be hidden by the Dynamic Focus or Navigation features, which by default will hide all floors that are not the active floor. ### Stacked Maps Utility Class The following utility class can be used to expand and collapse the stacked maps view using the `animateState` or `updateState` methods. ```kotlin package com.mappedin.demo import com.mappedin.MapView import com.mappedin.data.MapData import com.mappedin.models.Floor import com.mappedin.models.FloorUpdateState import com.mappedin.models.MapDataType /** * Options for expanding floors in a stacked view. * * @param distanceBetweenFloors The vertical spacing between floors in meters. Default: 10 * @param animate Whether to animate the floor expansion. Default: true * @param cameraPanMode The camera pan mode to use ("default" or "elevation"). Default: "elevation" */ data class ExpandOptions( val distanceBetweenFloors: Double = 10.0, val animate: Boolean = true, val cameraPanMode: String = "elevation", ) /** * Options for collapsing floors back to their original positions. * * @param animate Whether to animate the floor collapse. Default: true */ data class CollapseOptions( val animate: Boolean = true, ) /** * Utility object for managing stacked floor views. * * Provides functions to expand all floors vertically (stacked view) and collapse them back * to a single floor view. This creates a 3D exploded view effect where all floors are visible * at different altitudes. * * Example usage: * ``` kotlin * // Expand floors with default options * StackedMapsUtils.expandFloors(mapView) * * // Expand floors with custom gap * StackedMapsUtils.expandFloors(mapView, ExpandOptions(distanceBetweenFloors = 20.0)) * * // Collapse floors back * StackedMapsUtils.collapseFloors(mapView) * ``` */ object StackedMapsUtils { /** * Expands all floors vertically to create a stacked view. * * Each floor is positioned at an altitude based on its elevation multiplied by the * distance between floors. This creates a 3D exploded view where all floors are visible. * * @param mapView The MapView instance * @param options Options controlling the expansion behavior */ fun expandFloors( mapView: MapView, options: ExpandOptions = ExpandOptions(), ) { // Set camera pan mode to elevation for better navigation in stacked view mapView.camera.setPanMode(options.cameraPanMode) // Get the current floor ID to identify the active floor mapView.currentFloor { currentFloorResult -> val currentFloorId = currentFloorResult.getOrNull()?.id // Get all floors mapView.mapData.getByType(MapDataType.FLOOR) { result -> result.onSuccess { floors -> floors.forEach { floor -> val newAltitude = floor.elevation * options.distanceBetweenFloors val isCurrentFloor = floor.id == currentFloorId // First, make sure the floor is visible mapView.getState(floor) { stateResult -> stateResult.onSuccess { currentState -> if (currentState != null && (!currentState.visible || !currentState.geometry.visible) ) { // Make the floor visible first with 0 opacity if not current mapView.updateState( floor, FloorUpdateState( visible = true, altitude = 0.0, geometry = FloorUpdateState.Geometry( visible = true, opacity = if (isCurrentFloor) 1.0 else 0.0, ), ), ) } // Then animate or update to the new altitude if (options.animate) { mapView.animateState( floor, FloorUpdateState( altitude = newAltitude, geometry = FloorUpdateState.Geometry( opacity = 1.0, ), ), ) } else { mapView.updateState( floor, FloorUpdateState( altitude = newAltitude, visible = true, geometry = FloorUpdateState.Geometry( visible = true, opacity = 1.0, ), ), ) } } } } } } } } /** * Collapses all floors back to their original positions. * * Floors are returned to altitude 0, and only the current floor remains fully visible. * Other floors are hidden to restore the standard single-floor view. * * @param mapView The MapView instance * @param options Options controlling the collapse behavior */ fun collapseFloors( mapView: MapView, options: CollapseOptions = CollapseOptions(), ) { // Reset camera pan mode to default mapView.camera.setPanMode("default") // Get the current floor ID to identify the active floor mapView.currentFloor { currentFloorResult -> val currentFloorId = currentFloorResult.getOrNull()?.id // Get all floors mapView.mapData.getByType(MapDataType.FLOOR) { result -> result.onSuccess { floors -> floors.forEach { floor -> val isCurrentFloor = floor.id == currentFloorId if (options.animate) { // Animate to altitude 0 and fade out non-current floors mapView.animateState( floor, FloorUpdateState( altitude = 0.0, geometry = FloorUpdateState.Geometry( opacity = if (isCurrentFloor) 1.0 else 0.0, ), ), ) // After animation, hide non-current floors if (!isCurrentFloor) { // Use a handler to delay hiding the floor android.os.Handler(android.os.Looper.getMainLooper()).postDelayed({ mapView.updateState( floor, FloorUpdateState( visible = false, altitude = 0.0, geometry = FloorUpdateState.Geometry( visible = false, opacity = 0.0, ), ), ) }, 1000) // Default animation duration } } else { mapView.updateState( floor, FloorUpdateState( altitude = 0.0, visible = isCurrentFloor, geometry = FloorUpdateState.Geometry( visible = isCurrentFloor, opacity = if (isCurrentFloor) 1.0 else 0.0, ), ), ) } } } } } } } ``` :::tip A complete example demonstrating Stacked Maps can be found in the Mappedin Android Github repo: StackedMapsDemoActivity.kt ::: ### Outdoor Map # Outdoor Map > The outdoor map shown around the Mappedin indoor map gives users context for their indoor navigation. ## Styles Styles can be applied to the outdoor map to change its colors. Mappedin provides five pre-built styles to choose from. :::info The URLs listed below can be used in Mappedin SDKs. They require authentication and cannot be used in other contexts. ::: - Classic: `https://tiles-cdn.mappedin.com/styles/mappedin/style.json` - Beach Please: `https://tiles-cdn.mappedin.com/styles/beachplease/style.json` - Honeycrisp: `https://tiles-cdn.mappedin.com/styles/honeycrisp/style.json` - Fresh Mint: `https://tiles-cdn.mappedin.com/styles/freshmint/style.json` - Night Blue: `https://tiles-cdn.mappedin.com/styles/midnightblue/style.json` - Starlight: `https://tiles-cdn.mappedin.com/styles/starlight/style.json` - Dark Roast: `https://tiles-cdn.mappedin.com/styles/darkroast/style.json` To change the style used by the Outdoor map, pass the URL of the style in the outdoorView object of Show3DMapOptions as shown below. ```kotlin mapView.show3dMap( Show3DMapOptions( outdoorView = Show3DMapOptions.OutdoorViewOptions( style = "https://tiles-cdn.mappedin.com/styles/darkroast/style.json", ), ), ) { r -> r.onSuccess { // Successfully initialized the map. } } ``` The outdoor style can also be changed at runtime using mapView.outdoor.setStyle(). ```kotlin mapView.outdoor.setStyle("https://tiles-cdn.mappedin.com/styles/midnightblue/style.json") ``` ### Points of Interest # Points of Interest > Points of Interest (POIs) are specific locations or features on a map that users find useful or informative. POIs serve as landmarks or markers, highlighting key places, services, or objects to enhance the map's utility and user experience. They are contained in the PointOfInterest class, which contains a coordinate, name, description, images, links and the floor the point of interest exists on. All of these elements are configured in Mappedin Maker. !Mappedin JS v6 POIs PointOfInterest.name could be used to create labels to show users helpful information. The following sample code demonstrates one possible use for PointOfInterest. It labels each PointOfInterest and uses Camera.animateTo() to create a flyby of each one. ```kotlin package com.mappedin.demo import android.os.Bundle import android.os.Handler import android.os.Looper import android.util.Log import android.view.Gravity import android.view.ViewGroup import android.widget.FrameLayout import android.widget.ProgressBar import androidx.appcompat.app.AppCompatActivity import com.mappedin.MapView import com.mappedin.models.Annotation import com.mappedin.models.Area import com.mappedin.models.CameraAnimationOptions import com.mappedin.models.CameraTarget import com.mappedin.models.Connection import com.mappedin.models.Door import com.mappedin.models.EasingFunction import com.mappedin.models.EnterpriseCategory import com.mappedin.models.EnterpriseLocation import com.mappedin.models.EnterpriseVenue import com.mappedin.models.Facade import com.mappedin.models.Floor import com.mappedin.models.FloorStack import com.mappedin.models.GetMapDataWithCredentialsOptions import com.mappedin.models.LocationCategory import com.mappedin.models.LocationProfile import com.mappedin.models.MapDataType import com.mappedin.models.MapObject import com.mappedin.models.Node import com.mappedin.models.PointOfInterest import com.mappedin.models.Show3DMapOptions import com.mappedin.models.Space import kotlin.math.atan2 import kotlin.math.cos import kotlin.math.floor import kotlin.math.sin class DisplayMapDemoActivity : AppCompatActivity() { private lateinit var mapView: MapView private lateinit var loadingIndicator: ProgressBar override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) title = "Display a Map" // Create a FrameLayout to hold both the map view and loading indicator val container = FrameLayout(this) mapView = MapView(this) container.addView( mapView.view, ViewGroup.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, ), ) // Add loading indicator loadingIndicator = ProgressBar(this) val loadingParams = FrameLayout.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, ) loadingParams.gravity = Gravity.CENTER container.addView(loadingIndicator, loadingParams) setContentView(container) // See Trial API key Terms and Conditions // https://developer.mappedin.com/docs/demo-keys-and-maps val options = GetMapDataWithCredentialsOptions( key = "mik_yeBk0Vf0nNJtpesfu560e07e5", secret = "mis_2g9ST8ZcSFb5R9fPnsvYhrX3RyRwPtDGbMGweCYKEq385431022", mapId = "65c0ff7430b94e3fabd5bb8c", ) // Load the map data. mapView.getMapData(options) { result -> result .onSuccess { Log.d("MappedinDemo", "getMapData success") // Display the map. mapView.show3dMap(Show3DMapOptions()) { r -> r.onSuccess { runOnUiThread { loadingIndicator.visibility = android.view.View.GONE } onMapReady(mapView) } r.onFailure { runOnUiThread { loadingIndicator.visibility = android.view.View.GONE } Log.e("MappedinDemo", "show3dMap error: $it") } } }.onFailure { Log.e("MappedinDemo", "getMapData error: $it") } } } // Place your code to be called when the map is ready here. private fun onMapReady(mapView: MapView) { Log.d("MappedinDemo", "show3dMap success - Map displayed") val animationDuration = 4000 // Get the map center as the starting point for bearing calculations. mapView.mapData.mapCenter { centerResult -> centerResult.onSuccess { mapCenter -> if (mapCenter == null) { Log.e("MappedinDemo", "Map center is null") return@onSuccess } // Get all points of interest. mapView.mapData.getByType(MapDataType.POINT_OF_INTEREST) { result -> result.onSuccess { pois -> // Start iterating through POIs with initial position from map center. animateThroughPOIs( mapView = mapView, pois = pois, index = 0, startLat = mapCenter.latitude, startLon = mapCenter.longitude, animationDuration = animationDuration, ) } result.onFailure { error -> Log.e("MappedinDemo", "Failed to get POIs: $error") } } } centerResult.onFailure { error -> Log.e("MappedinDemo", "Failed to get map center: $error") } } } /** * Recursively animates through each point of interest. */ private fun animateThroughPOIs( mapView: MapView, pois: List, index: Int, startLat: Double, startLon: Double, animationDuration: Int, ) { if (index >= pois.size) { Log.d("MappedinDemo", "Finished animating through all POIs") return } val poi = pois[index] // Label the point of interest. mapView.labels.add(target = poi.coordinate, text = poi.name) // Calculate the bearing between the current position and the POI. val bearing = calcBearing( startLat, startLon, poi.coordinate.latitude, poi.coordinate.longitude, ) // Animate to the current point of interest. mapView.camera.animateTo( target = CameraTarget( bearing = bearing, pitch = 80.0, zoomLevel = 50.0, center = poi.coordinate, ), options = CameraAnimationOptions( duration = animationDuration, easing = EasingFunction.EASE_OUT, ), ) // Wait for the animation to complete before moving to the next POI. Handler(Looper.getMainLooper()).postDelayed({ animateThroughPOIs( mapView = mapView, pois = pois, index = index + 1, startLat = poi.coordinate.latitude, startLon = poi.coordinate.longitude, animationDuration = animationDuration, ) }, animationDuration.toLong()) } /** * Calculate the bearing between two points. */ private fun calcBearing( startLat: Double, startLng: Double, destLat: Double, destLng: Double, ): Double { val startLatRad = toRadians(startLat) val startLngRad = toRadians(startLng) val destLatRad = toRadians(destLat) val destLngRad = toRadians(destLng) val y = sin(destLngRad - startLngRad) * cos(destLatRad) val x = cos(startLatRad) * sin(destLatRad) - sin(startLatRad) * cos(destLatRad) * cos(destLngRad - startLngRad) var brng = atan2(y, x) brng = toDegrees(brng) return (brng + 360) % 360 } /** Converts from degrees to radians. */ private fun toRadians(degrees: Double): Double = degrees * Math.PI / 180 /** Converts from radians to degrees. */ private fun toDegrees(radians: Double): Double = radians * 180 / Math.PI } ``` ### Release Notes # Release Notes Mappedin SDK for Android release notes are posted here and this page will be kept up-to-date as updates are released. { // Release notes template: // https://keepachangelog.com/en/1.0.0/#how // ## vXX.XX.XX - Month Day, Year // _ Added // _ Changed // _ Deprecated // _ Removed // _ Fixed // _ Security } ## 6.2.0-alpha.2 - January 8, 2026 - Upgraded to Mappedin JS v6.10.0 - Added - getDirections must also accept an array of NavigationTarget - Added - Coordinate.geoJSON - Fixed - mapView.updateState is not working on walls or doors - Fixed - getDirectionsMultiDestination's to method should use NavigationTarget not Any - Removed - Duplicated unused standalone classes of Point, LineString and MultiPolygon that are defined in Geometry ### ⚠️ Breaking Changes - Changed - Clean up remaining generic types - Changed - Strongly type .geoJSON properties - Changed - Shapes.add should be strongly typed ```kotlin // ❌ Before // Create a FeatureCollection containing the Feature of the Area val shapeFeatureCollection = JSONObject().apply { put("type", "FeatureCollection") put( "features", JSONArray().apply { put( JSONObject().apply { put("type", areaGeoJSON.optString("type")) areaGeoJSON.optJSONObject("properties")?.let { put("properties", it) } areaGeoJSON.optJSONObject("geometry")?.let { put("geometry", it) } }, ) }, ) } // Draw the shape mapView.shapes.add( shapeFeatureCollection, PaintStyle(color = color, opacity = opacity, altitude = altitude, height = height), ) {} // ✅ After // Get the GeoJSON Feature from the area val feature = area.geoJSON ?: return // Create a FeatureCollection containing the single Feature val featureCollection = FeatureCollection(features = listOf(feature)) // Draw the shape using the strongly-typed API mapView.shapes.add( featureCollection, PaintStyle(color = color, opacity = opacity, altitude = altitude, height = height), ) {} ``` ## 6.2.0-alpha.1 - December 30, 2025 - Upgraded to Mappedin JS v6.9.1. - Added - `Show3DMapOptions.preloadFloors` option to preload floors. - Added -`MultiFloorViewOptions.floorGap` option to set the gap between floors. - Fixed - `Show3DMapOptions.initialFloor` should accept only a string. ### ⚠️ Breaking Changes - Changed - Strongly type MapView.on parameters and return values ```kotlin // ❌ Before mapView.on("click") { payload -> val clickPayload = payload as? ClickPayload } // ❌ Before mapView.on(Events.CLICK) { payload -> val clickPayload = payload as? ClickPayload } // ✅ After mapView.on(Events.Click) { clickPayload -> } ``` ## 6.1.0-alpha.1 - December 19, 2025 - Added - LabelAppearance.iconScale property to control the scale of the icon. - Fixed - `MapData.getById` not returning the correct type. ### ⚠️ Breaking Changes - Fixed - Removed duplicate inline implementation of Interpolation and Width. ```kotlin // ❌ Before AddPathOptions( width = AddPathOptions.Width.Fixed(1.0), ) // ✅ After AddPathOptions( width = Width.Value(1.0), ) ``` - Fixed - `MapView.getState` and `MapView.updateState` should use data classes and not plain objects. ```kotlin // ❌ Before mapView.updateState(space, mapOf("interactive" to true)) { } // ✅ After mapView.updateState(space, GeometryUpdateState(interactive = true)) { } ``` ## 6.0.0-alpha.1 - December 4, 2025 - Upgraded to Mappedin JS v6.7.0. ## 6.0.0-alpha.0 - December 3, 2025 - Initial release of Mappedin SDK for Android v6. ### Spaces # Spaces > A Space represents an area enclosed by walls, such as a hall or room. Spaces can be Interactive and have Labels and Markers added to them. Spaces can also be customized with a color and texture. ## Spaces Example The example below loops through all spaces and makes them interactive. Refer to the Textures & Colors Guide section for more information on how to set the texture or color of a space. ```kotlin // Set all spaces to be interactive so they can be clicked mapView.mapData.getByType(MapDataType.SPACE) { result -> result.onSuccess { spaces -> spaces.forEach { space -> mapView.updateState(space, mapOf("interactive" to true)) { } } } } ``` ## Doors By default, a Door is not visible and drawn as a gap in a wall. An app can set the `visible` property to `true` to make the door visible. Other properties of a door can also be set, such as color, texture, interactivity and more. Refer to DoorsState for the complete list of properties. Refer to the Textures & Colors Guide section for more information on how to set the texture or color of a door. Doors are grouped into DOORS.Interior and DOORS.Exterior doors, based on whether they are on an interior or exterior wall. ```kotlin // Make interior doors visible and brown. mapView.updateState( Doors.INTERIOR.value, mapOf( "visible" to true, "color" to "#5C4033", "opacity" to 0.6, ), ) { } // Make exterior doors visible and black. mapView.updateState( Doors.EXTERIOR.value, mapOf( "visible" to true, "color" to "black", "opacity" to 0.6, ), ) { } ``` The screenshot below shows brown interior and black exterior doors with labels added to depict the status of the door. !Visible Doors ### Views # Views > A `view` is a copy of a map that allows a map creator to toggle the visibility of a layer or individual items in a layer on and off and choose a map theme. It is similarly named but should not be confused with the `MapView` class, which is used to show a map. Views allow the same map to be used for many use cases, such as: - Public use for wayfinding - Use one of many light or dark themes - With safety annotations for safety and security personnel - Showing private areas for maintenance and custodial staff - Displaying only the floor plan for leasing prospects - Highlighting delivery doors for delivery drivers - and many more... ## Get a View ID A `viewId` is used by Mappedin SDKs to download specific view. To get a `viewId`: 1. Log into Mappedin Maker. 2. Click on the `Developers` tab. 3. Select the desired map from the map drop down. 4. Select the desired view from the view drop down. 5. The `viewId` will be shown in the code snippet on the page. ## Display a View To display a specific view of a map, specify the `viewId` of the view using the GetMapDataWithCredentialsOptions or GetMapDataWithAccessTokenOptions objects that is passed into the MapView.getMapData() method as shown below. ```kotlin // See Trial API key Terms and Conditions // https://developer.mappedin.com/docs/demo-keys-and-maps val options = GetMapDataWithCredentialsOptions( key = "mik_yeBk0Vf0nNJtpesfu560e07e5", secret = "mis_2g9ST8ZcSFb5R9fPnsvYhrX3RyRwPtDGbMGweCYKEq385431022", mapId = "660c0c3aae0596d87766f2da", viewId = "71-i", ) // Load the map data. mapView.getMapData(options) { result -> ``` ### Wayfinding # Wayfinding > Wayfinding is the process of navigating through environments using spatial cues and instructions to efficiently reach a destination. Mappedin SDKs provide the tools needed to guide users from one location to another. It allows drawing a path between points on the map as well as creation of textual turn-by-turn directions for navigation. !Mappedin v6 Navigation ## Getting Directions Directions form the core of wayfinding. Mappedin has path finding capabilities that allow it to generate directions from one target to another. These directions are used for drawing paths and providing the user with textual turn-by-turn directions. Generate directions by calling MapData.getDirections() and pass in targets for the origin and destination. These targets are wrapped in a NavigationTarget, which can contain various types of targets. MapData.getDirections() can accept a single NavigationTarget or an array of them for the origin and destination. If an array is used, Mappedin will choose the targets that are closest to each other. An example of where this could be used is when a user asks for directions to a washroom. There may be many Spaces named Washroom. The app can pass all washroom spaces to `getDirections` and receive directions to the nearest one. Directions for some maps may appear jagged or not smooth. This is due to the SDK attempting to find the shortest path through the map's geometry. Directions can be smoothed by setting GetDirectionsOptions.smoothing to enabled in the `GetDirectionsOptions` passed to MapData.getDirections(). Directions are smoothed by default for maps created using Mappedin Maker and disabled for maps created using Mappedin CMS. ## Drawing Navigation When a user needs to get from point A to point B, drawing a path on the map helps them to navigate to their destination. It can help them to visualize the route they'll need to take, like a good treasure map. Navigation is a helper class to display wayfinding easily on the map. Functionality of Navigation could be replicated by drawing the paths using Paths and adding well designed markers at connection points. :::tip Note that the MapView class instantiates the Navigation class and exposes it as MapView.navigation. Use MapView.navigation to utilize Navigation's methods. ::: Navigation.draw() allows for easily drawing multiple components that make up a wayfinding illustration. It shows a human figure to mark the start point, a path with animated directional arrows, pulses in the direction of travel and a pin to mark the destination. Each of these components can be customized to match an app's style. The following sample uses the default navigation settings to navigate from the Cafeteria to the Gymnasium. ```kotlin // Draw an interactive navigation path from Cafeteria to Gymnasium mapView.mapData.getByType(MapDataType.SPACE) { result -> result.onSuccess { locations -> val cafeteria = locations.find { it.name == "Cafeteria" } val gymnasium = locations.find { it.name == "Gymnasium" } if (cafeteria != null && gymnasium != null) { mapView.mapData.getDirections( NavigationTarget.SpaceTarget(cafeteria), NavigationTarget.SpaceTarget(gymnasium), ) { dirResult -> dirResult.onSuccess { directions -> if (directions != null) { mapView.navigation.draw(directions) { } } } } } } } ``` The navigation visualization can be customized by passing in a NavigationOptions object to Navigation.draw(). The following example demonstrates how to customize the navigation visualization, using the `pathOptions`, `markerOptions` and `createMarkers` properties. :::tip A complete example demonstrating custom navigation markers and paths can be found in the Mappedin Android Github repo: NavigationDemoActivity.kt ::: ```kotlin private fun drawNavigation() { val pathOptions = com.mappedin.models.AddPathOptions( color = "#4b90e2", displayArrowsOnPath = true, animateDrawing = true, ) NavigationOptions( pathOptions = pathOptions, createMarkers = NavigationOptions.CreateMarkers.withCustomMarkers( departure = NavigationOptions.CreateMarkers.CreateMarkerValue.CustomMarker( template = getDepartureMarker(), options = AddMarkerOptions( rank = AddMarkerOptions.Rank.Tier(CollisionRankingTier.ALWAYS_VISIBLE), interactive = AddMarkerOptions.Interactive.True, ), ), destination = NavigationOptions.CreateMarkers.CreateMarkerValue.CustomMarker( template = getDestinationMarker(), options = AddMarkerOptions( rank = AddMarkerOptions.Rank.Tier(CollisionRankingTier.ALWAYS_VISIBLE), interactive = AddMarkerOptions.Interactive.True, ), ), connection = NavigationOptions.CreateMarkers.CreateMarkerValue.CustomMarker( template = getConnectionMarker(), options = AddMarkerOptions( rank = AddMarkerOptions.Rank.Tier(CollisionRankingTier.ALWAYS_VISIBLE), interactive = AddMarkerOptions.Interactive.True, ), ), ), ) mapView.navigation.draw(directions, navOptions) { } } // Functions to get the SVGs for the markers private fun getDepartureMarker(): String = """ """.trimIndent() private fun getDestinationMarker(): String = """ """.trimIndent() private fun getConnectionMarker(): String = """ """.trimIndent() ``` ## Highlighting a Portion of a Path The path drawn by `Navigation` or `Paths` can have a portion highlighted to draw attention to it. This could be used to show the progress of a user's journey. To highlight a portion of the path, use the Navigation.highlightPathSection or Paths.highlightSection methods. The following code demonstrates how to highlight a portion of a path, starting from the origin of directions and ending at a given coordinate. Note that the floor must be provided when using a coordinate to highlight a path section. ```kotlin val coordinate = mapView.createCoordinate( position.latitude.toDouble(), position.longitude.toDouble(), position.floorOrFloorId ) directions?.coordinates?.firstOrNull()?.let { firstCoordinate -> // Highlight the traveled path. mapView.Navigation.highlightPathSection( from = firstCoordinate, to = coordinate, options = JSONObject().apply { put("animationDuration", 0) put("color", "#9d9d9d") put("widthMultiplier", 1.1) } ) } ``` ## Navigating From a Click Event A navigation start or end point may originate from a user clicking on the map. It is possible to create a start and or end point using the click event and accessing its Events payload. :::tip A complete example demonstrating Navigation from a click event can be found in the Mappedin Android Github repo: PathsDemoActivity.kt ::: The code shown below uses the first click position as a start point and the second click position as an end point to create directions between them. ```kotlin // Set all spaces to be interactive. mapView.mapData.getByType(MapDataType.SPACE) { result -> result.onSuccess { spaces -> spaces.forEach { space -> mapView.updateState(space, GeometryUpdateState(interactive = true)) { } } // Handle click events mapView.on(Events.Click) { clickPayload -> clickPayload ?: return@on val spaces = clickPayload.spaces if (spaces == null || spaces.isEmpty()) { // Click on non-space area when path exists - reset if (path != null) { mapView.paths.removeAll() startSpace = null path = null setSpacesInteractive(mapView, true) instructionText.text = "1. Click on a space to select it as the starting point." } return@on } val clickedSpace = spaces[0] when { startSpace == null -> { // Step 1: Select starting space startSpace = clickedSpace instructionText.text = "2. Click on another space to select it as the end point." } path == null -> { // Step 2: Select ending space and create path val start = startSpace ?: return@on mapView.mapData.getDirections( NavigationTarget.SpaceTarget(start), NavigationTarget.SpaceTarget(clickedSpace), ) { result -> result.onSuccess { directions -> if (directions != null) { mapView.navigation.draw(directions.coordinates) { pathResult -> pathResult.onSuccess { createdPath -> path = createdPath setSpacesInteractive(mapView, false) instructionText.text = "3. Click anywhere to remove the path." } } } } } } else -> { // Step 3: Remove path and reset mapView.paths.removeAll() startSpace = null path = null setSpacesInteractive(mapView, true) instructionText.text = "1. Click on a space to select it as the starting point." } } } } } ``` ## Multi-Floor Wayfinding Using Navigation, no additional work is needed to provide wayfinding between floors. Whenever a user needs to switch a floor, an interactive tooltip with an icon indicating the type of Connection (such as an elevator or stairs) will be drawn. By clicking or tapping the tooltip, the map view switches to the destination floor. ## Multi-Destination Wayfinding Multi-segment directions are directions that include multiple legs. They can be created by passing an array of destinations to MapData.getDirectionsMultiDestination(). ```kotlin val start = // ... get entrance space val destinations = listOf( NavigationTarget.SpaceTarget(store1), NavigationTarget.SpaceTarget(store2), NavigationTarget.SpaceTarget(restaurant) ) mapData.getDirectionsMultiDestination( NavigationTarget.SpaceTarget(start), destinations ) { result -> result.onSuccess { allDirections -> allDirections?.forEachIndexed { index, directions -> Log.d("MapData", "Route ${index + 1}: ${directions.distance}m") } } } ``` ## Wayfinding Using Accessible Routes When requesting directions, it is important to consider the needs of the user. Users with mobility restrictions may require a route that avoids stairs and escalators and instead uses ramps or elevators. The getDirections method accepts GetDirectionsOptions, which allows specifying whether an accessible route should be returned. By default, the shortest available route is chosen. The following code demonstrates how to request directions that make use of accessible routes. ```kotlin mapData.getDirections( NavigationTarget.SpaceTarget(space1), NavigationTarget.SpaceTarget(space2), GetDirectionsOptions(accessible = true) ) { result -> result.onSuccess { directions -> // Use directions } } ``` ## Drawing a Path :::tip A complete example demonstrating drawing a path can be found in the Mappedin Android Github repo: PathsDemoActivity.kt ::: While Navigation provides a complete start and end navigation illustration, it may be desired to draw just the path. This can be done using Paths. :::tip Note that the MapView class implements the Paths interface and exposes it as MapView.paths. Use MapView.paths to utilize Paths methods. ::: Paths can be drawn from one coordinate to another using Paths.add(). If using just two coordinates, the path will be drawn straight between the two points. This may work for some scenarios, but in most cases an app will need to show the user their walking path, going through doors and avoiding walls and other objects. Such a path of coordinates can be created by calling the MapData.getDirections() method, passing in a start and end NavigationTarget. Note that a Space requires an entrance to be used as a target. The width of the path is set using the `width` parameter. This value is in meters. Additional path styles are outlined later in this guide in the Path Styles section. ```kotlin mapView.mapData.getDirections( NavigationTarget.SpaceTarget(start), NavigationTarget.SpaceTarget(end), ) { result -> result.onSuccess { directions -> if (directions != null) { val opts = AddPathOptions( width = Width.Value(1.0) ) mapView.paths.add(directions.coordinates, opts) { pathResult -> pathResult.onSuccess { createdPath -> // Store the path for later use. path = createdPath } } } } } ``` ## Removing Paths There are two methods that can be used to remove paths. Paths.remove() accepts a path to remove and is used to remove a single path. To remove all paths, Paths.removeAll() can be used. ```ts // Remove a single path. mapView.paths.remove(path); ``` ```ts // Remove all paths mapView.paths.removeAll(); ``` ## Path Styles Mappedin SDKs offer many options to customise how paths appear to the user. Path animations, color, width and many more options can be set using AddPathOptions. ## Dynamic Routing When generating directions, Mappedin SDKs provide the most direct route possible between the origin and destination. There can be scenarios when this is not desired, such as when there there is an obstruction like a spill that requires cleaning or where maintenance crews are active. :::tip A complete example demonstrating dynamic routing can be found in the Mappedin Android Github repo: AreaShapesDemoActivity.kt ::: The MapData.getDirections() method accepts a zones parameter that denotes areas that could be avoided. Zones are defined using DirectionZone and contain a `cost`, `floor` and `geometry`. `cost` represents the additional cost for navigation through the zone and can range from from 0 to Infinity. A cost of 0 will make the zone free to navigate through. A zone cost of Infinity will block passage through the zone. Multiple zones occupying the same location they are added together, along with the cost from the map. The SDK may route directions through a zone if all other routes have a higher cost. `floor` represents the floor for the zone. If not specified the zone blocks all floors. `geometry` is held within a Feature that contains a Geometry object. ## Turn-by-Turn Directions Turn-by-Turn directions are a set of text instructions describing the route the user needs to take. An example is "Turn right and go 10 meters". These could be shown to the user in a list to give them an overview with all steps they need to take, or the current instruction could be displayed along with a map showing the next leg of their journey. :::tip A complete example demonstrating turn-by-turn directions can be found in the Mappedin Android Github repo: TurnByTurnDemoActivity.kt ::: The code sample assembles these actions together and: - Gets directions between the start and end NavigationTarget. - Draws a path using the directions' coordinates. - Creates a Marker with textual turn-by-turn instructions for each leg in the journey. Refer to the Marker Guide for more information on using Markers. ```kotlin private var currentDirections: Directions? = null private fun onMapReady() { // Add labels to all named spaces mapView.mapData.getByType(MapDataType.SPACE) { spacesResult -> spacesResult.onSuccess { spaces -> spaces.forEach { space -> if (space.name.isNotEmpty()) { mapView.labels.add( target = space, text = space.name, options = AddLabelOptions(interactive = true), ) { } } } // Find destination space val destination = spaces.find { it.name == "Family Med Lab EN-09" } // Get origin object mapView.mapData.getByType(MapDataType.MAP_OBJECT) { objResult -> objResult.onSuccess { objects -> val origin = objects.find { it.name == "Lobby" } if (origin != null && destination != null) { getAndDisplayDirections(origin, destination) } } } } } } private fun getAndDisplayDirections( origin: MapObject, destination: Space, ) { mapView.mapData.getDirections( NavigationTarget.MapObjectTarget(origin), NavigationTarget.SpaceTarget(destination), ) { result -> result.onSuccess { directions -> if (directions != null) { currentDirections = directions // Focus on the first 3 steps in the journey val focusCoordinates = directions.coordinates.take(3).map { FocusTarget.CoordinateTarget(it) } val focusOptions = FocusOnOptions( screenOffsets = InsetPadding( top = 50.0, left = 50.0, bottom = 50.0, right = 50.0, ), ) mapView.camera.focusOn(focusCoordinates, focusOptions) // Add markers for each direction instruction addInstructionMarkers(directions) // Draw navigation by default drawNavigation() } } } } private fun drawNavigation() { val directions = currentDirections ?: return mapView.navigation.draw(directions) { } } private fun addInstructionMarkers(directions: Directions) { val instructions = directions.instructions for (i in instructions.indices) { val instruction = instructions[i] val nextInstruction = if (i < instructions.size - 1) instructions[i + 1] else null val isLastInstruction = i == instructions.size - 1 val markerText = if (isLastInstruction) { "You Arrived!" } else { val actionType = instruction.action.type val bearing = instruction.action.bearing ?: "" val distance = nextInstruction?.distance?.roundToInt() ?: 0 "$actionType $bearing and go $distance meters" } val markerTemplate = """

$markerText

""".trimIndent() mapView.markers.add( instruction.coordinate, markerTemplate, AddMarkerOptions( rank = AddMarkerOptions.Rank.Tier(CollisionRankingTier.ALWAYS_VISIBLE), ), ) { } } } ```