
package com.graphhopper.util;

import static java.lang.Math.*;

/**
 * Calculates the approximate distance of two points on earth. Very good results if delat_lon is
 * not too big (see DistanceCalcTest), e.g. the distance is small.
 * <p>
 * http://en.wikipedia.org/wiki/Geographical_distance#Spherical_Earth_projected_to_a_plane
 * <p>
 * http://stackoverflow.com/q/1006654
 * <p>
 * http://en.wikipedia.org/wiki/Mercator_projection#Mathematics_of_the_Mercator_projection
 * http://gis.stackexchange.com/questions/4906/why-is-law-of-cosines-more-preferable-than-haversine-when-calculating-distance-b
 * <p>
 *
 * @author Peter Karich
 */
public class DistancePlaneProjection extends DistanceCalcEarth {
    public static final DistancePlaneProjection DIST_PLANE = new DistancePlaneProjection();

    @Override
    public double calcDist(double fromLat, double fromLon, double toLat, double toLon) {
        double normedDist = calcNormalizedDist(fromLat, fromLon, toLat, toLon);
        return R * sqrt(normedDist);
    }

    @Override
    public double calcDist3D(double fromLat, double fromLon, double fromHeight,
                             double toLat, double toLon, double toHeight) {
        double dEleNorm = hasElevationDiff(fromHeight, toHeight) ? calcNormalizedDist(toHeight - fromHeight) : 0;
        double normedDist = calcNormalizedDist(fromLat, fromLon, toLat, toLon);
        return R * sqrt(normedDist + dEleNorm);
    }

    @Override
    public double calcDenormalizedDist(double normedDist) {
        return R * sqrt(normedDist);
    }

    @Override
    public double calcNormalizedDist(double dist) {
        double tmp = dist / R;
        return tmp * tmp;
    }

    @Override
    public double calcNormalizedDist(double fromLat, double fromLon, double toLat, double toLon) {
        double dLat = toRadians(toLat - fromLat);
        double dLon = toRadians(toLon - fromLon);
        double left = cos(toRadians((fromLat + toLat) / 2)) * dLon;
        return dLat * dLat + left * left;
    }

    @Override
    public String toString() {
        return "PLANE_PROJ";
    }
}
