package com.example.distance02;

import java.text.DecimalFormat;

public class Haversine 
{

    public static double Haversine(double lat1, double lon1, double lat2, double lon2, String unit) 
    {

    	double theta = lon1 - lon2;
    	double dist = Math.sin(deg2rad(lat1)) * Math.sin(deg2rad(lat2)) + Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) * Math.cos(deg2rad(theta));
    	dist = Math.acos(dist);
    	dist = rad2deg(dist);
    	dist = dist * 60 * 1.1515;
    	  
    	  if (unit.equals("K") )
    	  {
    	    dist = dist * 1.609344;
    	  } 
    	  
    	  else if ( unit.equals("N") ) 
    	  {
    		  dist = dist * 0.8684;
    	  }
    	  
    	  return (dist);

    	
    }
    
    
    	public static double CalculationByDistance(double latitude1, double longitude1, double latitude2, double longitude2)
    	{
        int Radius=6371;//radius of earth in Km         
        double lat1 = latitude1;
        double lat2 = latitude2;
        double lon1 = longitude1;
        double lon2 = longitude2;
        double dLat = Math.toRadians(lat2-lat1);
        double dLon = Math.toRadians(lon2-lon1);
        double a = Math.sin(dLat/2) * Math.sin(dLat/2) +
        Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) *
        Math.sin(dLon/2) * Math.sin(dLon/2);
        double c = 2 * Math.asin(Math.sqrt(a));
        double valueResult= Radius*c;
        double km=valueResult/1;
        DecimalFormat newFormat = new DecimalFormat("####");
        Integer kmInDec =  Integer.valueOf(newFormat.format(km));
        double meter=valueResult%1000;
        Integer  meterInDec= Integer.valueOf(newFormat.format(meter));
        System.out.println("Radius Value "+valueResult+"   KM  "+kmInDec+" Meter   "+meterInDec);

        return Radius * c;
     }
    	
    	
    	public static double CalculationByDistance02(double initialLat, double initialLong, double finalLat, double finalLong){
    	    /*PRE: All the input values are in radians!*/

    	    double latDiff = finalLat - initialLat;
    	    double longDiff = finalLong - initialLong;
    	    double earthRadius = 6371; //In Km if you want the distance in km

    	    double distance = 2*earthRadius*Math.asin(Math.sqrt(Math.pow(Math.sin(latDiff/2.0),2)+Math.cos(initialLat)*Math.cos(finalLat)*Math.pow(Math.sin(longDiff/2),2)));

    	    return distance;

    	}
    	
    
    private static double deg2rad(double deg)
    {
    	  return (deg * Math.PI / 180.0);
    }

    private static double rad2deg(double rad)
    {
    	  return (rad * 180.0 / Math.PI);
    }

}
