[SOLVED] Swift Mapbox add layer with coordinates coming from server every second

Issue

I have coordinates coming from the server every second and I need to smoothly move car images on map according to this updates. As I understood it can’t be done using annotations, so I am trying to use layers instead. Here is how I try to create them:

var layer = LocationIndicatorLayer(id: vanPosition.userId)
guard let lat = vanPosition.latitude, let lon = vanPosition.longitude else { return }
layer.location = .constant([lat, lon])
let image = UIImage(named: "van-pin")!

layer.topImage = .constant(.name("van-pin"))
layer.source = "some-source"
layer.sourceLayer = nil
try? mapView.mapboxMap.style.addImage(image, id: vanPosition.userId, stretchX: [], stretchY: [])
try? mapView.mapboxMap.style.addLayer(layer, layerPosition: .default)

But nothing is displayed on the map. I also tried creating a source like this:

var source = GeoJSONSource()
source.data = .feature(Feature(geometry: .point(Point(vanPosition.coordinate!))))
try! mapView.mapboxMap.style.addSource(source, id: vanPosition.userId)

var layer = LocationIndicatorLayer(id: vanPosition.userId)
guard let lat = vanPosition.latitude, let lon = vanPosition.longitude else { return }
layer.location = .constant([lat, lon])
let image = UIImage(named: "van-pin")!

layer.topImage = .constant(.name("van-pin"))
layer.source = vanPosition.userId
layer.sourceLayer = nil
try? mapView.mapboxMap.style.addImage(image, id: vanPosition.userId, stretchX: [], stretchY: [])
try? mapView.mapboxMap.style.addLayer(layer, layerPosition: .default)

But it doesn’t work also. Layer is not actually added to mapView, if I check with mapView.mapboxMap.style.layerExists(withId: vanPosition.userId) there is nothing. Thanks for any help you can provide, please do ask me for more info if needed.

Solution

Layer isn’t created because there is no "van-pin" image in my map – you have to add them manually if you want to use custom images. Like this:

try? mapView.mapboxMap.style.addImage(UIImage(named: "van-pin")!, id: "van-pin", stretchX: [], stretchY: [])

And the smooth animation thing doesn’t seem possible through mapbox. Just launch a timer and manually update layers’ positions.

Answered By – f3dm76

Answer Checked By – Willingham (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published.