Hi Henry,
You'll need to do some conversions because decimals are put into the Java action as BigDecimals and the function provided uses doubles. Easiest method is to just create doubles from the input then create a new BigDecimal as output. I've found this works for me:
double latStartDouble = LatStart.doubleValue();
double latEndDouble = LatEnd.doubleValue();
double longStartDouble = LongStart.doubleValue();
double longEndDouble = LongEnd.doubleValue();
final int R = 6371; // Radius of the earth
double latDistance = Math.toRadians(latEndDouble - latStartDouble);
double lonDistance = Math.toRadians(longStartDouble - longEndDouble);
double a = Math.sin(latDistance / 2) * Math.sin(latDistance / 2) + Math.cos(Math.toRadians(latStartDouble))
* Math.cos(Math.toRadians(latEndDouble)) * Math.sin(lonDistance / 2) * Math.sin(lonDistance / 2);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
double distance = R * c * 1000; // convert to meters
distance = Math.pow(distance, 2);
return new BigDecimal(Math.sqrt(distance));
Note that you'll need to remove the first line of the provided function, as it’s not necessary for the Java action.
Hi Henry,
You can refer to the code below:
public class JA_Henry_CalculateDistance extends CustomJavaAction<java.math.BigDecimal>
{
private java.math.BigDecimal lat1;
private java.math.BigDecimal lat2;
private java.math.BigDecimal lon1;
private java.math.BigDecimal lon2;
public JA_Henry_CalculateDistance(IContext context, java.math.BigDecimal lat1, java.math.BigDecimal lat2, java.math.BigDecimal lon1, java.math.BigDecimal lon2)
{
super(context);
this.lat1 = lat1;
this.lat2 = lat2;
this.lon1 = lon1;
this.lon2 = lon2;
}
@java.lang.Override
public java.math.BigDecimal executeAction() throws Exception
{
// BEGIN USER CODE
double lat1D=lat1.doubleValue();
double lat2D=lat2.doubleValue();
double lon1D=lon1.doubleValue();
double lon2D=lon2.doubleValue();
double dis = this.distance(lat1D, lat2D, lon1D, lon2D);
return new BigDecimal(dis);
// END USER CODE
}
/**
* Returns a string representation of this action
* @return a string representation of this action
*/
@java.lang.Override
public java.lang.String toString()
{
return "JA_Henry_CalculateDistance";
}
// BEGIN EXTRA CODE
public static double distance(double lat1, double lat2, double lon1,
double lon2) {
final int R = 6371; // Radius of the earth
double latDistance = Math.toRadians(lat2 - lat1);
double lonDistance = Math.toRadians(lon2 - lon1);
double a = Math.sin(latDistance / 2) * Math.sin(latDistance / 2)
+ Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2))
* Math.sin(lonDistance / 2) * Math.sin(lonDistance / 2);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
double distance = R * c * 1000; // convert to meters
distance = Math.pow(distance, 2);
return Math.sqrt(distance);
}
// END EXTRA CODE