Good afternoon Community,
I am having trouble plotting the Poly Line within my application, I already tried calling it in the func method locationManager (_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {}
but nothing is generated, just as I would like each step that I take the polyline to be marked and not at the end of my journey. I leave my code below:
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
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.requestLocation()
break;
case .restricted, .denied:
alertLocation(title: "We have a Error", Message: "You have your localization restricted.")
case .authorizedAlways,.authorizedWhenInUse:
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
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation
DispatchQueue.main.async {
self.locationManager.startUpdatingLocation()
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
coordenadas = manager.location?.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)")
}
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()
} }
I have read the documentation a bit and apparently my code is fine, if someone could help me, it would be of great help. Like someone if you have any method that can help me to know when I did and how many steps I walked since I did not see that CLLocation had an option for that type of information.
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()
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.