开发者

Geographical destination formula

开发者 https://www.devze.com 2022-12-27 18:55 出处:网络
I have this PHP function, but it seems to give wrong results. Does anybody have an idea what\'s wrong with it (esp the formula)?

I have this PHP function, but it seems to give wrong results. Does anybody have an idea what's wrong with it (esp the formula)?

/**
 * Finds a destination given a starting location, bearing and distance.
 * 
 * @param array $startingCoordinates The starting coordinates, as non-directional floats in an array wi开发者_运维知识库th lat and lon keys.
 * @param float $bearing The initial bearing in degrees.
 * @param float $distance The distance to travel in km.
 * 
 * @return array The desitination coordinates, as non-directional floats in an array with lat and lon keys.
 */
public static function findDestination( array $startingCoordinates, $bearing, $distance ) {
        $startingCoordinates['lat'] = (float)$startingCoordinates['lat'];
        $startingCoordinates['lon'] = (float)$startingCoordinates['lon'];
        $angularDistance = $distance / Maps_EARTH_RADIUS;
        $lat = asin(
                        sin( $startingCoordinates['lat'] ) * cos( $angularDistance ) +
                        cos( $startingCoordinates['lat'] ) * sin( $angularDistance ) * cos( $bearing )
        );
        return array(
                'lat' => $lat,
                'lon' => $startingCoordinates['lon'] + atan2(
                        sin( $bearing ) * sin( $angularDistance ) * cos( $startingCoordinates['lat'] ),
                        cos( $angularDistance ) - sin( $startingCoordinates['lat'] ) * sin( $lat )
                )
        );
}


The calculations work on radians so you first need to convert the degree-based values to that, and then back again for a meaningful value to you. Eg:

public static function findDestination(array $startingCoordinates, $bearing, $distance) {
        $startingCoordinates['lat'] = deg2rad((float)$startingCoordinates['lat']);
        $startingCoordinates['lon'] = deg2rad((float)$startingCoordinates['lon']);
        $bearing = deg2rad($bearing);
        $angularDistance = $distance / Maps_EARTH_RADIUS;
        $lat = asin(
            sin($startingCoordinates['lat']) * cos( $angularDistance) +
            cos($startingCoordinates['lat']) * sin( $angularDistance) * cos($bearing)
        );
        return array(
            'lat' => rad2deg($lat),
            'lon' => rad2deg($startingCoordinates['lon'] + atan2(
                    sin($bearing ) * sin($angularDistance ) * cos($startingCoordinates['lat']),
                    cos($angularDistance) - sin($startingCoordinates['lat'] ) * sin($lat)
            ))
        );
}

Testing with findDestination(array('lat' => 40.7142691, 'lon' => -74.0059729), 90, 1000) gives the result of 40.714268492616,-73.994108059287, which I think is more like you're looking for.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号