我有一个数组,其中包含显示在 mapView 上的路线坐标。我无法在路线上画一条我的坐标线。
这是我的课:
我导入需要的模块
import UIKit
import MapKit
import CoreLocation
这是我的课
class MapViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate {
var locationManager = CLLocationManager()
var location: [(Double, Double)]?
var placeAnnotation: [String]?
var sourceLocation: CLLocationCoordinate2D!
var indexPoint = 0
@IBOutlet weak var mapView: MKMapView!
let regionRadius: CLLocationDistance = 1000
func centerMapOnLocation(location: CLLocation) {
let coordinateRegion = MKCoordinateRegionMakeWithDistance(location.coordinate, regionRadius, regionRadius)
mapView.setRegion(coordinateRegion, animated: true)
}
override func viewDidLoad() {
super.viewDidLoad()
mapView.delegate = self
drawPlaceMark()
}
func drawPlaceMark() {
for (x,y) in location! {
sourceLocation = CLLocationCoordinate2D(latitude: x, longitude: y)
let destinationPlacemark = MKPlacemark(coordinate: sourceLocation, addressDictionary: nil)
let destinationMapItem = MKMapItem(placemark: destinationPlacemark)
let sourceAnnotation = MKPointAnnotation()
sourceAnnotation.title = placeAnnotation?[indexPoint]
indexPoint = indexPoint + 1
if let location = destinationPlacemark.location {
sourceAnnotation.coordinate = location.coordinate
}
self.mapView.showAnnotations([sourceAnnotation,sourceAnnotation], animated: true )
// Calculate the direction and draw line
let directionRequest = MKDirectionsRequest()
directionRequest.source = destinationMapItem
directionRequest.destination = destinationMapItem
directionRequest.transportType = .walking
let directions = MKDirections(request: directionRequest)
directions.calculate {
(response, error) -> Void in
guard let response = response else {
if let error = error {
print("Error: \(error)")
}
return
}
let route = response.routes[0]
self.mapView.add((route.polyline), level: MKOverlayLevel.aboveRoads)
let rect = route.polyline.boundingMapRect
self.mapView.setRegion(MKCoordinateRegionForMapRect(rect), animated: true)
}
}
}
}
如果有人可以提供帮助,请告诉我如何以正确的方式正确地做到这一点。
最佳答案
实现rendererFor
方法。
func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
let renderer = MKPolylineRenderer(polyline: overlay as! MKPolyline)
renderer.strokeColor = UIColor.red
renderer.lineWidth = 3
return renderer
}
关于swift - 如何在 mapKit 中绘制路线?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50233078/