Search code examples
objective-cswiftmkmapviewlatitude-longitudemkannotation

Move the annotation on Map like Uber iOS application


I am working on a project where I need to create a similar iOS application to UBER and OLA where the car is moving based on the location. I'm looking for some kind of Library which can make Cars move and take turns smoothly just like OLA. For now, I was able to move the car from one latitude-longitude to another. But the complex part is how to turn and make sure the car face to the front when moving to the direction.

Please find the below screenshot for the same.

Screenshot


Solution

  • Actually I had also one requirement in my previous iOS application, so please find the below URL for download the code and review it.

    Environment: Xcode 11 and Swift 5

    Link: https://github.com/ram2386/Track-Car

    Highlight of the code in which I had done it.

    For accomplished the functionality for moving the car the same as Uber iOS application, you need to first calculate the angle between old location and new location. Please find the below code for how to calculate it.

    func angleFromCoordinate(firstCoordinate: CLLocationCoordinate2D, 
        secondCoordinate: CLLocationCoordinate2D) -> Double {
        
        let deltaLongitude: Double = secondCoordinate.longitude - firstCoordinate.longitude
        let deltaLatitude: Double = secondCoordinate.latitude - firstCoordinate.latitude
        let angle = (Double.pi * 0.5) - atan(deltaLatitude / deltaLongitude)
        
        if (deltaLongitude > 0) {
            return angle
        } else if (deltaLongitude < 0) {
            return angle + Double.pi
        } else if (deltaLatitude < 0) {
            return Double.pi
        } else {
            return 0.0
        }
    }
    
    //Apply the angle to the particular annotation for moving
    let getAngle = angleFromCoordinate(firstCoordinate: oldLocation, secondCoordinate: newLocation)
    
    //Apply the new location for coordinate
    myAnnotation.coordinate = newLocation;
    
    //Getting the MKAnnotationView
    let annotationView = self.mapView.view(for: myAnnotation)
    
    //Angle for moving the car
    annotationView?.transform = CGAffineTransform(rotationAngle: CGFloat(getAngle))
    

    Please find the below GIF representation, how it looks on the map.

    GIF

    For accomplished the functionality, I had created the .csv file where I had added 1000 records of latitude and longitude.

    Note: You get the angle based on the location, so sometimes it happens you does not get the proper angle due to location as it totally depends on your location.

    I hope it works for you!!!