Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to trace users location on MKMapview and draw line on users path

Tags:

ios

mkmapview

I would like to trace my users path on mapView when the user clicks a button on the map and draw a blue or red line along the path like shown in the image below. Also I would like to measure the distance traveled by the user. Currently I am using MKMapView. Is this task possible with iOS map kit or should i move on to using Google maps SDK. I've just started learning iOS development please bear with me if you find the question out of order. enter image description here Thanks in advance...;)

like image 223
bachman Avatar asked Dec 02 '25 12:12

bachman


1 Answers

Might be a bit too late, but for the sake of relevance, here's @Rinju's code in Swift (I added a bit more information here too):

override func viewDidLoad() {
super.viewDidLoad()
//This is a dummy location, you'd add locations to it using the 
//  func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation])
let location:CLLocation = CLLocation(latitude: 200, longitude: 100)
let locationArray:Array<CLLocation> = [location]
let camera:GMSCameraPosition = GMSCameraPosition.camera(withLatitude: (locationArray.first?.coordinate.latitude)!, longitude: (locationArray.first?.coordinate.longitude)!, zoom: 2)
//You can obtain the Lat and Long for above from the list of arrays of locations you saved
//You can use the .first or .last on the array (I used first)

let mapview:GMSMapView = GMSMapView.map(withFrame: CGRect.zero, camera: camera)

let path:GMSMutablePath = GMSMutablePath()
for nextLocation in locationArray {
    if locationArray.index(of: nextLocation) != 0 {
        //You dont want to use the first one as you've already done it
        //so you start with 1
        path.addLatitude(nextLocation.coordinate.latitude, longitude: nextLocation.coordinate.longitude)
    }
}

let polyline:GMSPolyline = GMSPolyline(path: path)
polyline.strokeColor = UIColor.red
polyline.strokeWidth = 2
polyline.map = mapview
self.view = mapview

//I personally prefer view.addSubview(mapview)
}
like image 156
Septronic Avatar answered Dec 05 '25 01:12

Septronic



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!