How to get angle between two POI?

后端 未结 3 458
傲寒
傲寒 2020-12-19 21:49

How do I calculate the angle in degrees between the coordinates of two POIs (points of interest) on an iPhone map application?

3条回答
  •  庸人自扰
    2020-12-19 22:54

    If the other solutions dont work for you try this:

    - (int)getInitialBearingFrom:(CLLocation *)first
                            to:(CLLocation *)second
    {
        float lat1 = [self degreesToRad:first.coordinate.latitude];
        float lat2 = [self degreesToRad:second.coordinate.latitude];
        float lon1 = [self degreesToRad:first.coordinate.longitude];
        float lon2 = [self degreesToRad:second.coordinate.longitude];
        float dLon = lon2 - lon1;
        float y = sin (dLon) * cos (lat2);
        float x1 = cos (lat1) * sin (lat2);
        float x2 = sin (lat1) * cos (lat2) * cos (dLon);
        float x = x1 - x2;
        float bearingRadRaw = atan2f (y, x);
        float bearingDegRaw = bearingRadRaw * 180 / M_PI;
        int bearing = ((int) bearingDegRaw + 360) % 360; // +- 180 deg to 360 deg
    
        return bearing;
    }
    

    For final bearing, simply take the initial bearing from the end point to the start point and reverse it (using θ = (θ+180) % 360).

    You need these 2 helpers:

    -(float)radToDegrees:(float)radians
    {
        return radians * 180 / M_PI;
    }
    -(float)degreesToRad:(float)degrees
    {
        return degrees * M_PI /180;
    }
    

提交回复
热议问题