Skip to content

Instantly share code, notes, and snippets.

@tomaszpolanski
Last active August 29, 2015 14:14
Show Gist options
  • Save tomaszpolanski/b199d281b93883d46ee3 to your computer and use it in GitHub Desktop.
Save tomaszpolanski/b199d281b93883d46ee3 to your computer and use it in GitHub Desktop.
Simple declarative implementation of geocoordinate
package com.tomaszpolanski.androidsandbox.models;
import com.tomaszpolanski.androidsandbox.utils.MathUtils;
import com.tomaszpolanski.androidsandbox.utils.option.Option;
import com.tomaszpolanski.androidsandbox.utils.result.Result;
import com.tomaszpolanski.androidsandbox.utils.result.ResultTuple;
import java.text.DecimalFormat;
import java.text.NumberFormat;
public final class GeoCoordinate {
public final double Latitude;
public final double Longitude;
private GeoCoordinate(final double latitude, final double longitude) {
Latitude = latitude;
Longitude = longitude;
}
public Option<GeoCoordinate> withLatitude(final double latitude) {
return create(latitude, Longitude);
}
public Option<GeoCoordinate> withLongitude(final double longitude) {
return create(Latitude, longitude);
}
public static Option<GeoCoordinate> create(final double latitude, final double longitude) {
return Option.asOption(latitude)
.filter(lat -> Math.abs(lat) <= 90.0)
.flatMap(lat -> Option.asOption(longitude)
.filter(lng -> Math.abs(lng) <= 180.0)
.map(lng -> new GeoCoordinate(lat, lng)));
}
public static Result<GeoCoordinate> fromString(final String stringCoordinate) {
return Result.asResult(stringCoordinate)
.map(cString -> cString.split(","))
.filter(coordinateStringList -> coordinateStringList.length == 2, list -> "Invalid number of items: " + list.length)
.flatMap(coordinateList -> ResultTuple.create(
Result.tryAsResult(() -> Double.parseDouble(coordinateList[0])),
Result.tryAsResult(() -> Double.parseDouble(coordinateList[1]))))
.flatMap(tuple -> tuple.map((latitude, longitude) -> GeoCoordinate.create(latitude, longitude))
.asResult("Coordinates out of bounds"));
}
@SuppressWarnings("EqualsWhichDoesntCheckParameterClass")
@Override
public boolean equals(final Object o) {
final double difference = 0.0001;
return Option.asOption(o)
.filter(obj -> obj instanceof GeoCoordinate)
.map(obj -> (GeoCoordinate) obj)
.filter(other -> MathUtils.areEqual(other.Longitude, Longitude, difference))
.filter(other -> MathUtils.areEqual(other.Latitude, Latitude, difference)) != Option.NONE;
}
@Override
public String toString() {
final NumberFormat formatter = new DecimalFormat("#0.0000");
return String.format("Latitude: %S, Longitude %S",
formatter.format(Latitude),
formatter.format(Longitude));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment