# How to Create a Device Map Source: https://www.nianticspatial.com/docs/nsdk/how-to/vps/adding_device_mapping/?platform=swift > **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 `NSDKDeviceMappingSession` enables you to locally create maps for VPS localization. When those maps are loaded with `NSDKMapStorage`, localization and anchors can be managed with a `NSDKVps2Session`, via the same APIs used to interact with a map created on Niantic Spatial's servers. ### Prerequisites You will need a Swift project with NSDK installed and a basic AR scene. For more information, see [Set up the NSDK in Swift](https://www.nianticspatial.com/docs/nsdk/setup/#set-up-the-nsdk-in-swift). ### Setting Up the Sessions Create the `NSDKDeviceMappingSession` and `NSDKMapStorage` from an existing `NSDKSession` instance: ```swift let mappingSession = nsdkSession.acquireDeviceMappingSession() let mapStorage = nsdkSession.acquireMapStorage() ``` ### Starting and Stopping Device Mapping The device mapping lifecycle has two levels: 1. **`start()` / `stop()`** -- Initializes and tears down native resources (including model downloads). No map data is produced at this level. 2. **`startMapping()` / `stopMapping()`** -- Controls the actual map construction within a started session. ```swift // Initialize native resources mappingSession.start() // Begin building the map mappingSession.startMapping() // ... user scans the environment ... // Stop map construction mappingSession.stopMapping() // Release native resources mappingSession.stop() ``` 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 the `mappingSession.$latestMapUpdate` publisher to receive incremental map data as it is produced: ```swift mappingSession.$latestMapUpdate .compactMap { $0 } .receive(on: DispatchQueue.main) .sink { [weak self] buffer in // `buffer` contains additional map data since the last update } .store(in: &cancellables) ``` Once a map is valid, you can create a root anchor at its origin. Check this after receiving map updates: ```swift if let anchorPayload = mapStorage.createRootAnchor() { // The map is valid -- save or continue to grow it } ``` Alternatively, you can poll for updates with `mapStorage.mapUpdate()` instead of using the publisher. ### 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: ```swift guard let buffer = mapStorage.mapData() else { print("Failed to get map from storage") return } let mapData = Data(bytes: buffer.data, count: buffer.dataSize) do { let fileURL = documentsDirectory.appendingPathComponent("my_device_map.map") try mapData.write(to: fileURL) print("Map saved to \(fileURL)") } catch { print("Failed to save map: \(error)") } ``` > **Note:** > > `mapStorage.mapData()` can block the calling thread. Call it off the main thread to avoid interrupting the AR session. ### Optional: Customizing the Configuration You can customize the mapping session before calling `start()` using `NsdkDeviceMappingSession.Configuration`: ```swift var config = NsdkDeviceMappingSession.Configuration() config.mapperFrameRate = 15 // Target FPS for map processing (0 = automatic) try mappingSession.configure(with: 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, `mapStorage.extractMapMetadata(anchorPayload:map:)` can be used to obtain the map's feature points. Pass the incremental buffer from `mappingSession.$latestMapUpdate` or the complete map from `mapStorage.mapData()`: ```swift do { let mapMetadata = try mapStorage.extractMapMetadata( anchorPayload: rootAnchorPayload, map: buffer) guard let metadata = mapMetadata else { print("Failed to extract map metadata.") return } // Visualize points described in metadata.points } catch { print("Failed to extract map metadata: \(error)") } ``` Feature points are extracted relative to the pose of the anchor passed in for the `anchorPayload` argument. To render the points on screen, you must first track the pose of that anchor using a VPS2 session. See the guide [Localizing and Tracking anchors with VPS](https://www.nianticspatial.com/docs/nsdk/how-to/vps/tracking_anchors_swift/#tracking-existing-anchors) for how to do that. Then get the location of feature points relative to that anchor: ```swift let points = metadata.points for i in stride(from: 0, to: points.count - 2, by: 3) { let center = SIMD3(points[i], points[i + 1], points[i + 2]) // Position a point cloud entity at `center` } ``` > **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: ```swift do { let mapData = try Data(contentsOf: mapFileURL) let mapBuffer = NSDKBuffer(data: mapData) try mapStorage.addMap(map: mapBuffer) } catch { print("Failed to add map to storage: \(error)") } ``` Once a device map has been added to storage, the `NSDKVps2Session` APIs can be used to create and track anchors to the map. > **Caution:** > > `addMap()` **appends** to existing storage. If you want to replace the current map, call `mapStorage.clear()` before `addMap()`. 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/).