如何在 Mapbox 中的特定坐标上放置自定义注释的底部 iOS

How to Place Bottom Of a Custom Annotation On a Specific Coordinate in Mapbox iOS

我在我的应用程序中使用 iOS Mapbox SDK。我将注释图像更改为自定义图像(它看起来像地图标记)。当我向地图视图上的特定坐标添加注释时,它会被添加,但我的自定义注释图像(标记)的中心将设置在坐标上。我需要更改标记位置以将标记的底部设置在坐标上。我找到了一种方法,但我不知道是否有更好的方法? 我把坐标转成点,然后改变点的y位置,再把点转成新的坐标。

func mapView(_ mapView: MGLMapView, imageFor annotation: MGLAnnotation) -> MGLAnnotationImage? {
    let reuseIdentifier = "annotationImage"
    var annotationImage = mapView.dequeueReusableAnnotationImage(withIdentifier: reuseIdentifier)

    if annotationImage == nil {
        annotationImage = MGLAnnotationImage(image: UIImage(named: "Orange")!, reuseIdentifier: reuseIdentifier)
    }
    return annotationImage
}

func addDestinationMarker(coordinate: CLLocationCoordinate2D) {
    guard let mapView = mapView else { return }
    if let annotations = mapView.annotations {
        mapView.removeAnnotations(annotations)
    }
    var point = mapView.convert(coordinate, toPointTo: mapView)
    point.y -= markerImageView.frame.height / 2
    let newCoordinate = mapView.convert(point, toCoordinateFrom: mapView)
    let annotation = MGLPointAnnotation()
    annotation.coordinate = newCoordinate
    mapView.addAnnotation(annotation)
}

我 运行 遇到了同样的问题,并开始认为圆形地图图钉正在成为事实上的标准,因此它们可以直接插入到地图上,图像中心表示坐标。但是,如果您查看 Mapbox 网站上的 this 示例,他们会使用非圆形图像并很好地解决偏移问题。

// The anchor point of an annotation is currently always the center. To
// shift the anchor point to the bottom of the annotation, the image
// asset includes transparent bottom padding equal to the original image
// height.
//
// To make this padding non-interactive, we create another image object
// with a custom alignment rect that excludes the padding.

image = image.withAlignmentRectInsets(UIEdgeInsets(top: 0, left: 0, bottom: image.size.height/2, right: 0))

这确实意味着您需要生成两倍高的图钉图像,下半部分透明,但这真的没什么大不了的。

您可以利用 MGLAnnotationView 提供的 centerOffset 属性 来解决这个问题。虽然我不确定它是否存在于您正在使用的 MGLAnnotationImage 中。

要将锚点设置到注释的底部,请使用:

centerOffset.dy = -height / 2

如果事先设置frame,高度就是frame.height

其他答案表达正确,但都缺少正确的语法:

annotationView?.centerOffset.y = -(annotationView?.frame.height ?? 0) / 2

这将达到预期的效果。