Route Not Showing in Mkmapview

Route not showing in MKMapView?

Actually both source and destination variables were nil.. So i got bad response from the server.If you need just try the below code

func addRoutesOverLayForMapView(){

var source:MKMapItem?
var destination:MKMapItem?
var sourcePlacemark = MKPlacemark(coordinate: pickUpDistanceLocation!.coordinate, addressDictionary: nil)
source = MKMapItem(placemark: sourcePlacemark)

var desitnationPlacemark = MKPlacemark(coordinate: dropOffDistanceLocation!.coordinate, addressDictionary: nil)
destination = MKMapItem(placemark: desitnationPlacemark)
let request:MKDirectionsRequest = MKDirectionsRequest()
request.setSource(source)
request.setDestination(destination)
request.transportType = MKDirectionsTransportType.Walking

let directions = MKDirections(request: request)
directions.calculateDirectionsWithCompletionHandler ({
(response: MKDirectionsResponse?, error: NSError?) in

if error == nil {

self.showRoute(response!)
}
else{

println("trace the error \(error?.localizedDescription)")

}
})
}

func showRoute(response:MKDirectionsResponse){
for route in response.routes as! [MKRoute]{
mapView.addOverlay(route.polyline, level: MKOverlayLevel.AboveRoads)
var routeSeconds = route.expectedTravelTime
let routeDistance = route.distance
println("distance between two points is \(routeSeconds) and \(routeDistance)")


}

}

And you should implement this delegate method,dont forget to set the mapview delegate

  func mapView(mapView: MKMapView!, rendererForOverlay overlay: MKOverlay!) -> MKOverlayRenderer! {

if overlay is MKPolyline {
var polylineRenderer = MKPolylineRenderer(overlay: overlay)
polylineRenderer.lineDashPattern = [14,10,6,10,4,10]
polylineRenderer.strokeColor = UIColor(red: 0.012, green: 0.012, blue: 0.012, alpha: 1.00)
polylineRenderer.lineWidth = 2.5
return polylineRenderer
}
return nil

}

MapKit: Route not being displayed between two annotations

You've almost got it.

The one issue that you need to resolve is the use of the MKMapView delegate functions.

The easiest way to do that is to subclass MKMapView and make your own map view that has conforms to MKMapViewDelegate.

Firstly, create your own map view, subclassing MKMapView and conforming to MKMapViewDelegate. At the moment you're only really using the rendererFor overlay delegate method so I'll just implement that, but you can add other methods if you require them.

class WrappableMapView: MKMapView, MKMapViewDelegate {

func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
let renderer = MKPolylineRenderer(overlay: overlay)
renderer.strokeColor = .red
renderer.lineWidth = 4.0
return renderer
}
}

Then you need to update your UIViewRepresentable to use the new WrappableMapView that you just created. I have gone for making a functional example, so here I am passing in the request and destination locations. You can handle this how you want but at least this will give you something that works.

struct MyMapView: UIViewRepresentable {

@Binding var requestLocation: CLLocationCoordinate2D
@Binding var destinationLocation: CLLocationCoordinate2D

private let mapView = WrappableMapView()

func makeUIView(context: UIViewRepresentableContext<MyMapView>) -> WrappableMapView {
mapView.delegate = mapView // make sure we set our delegate to be the mapView we just created
return mapView
}

func updateUIView(_ uiView: WrappableMapView, context: UIViewRepresentableContext<MyMapView>) {

let requestAnnotation = MKPointAnnotation()
requestAnnotation.coordinate = requestLocation
requestAnnotation.title = "Package Title"
uiView.addAnnotation(requestAnnotation)

let destinationAnnotation = MKPointAnnotation()
destinationAnnotation.coordinate = destinationLocation
destinationAnnotation.title = "Destination"
uiView.addAnnotation(destinationAnnotation)

let requestPlacemark = MKPlacemark(coordinate: requestLocation)
let destinationPlacemark = MKPlacemark(coordinate: destinationLocation)

let directionRequest = MKDirections.Request()
directionRequest.source = MKMapItem(placemark: requestPlacemark)
directionRequest.destination = MKMapItem(placemark: destinationPlacemark)
directionRequest.transportType = .automobile

let directions = MKDirections(request: directionRequest)
directions.calculate { response, error in
guard let response = response else { return }

let route = response.routes[0]
uiView.addOverlay(route.polyline, level: .aboveRoads)

let rect = route.polyline.boundingMapRect
uiView.setRegion(MKCoordinateRegion(rect), animated: true)

// if you want insets use this instead of setRegion
// uiView.setVisibleMapRect(rect, edgePadding: .init(top: 50.0, left: 50.0, bottom: 50.0, right: 50.0), animated: true)
}

}
}

Finally we can put it all together with a ContentView that shows it works:

struct ContentView: View {

@State var requestLocation = CLLocationCoordinate2D(latitude: 51.509865, longitude: -0.118092)
@State var destinationLocation = CLLocationCoordinate2D(latitude: 51.501266, longitude: -0.093210)

var body: some View {
MyMapView(requestLocation: $requestLocation, destinationLocation: $destinationLocation)
}
}

This is what it should look like:

Map View with route


One thing to note, using the rendererFor overlay delegate function in the simulator causes an error. This only happens in the simulator and not on device, so don't be surprised if you see an error message like this in the console.

2019-11-08 18:50:30.034066+0000 StackOverflow[80354:9526181] Compiler error: Invalid library file

MapKit - Route is found but not displaying

Did you make sure to assign the MapView's delegate so it knows where to look for the renderer?

MKDirections not showing route on map in iOS

add this method

-(MKOverlayRenderer *)mapView:(MKMapView *)mapView rendererForOverlay:(id<MKOverlay>)overlay {

MKPolylineRenderer * routeLineRenderer = [[MKPolylineRenderer alloc] initWithPolyline:overlay];

routeLineRenderer.strokeColor = [UIColor blueColor];
routeLineRenderer.lineWidth = 4;
return routeLineRenderer;
}

Swift MapKit not showing directions to pin

Maybe MapView.userLocation.coordinate is nil.

Check "User Location" of the MapView on Storyboard.

Sample Image

Problems drawing poly Line in Map Kit

the problem is not set Map delegate object, also I made some changes to add polyline overlay. Simple but it is working. Good luck.

Maps.delegate = self

Code file:

import UIKit
import MapKit
import CoreLocation

class ViewController: UIViewController, CLLocationManagerDelegate,MKMapViewDelegate {


@IBOutlet var Maps: MKMapView!
var locationManager = CLLocationManager()
var coordenadas = CLLocationCoordinate2D()
var startPoint = MKDirections.Request()
var ArrayDeCoordenadas: [CLLocationCoordinate2D] = []
var tap: Int = 0
var journeyPolyline: MKPolyline?

func getDirections(){

let request = MKDirections.Request()
request.source = MKMapItem.forCurrentLocation()

request.requestsAlternateRoutes = true

let directions = MKDirections(request: request)
directions.calculate { (response, error) in

if error != nil {

print("Error \(error)")


} else {


//self.dispLayRout(response)
var overlays = self.Maps.overlays
self.Maps.removeOverlays(overlays)

for route in response!.routes as! [MKRoute] {

self.Maps.addOverlay(route.polyline,
level: MKOverlayLevel.aboveRoads)

var instructionNumber = 0
for next in route.steps {
instructionNumber += 1
print(next.instructions)
}

}
}

}
}

func alertLocation(title: String, Message:String){

let alert = UIAlertController(title: title, message: Message, preferredStyle: .alert)
let actionAlert = UIAlertAction(title: "Acept", style: .default, handler: nil)
alert.addAction(actionAlert)
self.present(alert, animated: true,completion: nil)

}

func LocalizationInit(){
let autorization = CLLocationManager.authorizationStatus()
switch autorization{
case .notDetermined, .restricted:
locationManager.requestWhenInUseAuthorization()
locationManager.startUpdatingLocation()
break;
case .restricted, .denied:
alertLocation(title: "We have a Error", Message: "You have your localization restricted.")
case .authorizedAlways,.authorizedWhenInUse:
locationManager.startUpdatingLocation()
break;
default:
break;
}
}


@IBAction func Share(_ sender: UIButton) {
let compartir = UIActivityViewController(activityItems: ["Share baby" as Any],
applicationActivities: nil)
compartir.popoverPresentationController?.sourceView = self.view
present(compartir,animated: true,completion: nil)
}

@IBAction func recordButton(_ sender: UIButton) {

if sender.isSelected != true {
tap += 1
print("tap -> :\(tap)")
if tap == 1{
let annotation = MKPointAnnotation()
annotation.title = "My route"
annotation.subtitle = "I Hoppe"
annotation.coordinate = coordenadas
let annotation2 = MKPointAnnotation()
annotation2.title = "My ride"
annotation2.subtitle = "I Hoppe"
annotation.coordinate = locationManager.location?.coordinate as! CLLocationCoordinate2D
self.Maps.addAnnotation(annotation)


}else if tap == 2 {
tap = 0
locationManager.stopMonitoringSignificantLocationChanges()


}
}

}
@IBAction func mapOptions(_ sender: UISegmentedControl) {
switch sender.selectedSegmentIndex{
case 0:
Maps.mapType = MKMapType.standard
break;
case 1:
Maps.mapType = MKMapType.satellite
break;
case 2:
Maps.mapType = MKMapType.hybrid
break;
default:
break;
}
}



override func viewDidLoad() {
super.viewDidLoad()


LocalizationInit()
// let polyLineMake = MKPolyline(coordinates: ArrayDeCoordenadas, count: ArrayDeCoordenadas.count)
// self.Maps.addOverlay(polyLineMake, level: .aboveRoads)
Maps.showsUserLocation = true
Maps.delegate = self
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation
}

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
coordenadas = locations.first!.coordinate as! CLLocationCoordinate2D
ArrayDeCoordenadas.append(locations.last!.coordinate)
print("Array de coordenadas : -> \(ArrayDeCoordenadas)")
let region = MKCoordinateRegion(center: locations.last!.coordinate, latitudinalMeters: 200,
longitudinalMeters: 200)
self.Maps.setRegion(region, animated: false)
let distancia = locations.distance(from: Int(manager.location!.coordinate.latitude), to:
Int((locations.last?.coordinate.latitude)!))
print("distancia \(distancia)")

let polyline = MKPolyline(coordinates: ArrayDeCoordenadas, count: ArrayDeCoordenadas.count)
Maps.addOverlay(polyline)

//remove old polyline
if let oldPolyline = journeyPolyline {
Maps.removeOverlay(oldPolyline)
}

journeyPolyline = polyline
}


func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
if annotation is MKUserLocation{
return nil
}
let pin = MKPinAnnotationView(annotation: annotation, reuseIdentifier: "My personal pin")
pin.pinTintColor = UIColor.green
return pin
}


func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
if overlay is MKPolyline{
let polyline = overlay
let polyLineRender = MKPolylineRenderer(overlay: polyline)
print(" se esta generando \(polyline)")
polyLineRender.strokeColor = UIColor.red
polyLineRender.lineWidth = 6.0
return polyLineRender
}
print(" no se esta generando")
return MKPolylineRenderer()
}

}



Related Topics



Leave a reply



Submit