我目前有一个应用程序,当按下按钮时MKPolyline
应显示在我的mapView
上。
当我在MKPolyline
中调用viewDidLoad()
函数时,折线会显示在mapView
上。如果我尝试使用按钮操作功能而不是viewDidLoad()
来调用该功能,则MKPolyline
不会显示。
根据按下的按钮决定应显示哪条折线。
如何显示MKPolyline
我的MapViewController
代码:
import UIKit
import MapKit
class MapViewController: UIViewController, MKMapViewDelegate,
CLLocationManagerDelegate {
@IBOutlet var mapView: MKMapView?
let locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
mapView?.delegate = self
mapView?.showsUserLocation = true
locationManager.requestAlwaysAuthorization()
locationManager.requestWhenInUseAuthorization()
if CLLocationManager.locationServicesEnabled() {
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.startUpdatingLocation()
}
onLoadMapView()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
let location1:CLLocationCoordinate2D = CLLocationCoordinate2DMake(40.7484445, -73.9878531)
let location2:CLLocationCoordinate2D = CLLocationCoordinate2DMake(40.758899, -73.9873197)
let location3:CLLocationCoordinate2D = CLLocationCoordinate2DMake(40.7058134, -73.9981622)
let location4:CLLocationCoordinate2D = CLLocationCoordinate2DMake(40.6892534, -74.0466891)
func onLoadMapView() {
let distanceSpan:CLLocationDegrees = 500
mapView?.setRegion(MKCoordinateRegionMakeWithDistance(
location1,
distanceSpan,
distanceSpan
), animated: true)
}
func mapPolylineView(buttonNo: NSNumber) {
let sourceCoordinates = locationManager.location?.coordinate
var destCoordinates: CLLocationCoordinate2D?
if buttonNo == 1 {
destCoordinates = location1
} else if buttonNo == 2 {
destCoordinates = location2
} else if buttonNo == 3 {
destCoordinates = location3
} else if buttonNo == 4 {
destCoordinates = location4
}
let sourceItem = MKMapItem(placemark: MKPlacemark(coordinate: sourceCoordinates!)
let destItem = MKMapItem(placemark: MKPlacemark(coordinate: destCoordinates!)
let directionRequest = MKDirectionsRequest()
directionRequest.source = sourceItem
directionRequest.destination = destItem
directionRequest.transportType = .walking
let directions = MKDirections(request: directionRequest)
directions.calculate(completionHandler: {
response, error in
guard let response = response else {
if error != nil {
print("Something went wrong")
}
return
}
let route = response.routes[0]
self.mapView?.add(route.polyline, level: .aboveRoads)
let rekt = route.polyline.boundingMapRect
self.mapView?.setRegion(MKCoordinateRegionForMapRect(rekt), animated: true)
})
}
func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
let renderer = MKPolylineRenderer(overlay: overlay)
renderer.strokeColor = UIColor(displayP3Red: 69/255, green: 0/255, blue: 132/255, alpha: 1)
renderer.lineWidth = 5.0
return renderer
}
}