【问题标题】:How to Place Bottom Of a Custom Annotation On a Specific Coordinate in Mapbox iOS如何在 Mapbox iOS 中的特定坐标上放置自定义注释的底部
【发布时间】:2018-11-19 07:36:43
【问题描述】:

我在我的应用程序中使用 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)
}

【问题讨论】:

    标签: swift mapkit mapbox


    【解决方案1】:

    我遇到了同样的问题,并开始认为圆形地图大头针正在成为事实上的标准,因此它们可以直接放在地图上,图像中心表示坐标。但是,如果您查看 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))
    

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

    【讨论】:

    • 能否请您提供相同问题的答案,但反应原生
    • 我在 react native 中使用了你给定的样式,它对我有用
    【解决方案2】:

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

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

    centerOffset.dy = -height / 2
    

    如果你事先设置了frame,那么高度就是frame.height

    【讨论】:

      【解决方案3】:

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

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

      这样就能达到预期的效果了。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-12-29
        • 1970-01-01
        • 1970-01-01
        • 2014-06-19
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多