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:
How it stands now:
- (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;
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With