Как установить пользовательскую аннотацию на карту в зависимости от масштаба - PullRequest
0 голосов
/ 05 мая 2019

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
}

1 Ответ

0 голосов
/ 17 мая 2019

Лучший способ сделать это - определить ширину экрана, отображаемую картой.Вы можете сделать это, используя пролет 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())
}

ЭтоСтоит отметить, что приведенное выше уравнение предполагает, что земля является идеальной сферой.Это должно быть более чем достаточно точно для вашего приложения.Проблема с нахождением истинного уровня «масштабирования» для карты состоит в том, что расстояние карты на ширине экрана (расстояние градуса долготы) изменяется в зависимости от вашей широты .

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...