简体   繁体   中英

How to show heading direction from Current location to other location on map in ios?

I have a requirement where i have to show the heading direction towards any location on map from user current location. Let say if we have 4 location annotation on map apart from current location and i want to show heading towards any of the location after tapping on it. How can we achieve it. I have gone trough Map API documentation & Locaiotn API, I found that we get the heading value in the delegate method which provided by API when we called the startupdatingheading method. I not getting idea how can we externally get the heading data between two locations. Please help me out. Thanks in advance.

This will calculate the initial bearing to get from lat1,lon1 to lat2,lon2 on a straight line.

double lat1=48.0;  // source latitude, example data
double lon1=17.0;  // source longitude

double lat2=49.0;  // destination latitude
double lon2=18.0;  // destination longitude

double lat1Rad = lat1 * M_PI / 180;
double lat2Rad = lat2 * M_PI / 180;

double dLon = (lon2 - lon1) * M_PI / 180;

double y = sin(dLon) * cos(lat2Rad);
double x = cos(lat1Rad) * sin(lat2Rad) - sin(lat1Rad) * cos(lat2Rad) * cos(dLon);

double bearingRad = atan2(y, x);

// this is the bearing from source to destination in degrees, normalized to 0..360
double bearing = fmod((bearingRad * 180 / M_PI + 360),360);

Swift version:

func getHeading(fromLoc: CLLocationCoordinate2D, toLoc: CLLocationCoordinate2D) -> Double {
    let lat1Rad = fromLoc.latitude * Double.pi / 180
    let lat2Rad = toLoc.latitude * Double.pi / 180
    let dLon = (toLoc.longitude - fromLoc.longitude) * Double.pi / 180
    let y = sin(dLon) * cos(lat2Rad)
    let x = cos(lat1Rad) * sin(lat2Rad) - sin(lat1Rad) * cos(lat2Rad) * cos(dLon)
    let bearingRad = atan2(y, x)
    // this is the bearing from/to in degrees, normalized to 0..360
    return fmod((bearingRad * 180 / Double.pi + 360),360);
}

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