简体   繁体   中英

Draw polyline depend on user location [SWIFT]

I've created an application where I've an map using (MapKit), and when I press "Start" it will automatically zoom into my location and place an annotation.

But from here, I'm confused. I'm trying to draw a poly line from the start position to my current position. (And update every movement I do). So for an example, if I walk 300 meters to the north, I should be able to check the map on my phone and see the poly line is following me.

So start from annotation -----> (Polyline) to User. And keep it updated all times (So you can see the line moving

How can I accomplish that? If you know, please let me know in the comments. I'd be very thankful for it! :)

Code for adding the annotation at the correct position:

@IBAction func StartWalk(_ sender: Any)
    {
        if play == true
        {
            play = false

            //Set resetbutton disabled.
            ResetButton.isHidden = true

            //Set new image when play is true
            PlayStop.setImage(UIImage(named: "Stop"), for: .normal)

            //Bool to check if button is stopped (op)
            isStopped = false

            //Checking userpermission to allow map and current location
            if (CLLocationManager.locationServicesEnabled())
            {
                locationManager.requestAlwaysAuthorization()
                locationManager.requestWhenInUseAuthorization()

                //Retrieve current position
                if let userLocation = locationManager.location?.coordinate
                {
                    //Zooming in to current position
                    let viewRegion = MKCoordinateRegion(center: userLocation, latitudinalMeters: 200, longitudinalMeters: 200)
                    mapView.setRegion(viewRegion, animated: false)

                    //Creating a start annotation
                    let annotation = MKPointAnnotation()
                    annotation.title = "Start"
                    annotation.coordinate = userLocation
                    mapView.addAnnotation(annotation)


                }
            }

        }

    }

Here is the idea for the poly line:

//Create polyline
    func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer
    {
        if(overlay is MKPolyline)
        {
            let polyLineRender = MKPolylineRenderer(overlay: overlay)
            polyLineRender.strokeColor = UIColor.blue.withAlphaComponent(1)
            polyLineRender.lineWidth = 3

            return polyLineRender
        }

        return MKPolylineRenderer()
    }

    //Updating location + polylines
    @objc func update()
    {
        //Startposition
        let startLat = locationManager.location?.coordinate.latitude
        let startlong = locationManager.location?.coordinate.longitude
        let startResult = CLLocation(latitude: startLat!, longitude: startlong!)


        //This should be the current user location.
        let stopLat = locationManager.location?.coordinate.latitude
        let stopLong  = locationManager.location?.coordinate.longitude
        let stopResult = CLLocation(latitude: stopLat!, longitude: stopLong!)


        let locations =
        [
            CLLocationCoordinate2D(latitude: startLat!, longitude: startlong!),
            CLLocationCoordinate2D(latitude: stopLat!, longitude: stopLong!)
        ]

            //Draw polyline on the map
            let aPolyLine = MKPolyline(coordinates: locations, count: locations.count)

            //Adding polyline to mapview
            mapView.addOverlay(aPolyLine)

    }

To make it short:

I want the poly line to start at the start position, and then follow the user wherever he walks until the stop button is pressed. Like chasing the blue dot at all times. Do you know? Please hit me up

Are you implementing the method MKMapViewDelegate on your ViewController class ?

If you are, you can access delegate from MapView, you have to add on viewDidLoad func or any other that you wish the following code with the coordinates :

mapView.delegate = self
// Connect all the mappoints using Poly line.

 var points: [CLLocationCoordinate2D] = [CLLocationCoordinate2D]()

  for annotation in annotations {
     points.append(annotation.coordinate)
  }     
  var polyline = MKPolyline(coordinates: &points, count: points.count)
  mapView.addOverlay(polyline)

You can follow this tutorial below that is very good: http://rshankar.com/how-to-add-mapview-annotation-and-draw-polyline-in-swift/

Set up as a CLLocationManagerDelegate and CoreLocation will feed you positions as they become available. For example:

import CoreLocation

class MyViewController: UIViewController, CLLocationManagerDelegate {

         override func viewDidLoad() {
            super.viewDidLoad()
            setupCoreLocation()
         }

         func setupCoreLocation() {
            let locationManager = CLLocationManager()
            locationManager.delegate = self

            switch CLLocationManager.authorizationStatus() {
            case .notDetermined:
                locationManager.requestWhenInUseAuthorization()
            case .authorizedWhenInUse:
                // NOTE: I normally only set up "WhenInUse" because "Always"
                // can quickly drain the battery on a device.
                locationManager.startUpdatingLocation()
            default:
                break
            }
        }

        func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
            // Create and add your MKPolyline here based on locations
            // passed (the last element of the array is the most recent
            // position).
        }
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM