У меня есть mapView с маркерами (аннотации) и позиция геолокации для пользователя. когда пользователь нажимает один из маркеров, я рисую маршрут между положением пользователя и остроконечным местоположением.Инкапсулировать маршрут в setRegion MapKit swift
Однако масштаб масштабирования карты в позиции пользователя и единственное, что я могу сделать, это установить область карты далеко от пользователя. это неправильный подход, поэтому я готов найти способ увеличения или уменьшения масштаба, чтобы максимизировать вид маршрута.
есть ли способ сделать это?
вот мой код:
// гнездо карты исходя из раскадровки @IBOutlet слабой вар MAPview: MKMapView!
//Geolocation variables
var locationManager = CLLocationManager()
var destination: MKMapItem?
в viewDidLoad
//Setting up delegate and CoreLocaton setup
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestWhenInUseAuthorization()
locationManager.startUpdatingLocation()
mapView.delegate = self
mapView.showsUserLocation = true
let initialLocation = CLLocation(latitude: 45.5215374, longitude: -73.5811606)
let regionRadius: CLLocationDistance = 2000
func centerMapOnLocation(location: CLLocation) {
let coordinateRegion = MKCoordinateRegionMakeWithDistance(location.coordinate,
regionRadius * 2.0, regionRadius * 2.0)
mapView.setRegion(coordinateRegion, animated: true)
}
//Ask the map to center itself
centerMapOnLocation(initialLocation)
делегаты
//MAP DELEGATES
func mapView(mapView: MKMapView!,
didSelectAnnotationView view: MKAnnotationView!){
//remove existing routes
mapView.removeOverlays(mapView.overlays)
//call for new route
var destination = MKPlacemark(coordinate: view.annotation.coordinate, addressDictionary: nil)
getDirection(destination)
}
//INTERACTION WITH ANNOTATIONS (MARKER)
func mapView(mapView: MKMapView!, annotationView view: MKAnnotationView!,
calloutAccessoryControlTapped control: UIControl!) {
if control == view.rightCalloutAccessoryView {
println("Disclosure Pressed! \(view.annotation.subtitle)")
if let cpa = view.annotation as? MapArtwork {
println("cpa.imageName")
}
}
}
//UPDATE LOCATION
func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
if (!locations.isEmpty)
{
let myLocation = locations[0] as! CLLocation
mapView.setRegion(MKCoordinateRegionMake(CLLocationCoordinate2DMake(myLocation.coordinate.latitude, myLocation.coordinate.longitude),
MKCoordinateSpanMake(0.06, 0.06)), animated: true)
}
locationManager.stopUpdatingLocation()
}
//GET DIRECTION BETWEEN GEOPOSITION AND TOUCHED MARKER
func getDirection(location:MKPlacemark){
println("getting direction")
destination = MKMapItem(placemark:location)
let request = MKDirectionsRequest()
request.setSource(MKMapItem.mapItemForCurrentLocation())
request.setDestination(destination!)
request.requestsAlternateRoutes = false
let directions = MKDirections(request: request)
directions.calculateDirectionsWithCompletionHandler({(response:
MKDirectionsResponse!, error: NSError!) in
if error != nil {
// Handle error
println(error)
} else {
self.showRoute(response)
}
})
}
вот та часть, где я установил область карты при отображении маршрута.
//DISPLAY ROUTE OVERLAY
func showRoute(response: MKDirectionsResponse) {
println("showing route")
for route in response.routes as! [MKRoute] {
mapView.addOverlay(route.polyline,
level: MKOverlayLevel.AboveRoads)
for step in route.steps {
println(step.instructions)
}
}
let userLocation = mapView.userLocation
let region = MKCoordinateRegionMakeWithDistance(
userLocation.location.coordinate, 6000, 6000)
mapView.setRegion(region, animated: true)
}
func mapView(mapView: MKMapView!, rendererForOverlay
overlay: MKOverlay!) -> MKOverlayRenderer! {
let renderer = MKPolylineRenderer(overlay: overlay)
renderer.strokeColor = UIColor(red: 8.0/255.0, green: 47.0/255.0, blue: 62.0/255.0, alpha: 1.0)
renderer.lineWidth = 5.0
return renderer
}