Как добавить описание в MKPolyline & MKPolygon?

Как добавить аннотации к полилинии и многоугольнику в Swift & MapKit? По пунктам все просто.

1 ответ

С.,

Я не уверен, что вы спрашиваете здесь, но я предполагаю, что вы хотите отобразить аннотацию где-нибудь на полилинии.

Сначала введение, как получить полилинию. Итак, давайте предположим, что у вас есть массив объектов CLLocation, которые будут рисовать полилинию на карте. Мы называем этот массив объектов местоположения: myLocations и он имеет тип [CLLocation]. Теперь где-то в вашем приложении вы вызываете метод, который создает полилинию, мы вызываем этот метод createOverlayObject(location: [CLLocation]) -> MKPolyline.

Ваш звонок может выглядеть так:

let overlayPolyline = createOverlayObject(myLocations)

Метод, который вы вызвали тогда, может выглядеть так:

func createOverlayObject(locations: [CLLocation]) -> MKPolyline {
    //This method creates the polyline overlay that you want to draw.
    var mapCoordinates = [CLLocationCoordinate2D]()

    for overlayLocation in locations {

        mapCoordinates.append(overlayLocation.coordinate)
    }

    let polyline = MKPolyline(coordinates: &mapCoordinates[0], count: mapCoordinates.count)

    return polyline
}

Это была первая часть, не забудьте реализовать mapView(_: rendererForOverlay overlay:) для визуализации строки. эта часть может выглядеть примерно так:

func mapView(mapView: MKMapView, rendererForOverlay overlay: MKOverlay) -> MKOverlayRenderer {
    //This function creatss the renderer for the polyline overlay. This makes the polyline actually display on screen.
    let renderer = MKPolylineRenderer(overlay: overlay)
    renderer.strokeColor = mapLineColor //The color you want your polyline to be.
    renderer.lineWidth = self.lineWidth

    return renderer
}

Теперь вторая часть получит аннотацию где-нибудь на карте. Это на самом деле просто, если вы знаете, какие координаты находятся там, где вы хотите разместить аннотацию. Создание и отображение аннотации снова очень просто, при условии, что вы определили представление карты с именем myNiceMapView:

func createAnnotation(myCoordinate: CLLocationCoordinate2D) {
    let myAnnotation = MKPointAnnotation()
    myAnnotation.title = "My nice title"
    startAnnotation.coordinate = myCoordinate

    self.myNiceMapView.addAnnotations([myAnnotation])
}

Не забудьте реализовать mapView(_: MKMapView, аннотация viewForAnnotation:) -> MKAnnotationView? метод, который может выглядеть так:

func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? {
    //This is the mapview delegate method that adjusts the annotation views.

    if annotation.isKindOfClass(MKUserLocation) {

        //We don't do anything with the user location, so ignore an annotation that has to do with the user location.
        return nil
    }

    let identifier = "customPin"
    let trackAnnotation = MKAnnotationView.init(annotation: annotation, reuseIdentifier: identifier)

    trackAnnotation.canShowCallout = true

    if annotation.title! == "Some specific title" { //Display a different image
        trackAnnotation.image = UIImage(named: "StartAnnotation")
        let offsetHeight = (trackAnnotation.image?.size.height)! / 2.0
        trackAnnotation.centerOffset = CGPointMake(0, -offsetHeight)
    } else { //Display a standard image.
        trackAnnotation.image = UIImage(named: "StopAnnotation")
        let offsetHeight = (trackAnnotation.image?.size.height)! / 2.0
        trackAnnotation.centerOffset = CGPointMake(0, -offsetHeight)
    }

    return trackAnnotation
}

Теперь задача состоит в том, чтобы найти правильную координату, где разместить вашу аннотацию. Я не могу найти ничего лучше, чем у вас есть CLLocationCoordinate2D, который ссылается на место, где вы хотите разместить аннотацию. Затем с помощью цикла for-in найдите место, куда вы хотите поместить аннотацию, что-то вроде этого:

для местоположения в myLocations {

if (location.latitude == myReferenceCoordinate.latitude) && (location.longitude == myReferenceCoordinate.longitude) {
    self.createAnnotation(location: CLLOcationCoordinate2D)
}

}

Надеюсь, что это ответ на ваш вопрос.

Другие вопросы по тегам