首页 > 解决方案 > 如何根据缩放在地图上安装自定义注释

问题描述

1)我需要设置一个自定义注释,根据地图上的缩放比例,它们将被放置在地图上的整个轨道上。(箭头显示方向)。

我的代码

   class customPin: NSObject, MKAnnotation {
    var coordinate: CLLocationCoordinate2D
    var title: String?
    var subtitle: String?

    init(pinTitle:String, pinSubTitle:String, location:CLLocationCoordinate2D) {
        self.title = pinTitle
        self.subtitle = pinSubTitle
        self.coordinate = location
    }
}


    func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
    if annotation is MKUserLocation {
        return nil
    }

    let annotationView = MKAnnotationView(annotation: annotation, reuseIdentifier: "customannotation")
    annotationView.image = UIImage(named:"mov_on_2")
    annotationView.canShowCallout = true
    return annotationView
}

标签: swiftmapkit

解决方案


我发现做到这一点的最好方法是确定地图显示的屏幕宽度的距离。您可以在地图中使用 mapView 的跨度来做到这一点regionDidChangeAnimated

func mapView(_ mapView: MKMapView, regionDidChangeAnimated animated: Bool) {

    // Get the span and the center coordinate of the mapview
    let span = mapView.region.span
    let center = mapView.centerCoordinate
    // Create two points on the left and right side of the region
    let rightSide = CLLocationCoordinate2D(latitude: center.latitude + (span.latitudeDelta / 2), longitude: center.longitude)
    let leftSide = CLLocationCoordinate2D(latitude: center.latitude - (span.latitudeDelta / 2), longitude: center.longitude)

    // Calculate the distance between these two points (don't forget to convert to meters!)
    let distance = calculateDistanceBetween(firstLoc: leftSide, secondGeoPoint: rightSide) * 1609.34

    // Switch case the distance to handle zooming logic
    switch distance {
    case _ where distance < 1000:
        // Handle logic for if the on screen width distance is < 1000 meters
    case _ where distance < 5000:
        // Handle logic for if the on screen width distance is < 5000 meters
    default:
        // Handle logic for if the on screen width distance is > 5000 meters
    }
}

可以使用以下方法找到任意两个 GPS 坐标之间的距离:

// Calculates the distance between two locations, returned in miles
func calculateDistanceBetween(firstLoc: CLLocationCoordinate2D, secondLoc: CLLocationCoordinate2D) -> Double {
    // Convert lat's and long's into radians
    let firstLatR = firstLoc.latitude * Double.pi / 180
    let firstLongR = firstLoc.longitude * Double.pi / 180
    let secondLatR = secondLoc.latitude * Double.pi / 180
    let secondLongR = secondLoc.longitude * Double.pi / 180
    // Calculate and return the distance
    return 2 * 3963.1 * asin((pow(sin((secondLatR - firstLatR) / 2), 2) + cos(firstLatR) * cos(secondLatR) * pow(sin((secondLongR - firstLongR) / 2), 2)).squareRoot())
}

值得注意的是,上述方程假设地球是一个完美的球体。这对于您的应用程序来说应该足够准确。为地图找到真正的“缩放”级别的问题在于,屏幕宽度(度经度的距离)的地图距离会根据您的纬度而变化


推荐阅读