Returns the addition of distance between all point int the array. - Java java.lang

Java examples for java.lang:Math Algorithm

Description

Returns the addition of distance between all point int the array.

Demo Code


//package com.java2s;
import java.awt.geom.Point2D;
import java.awt.geom.Point2D.Double;

public class Main {
    public static void main(String[] argv) throws Exception {
        String[] points = new String[] { "1", "abc", "level", null,
                "java2s.com", "asdf 123" };
        System.out.println(distanceArrayGeoPoint(points));
    }// w  w w  .  ja v  a  2s .  c  o m

    private static final double RADIUS = 6371.5;

    /**
     * Returns the addition of distance between all point int the array.
     * @param points the array with all point in the segment.
     * @return the addition of distance between all point int the array.
     */
    public static double distanceArrayGeoPoint(String[] points) {
        String[] coordinates;
        Point2D.Double pointA = new Point2D.Double();
        Point2D.Double pointB = new Point2D.Double();
        double distance = 0.0;

        for (int i = 0; i < points.length - 1; i++) {
            coordinates = points[i].split(",");

            pointA.x = java.lang.Double.parseDouble(coordinates[0]);
            pointA.y = java.lang.Double.parseDouble(coordinates[1]);

            coordinates = points[i + 1].split(",");

            pointB.x = java.lang.Double.parseDouble(coordinates[0]);
            pointB.y = java.lang.Double.parseDouble(coordinates[1]);

            distance += distanceTwoGeoPoint(pointA, pointB);
        }

        return distance;
    }

    /**
     * Returns the calculation of the geographical distance between two points.
     * @param pointA the point from start the segment. 
     * @param pointB the point from ends the segment.
     * @return the distance between two points.
     */
    public static double distanceTwoGeoPoint(Double pointA, Double pointB) {
        double latA = Math.toRadians(pointA.getX());
        double latB = Math.toRadians(pointB.getX());
        double dLon = Math.abs(Math.toRadians(pointA.getY())
                - Math.toRadians(pointB.getY()));
        return (RADIUS * (Math.acos(Math.sin(latA) * Math.sin(latB)
                + Math.cos(latA) * Math.cos(latB) * Math.cos(dLon))));
    }
}

Related Tutorials