Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mapbox Annotation Image centering

I started using MapBox in a project. When I am adding annotation with custom images, it is not centered correct. It is appears little bit lower of the original pins. Is it possible to change center point of the annotation image?

How it should be:

enter image description here

How it stands now:

enter image description here

- (MGLAnnotationImage *)mapView:(MGLMapView *)mapView imageForAnnotation:(id <MGLAnnotation>)annotation {
    MGLAnnotationImage *annotationImage = [mapView dequeueReusableAnnotationImageWithIdentifier:@"driverPinId"];

    if (!annotationImage) {
        UIImage *image = [UIImage imageNamed:@"DriverPin"];
        annotationImageWithImage:image reuseIdentifier:@"driverPinId"];
    }

    return annotationImage;
}
like image 713
korgx9 Avatar asked May 23 '16 08:05

korgx9


1 Answers

You should use MGLAnnotationView instead of MGLAnnotationImage because MGLAnnotationView a descendant of UIView so you can add to it anything you want as with ordinary UIView.

func mapView(_ mapView: MGLMapView, viewFor annotation: MGLAnnotation) -> MGLAnnotationView? {
    guard annotation is MGLPointAnnotation else {
        return nil
    }
    guard let castAnnotation = annotation as? MapPointMarker else {
        return nil
    }
    if (!castAnnotation.willUseImage) {
        return nil;
    }

    let identifier = castAnnotation.imageName!
    var image: UIImage = UIImage(named: castAnnotation.imageName!)!

    var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: identifier)

    if annotationView == nil {
        annotationView = MGLAnnotationView(annotation: annotation, reuseIdentifier: identifier)
        let imageView = UIImageView(image: image)
        annotationView!.frame = CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height)
        annotationView?.addSubview(imageView)
        annotationView?.centerOffset = CGVector(dx: 0, dy: -image.size.height / 2.0)
    }

    return annotationView
}

In code snippet above I've adding UIImageView to annotationView and with annotationView?.centerOffset = CGVector(dx: 0, dy: -image.size.height / 2.0) move image up.

Hope this help.

like image 65
Andrew Son Avatar answered Oct 19 '22 08:10

Andrew Son