简体   繁体   中英

iOS Moving annotations on MapBox map

Is it possible to move an annotation without removing and adding a new annotation?

I'd like to stick with MapBox because the future support of offline maps.

Thank you in advance!!

As of Mapbox iOS SDK v3.2.0, it is not possible to update the coordinates of an annotation that has been added to a map. Here is the relevant ticket on Github.

You can do a custom development for moving marker. I have done it and it's work as expected.

If you want to move a marker along your polyline, I would start by holding a reference to your MGLPointAnnotation and update its coordinate property on a timer or as the user moves along with it.

You can do this by keeping a reference to the annotation instance and then updating the coordinates of that instance.

If I assume you're adding your map (MGLMapView) to a View Controller, then a basic approach could be to add a property to that view controller so that you can keep track of the reference. For this example, I'll use an MGLPointAnnotation:

class ViewControllerWithAMap: UIViewController {
    var movingPointAnnotation: MGLPointAnnotation?
    ...
}

Make this reference an optional so that you know when to initiate it and then just update the coordinates. The last part may seem counterintuitive, but all you really need to do now is add the annotation to the map again. For example:

    if self.movingPointAnnotation == nil {
        self.movingPointAnnotation = MGLPointAnnotation()
    }
    guard self.movingPointAnnotation != nil else {
        print("What?! Could not initiate moving annotation.")
        return // something weird, give up
    }
    self.movingPointAnnotation!.coordinate = myNewCLLocationCoordinate2D
    self.mapView.addAnnotation(self.movingPointAnnotation!)

Regarding that last part where you add the annotation over and over again, I tried only adding the annotation once, and then just updating its coordinates afterward, but the annotation did not move.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM