如何在 Swift & MapKit 中为折线和多边形添加注释?按点很简单。
1 回答
S.,
我不确定您在这里问什么,但我假设您想在折线上的某处显示注释。
首先介绍如何获取折线:因此,假设您有一个 CLLocation 对象数组,它们将在地图上绘制折线。我们将此位置对象数组称为:myLocations,它的类型为 [CLLocation]。现在在您的应用程序的某个地方调用创建折线的方法,我们将此方法称为 createOverlayObject(locations: [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 annotation:) -> 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 循环找到要放置注释的位置,如下所示:
for location in myLocations {
if (location.latitude == myReferenceCoordinate.latitude) && (location.longitude == myReferenceCoordinate.longitude) {
self.createAnnotation(location: CLLOcationCoordinate2D)
}
}
希望这能回答你的问题。