# How to Create a Device Map Source: https://www.nianticspatial.com/docs/nsdk/how-to/vps/adding_device_mapping/?platform=kotlin > **Caution:** > > **Attention!** > > This feature is experimental and may not work as expected. For more information about it, see the [Device Mapping Feature page](https://www.nianticspatial.com/docs/nsdk/features/device_mapping/). The `DeviceMappingSession` enables you to locally create maps for VPS localization. When those maps are loaded with `MappingStorageSession`, localization and anchors can be managed with a `Vps2Session`, via the same APIs used to interact with a map created on Niantic Spatial's servers. ### Prerequisites You will need a Kotlin project with NSDK installed and a basic AR scene. For more information, see [Set up the NSDK in Kotlin](https://www.nianticspatial.com/docs/nsdk/setup/#set-up-the-nsdk-in-kotlin). ### Setting Up the Sessions Create the `DeviceMappingSession` and `MappingStorageSession` from an existing `NSDKSession` instance: ```kotlin val mappingSession = nsdkSession.mapping.acquire() val mapStoreSession = nsdkSession.mapStore.acquire() ``` ### Starting and Stopping Device Mapping The device mapping lifecycle has two levels: 1. **`start()` / `close()`** -- Initializes and tears down native resources (including model downloads). No map data is produced at this level. 2. **`startCreating()` / `stopCreating()`** -- Controls the actual map construction within a started session. ```kotlin // Initialize native resources mappingSession.start() // Begin building the map mappingSession.startCreating() // ... user scans the environment ... // Stop map construction mappingSession.stopCreating() // Release native resources when completely done mappingSession.stop() mappingSession.close() ``` After stopping, you can reconfigure and restart the session. ### Checking Mapping Progress The time it takes to construct a valid map varies depending on the environment and the device's processing power. Use `mapStoreSession.mapUpdates` to collect incremental map data as it is produced: ```kotlin coroutineScope.launch { mapStoreSession.mapUpdates.collect { mapUpdate -> if (mapUpdate == null) return@collect // `mapUpdate` is a ByteArray containing additional map data since the last update } } ``` Once a map is valid, you can create a root anchor at its origin. Check this after receiving map updates: ```kotlin val rootAnchorPayload = mapStoreSession.createRootAnchor() if (rootAnchorPayload != null) { // The map is valid -- save or continue to grow it } ``` Alternatively, you can retrieve the complete map at any time with `mapStoreSession.getData()`. ### Saving the Map to Disk To persist the map, retrieve the complete serialized map data from storage and write it to a file. The `.map` extension is recommended by convention: ```kotlin val mapData = mapStoreSession.getData() if (mapData == null) { Log.e("DeviceMapping", "Map has no data") return } val file = File(context.filesDir, "my_device_map.map") FileOutputStream(file).use { output -> output.write(mapData) } Log.i("DeviceMapping", "Map saved to ${file.absolutePath}") ``` ### Optional: Customizing the Configuration You can customize the mapping session before calling `start()` using `DeviceMappingConfig`: ```kotlin val config = DeviceMappingConfig( slickMapperFrameRate = 15 // Target FPS for map processing (0 = automatic) ) mappingSession.configure(config) mappingSession.start() ``` Configuration must be applied while the session is stopped. ### Optional: Visualizing the Point Cloud When mapping larger areas, it can be useful to visualize the growing map's coverage. Once a root anchor has been obtained, `mapStoreSession.extractMetadata()` can be used to obtain the map's feature points. Pass the incremental buffer from `mapStoreSession.mapUpdates` or the complete map from `mapStoreSession.getData()`: ```kotlin val metadata: MapMetadata? = mapStoreSession.extractMetadata(rootAnchorPayload, mapData) if (metadata != null) { val points = metadata.points // FloatArray of [x, y, z, x, y, z, ...] val count = metadata.pointsCount // number of points for (i in 0 until count.toInt()) { val x = points[i * 3] val y = points[i * 3 + 1] val z = points[i * 3 + 2] // Position a point cloud element at (x, y, z) } } ``` Feature points are extracted relative to the pose of the anchor passed in for the first argument. To render the points on screen, you must first track the pose of that anchor using a VPS2 session. See [How to Place Virtual Content Using a Device Map](https://www.nianticspatial.com/docs/nsdk/how-to/vps/using_device_maps/) for how to do that. > **Note:** > > Point cloud visualization requires a VPS2 session to track the anchor pose. Mapping itself does not require VPS2. ### Sharing the Map Serialized map data can be saved for use on the local device, or shared with other devices. To load a previously saved map into a fresh session: ```kotlin val mapData = File(context.filesDir, "my_device_map.map").readBytes() mapStoreSession.add(mapData) ``` Once a device map has been added to storage, the `Vps2Session` APIs can be used to create and track anchors to the map. > **Caution:** > > `add()` **appends** to existing storage. If you want to replace the current map, call `mapStoreSession.clear()` before `add()`. Do **not** call `clear()` while VPS is running -- stop the VPS2 session first. ## Device Mapping Tips - Because device mapping relies on a single scan, localization and tracking accuracy depend heavily on how well you scan the area. If you remember one tip, let it be this: **if you are having localization issues, don't be afraid to re-scan!** - Lighting matters a lot when scanning an area. If the lighting during localization doesn't match the scan, you will need to re-scan. (This includes both outdoor and indoor lighting!) - For best results, follow these guidelines when scanning: - Focus on distinctive objects in the area that are unlikely to move between scanning and localization, such as furniture, household fixtures, or statues. - Avoid looking primarily at flat surfaces without color variation, such as the ground, grass, walls, and floors. - Move around while scanning! The more viewpoints you see an object from, the better the map of it will be. ## Next Steps Once you have created and saved a device map, move on to [How to Place Real-World Content Using a Device Map](https://www.nianticspatial.com/docs/nsdk/how-to/vps/using_device_maps/).