首页 > 解决方案 > 处理不同的 MGLPointAnnotation 标注

问题描述

我有两个点 1 和 2,每个点都有自己的标注,但是当我尝试使用 taponcallout 函数时

func mapView(_ mapView: MGLMapView, tapOnCalloutFor annotation: MGLAnnotation ) {

它反映在两个点上,最终将我引向相同的方法

我怎样才能让这个功能区分这两点?

这是我的代码示例


let point = MGLPointAnnotation()
let point1 = MGLPointAnnotation()



 func mapView(_ mapView: MGLMapView, didFinishLoading style: MGLStyle) {

        // Create point to represent where the symbol should be placed

        point.coordinate = CLLocationCoordinate2D(latitude: 26.319735961914062, longitude: 50.14814726335609)
        point1.coordinate = CLLocationCoordinate2D(latitude: 26.319735961914062, longitude: 50.14414726335609)

        point.title = "big-bossman"
        point.subtitle = "very scary"

        point1.title = "smol-bossman"
        point1.subtitle = "smol scary"


        // Create a data source to hold the point data
        let shapeSource = MGLShapeSource(identifier: "marker-source", shape: point, options: nil)
        let shapeSource1 = MGLShapeSource(identifier: "marker-source1", shape: point1, options: nil)

        // Create a style layer for the symbol
        let shapeLayer = MGLSymbolStyleLayer(identifier: "marker-style", source: shapeSource)
        let shapeLayer1 = MGLSymbolStyleLayer(identifier: "marker-style1", source: shapeSource1)

        // Add the image to the style's sprite
        if let image = UIImage(named: "enemyImage") {
            style.setImage(image, forName: "home-symbol")
        }

        // Tell the layer to use the image in the sprite
        shapeLayer.iconImageName = NSExpression(forConstantValue: "home-symbol")
        shapeLayer1.iconImageName = NSExpression(forConstantValue: "home-symbol")

        // Add the source and style layer to the map
        style.addSource(shapeSource)
        style.addLayer(shapeLayer)

        style.addSource(shapeSource1)
        style.addLayer(shapeLayer1)

        mapView.selectAnnotation(point, animated: true, completionHandler: nil)
        mapView.selectAnnotation(point1, animated: true, completionHandler: nil)


    }

    func mapView(_ mapView: MGLMapView, annotationCanShowCallout annotation: MGLAnnotation) -> Bool {
        true
    }

    func mapView(_ mapView: MGLMapView, tapOnCalloutFor annotation: MGLAnnotation ) {


            transition()

    }

例如,我想要的是,如果我点击点的标注,我会进入转换(),但如果我点击点1 ,我会进入转换1 ()

标签: iosswiftxcodemapboxmapbox-ios

解决方案


不确定您是否尝试过上述解决方案,但这可以实现您想要的。如果您在方法中针对您的点引用注释tapOnCalloutFor,然后设置适当的操作,它应该可以正常工作。在下面的代码中,我使用了注释和点标题:

       if annotation.title == point.title {
                //do something
       } else if annotation.title == point1.title {
                //do something else 
       }

推荐阅读