如何在Swift&中为折线和多边形添加注释。 MapKit? By Point很简单。
答案 0 :(得分: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)
}
}
希望这能回答你的问题。