Maps, test if current location is on or near polyline - android

I'm using google directions api to draw a polyline for a route. Does anyone have any examples of checking if current location is on/near a polyline? Trying to determine if users current location is within x meters of that line and if not i'll make a new request and redraw a new route.
Cheers!

Here is my solution: just add the bdccGeoDistanceAlgorithm class I have created to your project and use bdccGeoDistanceCheckWithRadius method to check if your current location is on or near polyline (polyline equals to a list of LatLng of points)
Your can also get the distance from the method
Class bdccGeoDistanceAlgorithm
import com.google.android.gms.maps.model.LatLng;
import java.util.List;
public class bdccGeoDistanceAlgorithm {
// distance in meters from GLatLng point to GPolyline or GPolygon poly
public static boolean bdccGeoDistanceCheckWithRadius(List<LatLng> poly, LatLng point, int radius)
{
int i;
bdccGeo p = new bdccGeo(point.latitude,point.longitude);
for(i=0; i < (poly.size()-1) ; i++)
{
LatLng p1 = poly.get(i);
bdccGeo l1 = new bdccGeo(p1.latitude,p1.longitude);
LatLng p2 = poly.get(i+1);
bdccGeo l2 = new bdccGeo(p2.latitude,p2.longitude);
double distance = p.function_distanceToLineSegMtrs(l1, l2);
if(distance < radius)
return true;
}
return false;
}
// object
public static class bdccGeo
{
public double lat;
public double lng;
public double x;
public double y;
public double z;
public bdccGeo(double lat, double lon) {
this.lat = lat;
this.lng = lng;
double theta = (lon * Math.PI / 180.0);
double rlat = function_bdccGeoGeocentricLatitude(lat * Math.PI / 180.0);
double c = Math.cos(rlat);
this.x = c * Math.cos(theta);
this.y = c * Math.sin(theta);
this.z = Math.sin(rlat);
}
//returns in meters the minimum of the perpendicular distance of this point from the line segment geo1-geo2
//and the distance from this point to the line segment ends in geo1 and geo2
public double function_distanceToLineSegMtrs(bdccGeo geo1,bdccGeo geo2)
{
//point on unit sphere above origin and normal to plane of geo1,geo2
//could be either side of the plane
bdccGeo p2 = geo1.function_crossNormalize(geo2);
// intersection of GC normal to geo1/geo2 passing through p with GC geo1/geo2
bdccGeo ip = function_bdccGeoGetIntersection(geo1,geo2,this,p2);
//need to check that ip or its antipode is between p1 and p2
double d = geo1.function_distance(geo2);
double d1p = geo1.function_distance(ip);
double d2p = geo2.function_distance(ip);
//window.status = d + ", " + d1p + ", " + d2p;
if ((d >= d1p) && (d >= d2p))
return function_bdccGeoRadiansToMeters(this.function_distance(ip));
else
{
ip = ip.function_antipode();
d1p = geo1.function_distance(ip);
d2p = geo2.function_distance(ip);
}
if ((d >= d1p) && (d >= d2p))
return function_bdccGeoRadiansToMeters(this.function_distance(ip));
else
return function_bdccGeoRadiansToMeters(Math.min(geo1.function_distance(this),geo2.function_distance(this)));
}
// More Maths
public bdccGeo function_crossNormalize(bdccGeo b)
{
double x = (this.y * b.z) - (this.z * b.y);
double y = (this.z * b.x) - (this.x * b.z);
double z = (this.x * b.y) - (this.y * b.x);
double L = Math.sqrt((x * x) + (y * y) + (z * z));
bdccGeo r = new bdccGeo(0,0);
r.x = x / L;
r.y = y / L;
r.z = z / L;
return r;
}
// Returns the two antipodal points of intersection of two great
// circles defined by the arcs geo1 to geo2 and
// geo3 to geo4. Returns a point as a Geo, use .antipode to get the other point
public bdccGeo function_bdccGeoGetIntersection(bdccGeo geo1,bdccGeo geo2, bdccGeo geo3,bdccGeo geo4)
{
bdccGeo geoCross1 = geo1.function_crossNormalize(geo2);
bdccGeo geoCross2 = geo3.function_crossNormalize(geo4);
return geoCross1.function_crossNormalize(geoCross2);
}
public double function_distance(bdccGeo v2)
{
return Math.atan2(v2.function_crossLength(this), v2.function_dot(this));
}
//More Maths
public double function_crossLength(bdccGeo b)
{
double x = (this.y * b.z) - (this.z * b.y);
double y = (this.z * b.x) - (this.x * b.z);
double z = (this.x * b.y) - (this.y * b.x);
return Math.sqrt((x * x) + (y * y) + (z * z));
}
//Maths
public double function_dot(bdccGeo b)
{
return ((this.x * b.x) + (this.y * b.y) + (this.z * b.z));
}
//from Radians to Meters
public double function_bdccGeoRadiansToMeters(double rad)
{
return rad * 6378137.0; // WGS84 Equatorial Radius in Meters
}
// point on opposite side of the world to this point
public bdccGeo function_antipode()
{
return this.function_scale(-1.0);
}
//More Maths
public bdccGeo function_scale(double s)
{
bdccGeo r = new bdccGeo(0,0);
r.x = this.x * s;
r.y = this.y * s;
r.z = this.z * s;
return r;
}
// Convert from geographic to geocentric latitude (radians).
public double function_bdccGeoGeocentricLatitude(double geographicLatitude)
{
double flattening = 1.0 / 298.257223563;//WGS84
double f = (1.0 - flattening) * (1.0 - flattening);
return Math.atan((Math.tan(geographicLatitude) * f));
}
}
}

Related

How to find distance between two locations (By latitude and longitude) in kilometers

I am developing an android app which will track the current location latitude and longitude and store in external database.Here i am having a list of latitudes and longitudes.I populated them by using the custom adapter . But,Here i need the distance from one base latitude and base longitude to remaining items latitude and longitude.Here the base latitude and longitude was selected by the user it self.Here the below the list explains like this i have
SELECTION LAT LONG DISTANCE
-------------------------------------------------
checkbox1 123.4546 456.48751 Text
checkbox2 123.4546 456.48751 Text
checkbox3 123.4546 456.48751 Text
checkbox4 123.4546 456.48751 Text
If user selects the check-box 1 then i have to find the distance from check-box 1 lat long to check-box 2,check-box 3,check-box-4 lat long in KILOMETERS and display in their respected position .
This is some code from adapter i had written but it was not showing any results.
public class Locations_Adapter extends BaseAdapter {
public String distance_string;
Context context;
List<Locations_modle> objects;
double distance, latitude, longitude;
String latitude_string, longitude_string;
double baseLat, baseLong, finalLat, finalLong;
Location location_pointa, location_pointb;
TextView distance_text;
float[] results;
int selectedPostion = -1;
public Locations_Adapter(Context context, int resource, List<Locations_modle> objects) {
this.context = context;
this.objects = objects;
}
/**
* Distance calculation between two lat longs
**/
private static double calculateDistance(double baseLat, double baseLong, double latitude, double longitude, String unit) {
double theta = baseLong - longitude;
double dist = Math.sin(deg2rad(baseLat)) * Math.sin(deg2rad(latitude)) + Math.cos(deg2rad(baseLat)) * Math.cos(deg2rad(longitude)) * Math.cos(deg2rad(theta));
dist = Math.acos(dist);
dist = rad2deg(dist);
dist = dist * 60 * 1.1515;
if (unit == "K") {
dist = dist * 1.609344;
} else if (unit == "N") {
dist = dist * 0.8684;
}
return (dist);
}
/*:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/
/*:: This function converts decimal degrees to radians :*/
/*:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/
private static double deg2rad(double deg) {
return (deg * Math.PI / 180.0);
}
/*:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/
/*:: This function converts radians to decimal degrees :*/
/*:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/
private static double rad2deg(double rad) {
return (rad * 180 / Math.PI);
}
#Override
public int getCount() {
return objects.size();
}
#Override
public Object getItem(int position) {
return objects.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, final ViewGroup parent) {
final View locations_row = LayoutInflater.from(context).inflate(R.layout.layout_adapter_list_details, null);
final Locations_modle location = (Locations_modle) objects.get(position);
TextView text_cust_name = (TextView) locations_row.findViewById(R.id.txt_cust_name_heading);
TextView latitude = (TextView) locations_row.findViewById(R.id.txt_latitude);
latitude.setText(location.getLatitude());
TextView longitude = (TextView) locations_row.findViewById(R.id.txt_longitude);
distance_text = (TextView) locations_row.findViewById(R.id.txt_distance);
longitude.setText(location.getLongitude());
text_cust_name.setText(location.getLocationName());
CheckBox check_locations = (CheckBox) locations_row.findViewById(R.id.check_locations);
final Location location_point_a = new Location("Source");
final Location location_point_b = new Location("Destination");
location_point_a.setLatitude(Double.parseDouble(location.getLatitude()));
location_point_a.setLongitude(Double.parseDouble(location.getLongitude()));
if (position == selectedPostion) {
check_locations.setChecked(true);
} else {
check_locations.setChecked(false);
}
check_locations.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
// selectedPostion = position;
latitude_string = location.getLatitude();
longitude_string = location.getLongitude();
baseLat = Double.parseDouble(latitude_string);
baseLong = Double.parseDouble(longitude_string);
for (int i = 0; i < objects.size(); i++) {
finalLat = Double.parseDouble(objects.get(i).getLatitude());
finalLong = Double.parseDouble(objects.get(i).getLongitude());
calculateDistance(baseLat, baseLong, finalLat, finalLong, "k");
}
distance_text.setText(Double.toString(calculateDistance(baseLat, baseLong, finalLat, finalLong, "k")));
} /*else {
selectedPostion = -1;
}
notifyDataSetChanged();
*/
}
});
return locations_row;
}
}
Can any one tell how to achieve this
You can try this:
public static Double distanceBetween(LatLng point1, LatLng point2)
{
if (point1 == null || point2 == null) {
return null;
}
else{
return SphericalUtil.computeDistanceBetween(point1, point2);
}
}
You can try this
public float distance (float lat_a, float lng_a, float lat_b, float lng_b )
{
double earthRadius = 3958.75;
double latDiff = Math.toRadians(lat_b-lat_a);
double lngDiff = Math.toRadians(lng_b-lng_a);
double a = Math.sin(latDiff /2) * Math.sin(latDiff /2) +
Math.cos(Math.toRadians(lat_a)) * Math.cos(Math.toRadians(lat_b)) *
Math.sin(lngDiff /2) * Math.sin(lngDiff /2);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
double distance = earthRadius * c;
int meterConversion = 1609;
return new Float(distance * meterConversion).floatValue();
}
Use this method:
public static double haversineDistance(double lat1, double lng1, double lat2, double lng2) {
final int R = 6371; // Radious of the earth
double latDistance = toRad(lat2-lat1);
double lonDistance = toRad(lng2-lng1);
double a = Math.sin(latDistance / 2) * Math.sin(latDistance / 2) +
Math.cos(toRad(lat1)) * Math.cos(toRad(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;
distance = distance * 1000 * 0.000621371; // DISTANCE IN MILES
return (distance / 0.62137); // CONVERT MILES TO KM
}
public static double toRad(double value) {
return value * Math.PI / 180;
}
You can try this:
Location loc = new Location("");
Location p = new Location("");
loc.setLatitude(locLat);
loc.setLongitude(locLon);
p.setLatitude(pLat);
p.setLongitude(pLon);
double dis = loc.distanceTo(p);
String.format("%.2f", dis * 0.001);
In loc you set your location
You can use internal Api to find distance between 2 latlng
public double getDistanceBetweenPoints(LatLng origin, LatLng dest, String unit) {
Location selected_location = new Location("Start");
selected_location.setLatitude(origin.latitude);
selected_location.setLongitude(origin.longitude);
Location near_locations = new Location("End");
near_locations.setLatitude(dest.latitude);
near_locations.setLongitude(dest.longitude);
//in meters
double dist = selected_location.distanceTo(near_locations);
if (unit.equals("K")) {
dist = dist * 1.609344;
} else if (unit.equals("N")) {
dist = dist * 0.8684;
}
return dist;
}

Find out if a location is within a shape drawn with polygon on Google Maps v2

If I draw a shape with polygon on Google Maps v2, is there a way to find out if my current location is inside the shape?
please write me a clear code thanks
Draw a rectangle on map with points:
List<LatLng> points = new ArrayList<>();
points.add(new LatLng(lat1, lng1));
points.add(new LatLng(lat2, lng2));
points.add(new LatLng(lat3, lng3));
points.add(new LatLng(lat4, lng4));
Polygon polygon = myMap.addPolygon(new PolygonOptions().addAll(points));
Use android-maps-utils library to check to see is polygon contains your current location point:
boolean contain = PolyUtil.containsLocation(currentLocationLatLng, points, true);
You could create a LatLngBounds based on the specifications of your rectangle and then use the contains method to check whether the current location resides within it.
I split the PolyUtil from the Google Maps Android API Utility Library to one class.
Than just call like follow.
ArrayList<LatLng> polygon = new ArrayList<LatLng>();
LatLng myLocation = new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude());
boolean inPolygon = PolyUtil.containsLocation(myLocation, polygon, false);
And include the PolyUtil class in your code.
import static java.lang.Math.PI;
import static java.lang.Math.log;
import static java.lang.Math.sin;
import static java.lang.Math.tan;
import static java.lang.Math.toRadians;
public class PolyUtil {
/**
* Returns tan(latitude-at-lng3) on the great circle (lat1, lng1) to (lat2, lng2). lng1==0.
* See http://williams.best.vwh.net/avform.htm .
*/
private static double tanLatGC(double lat1, double lat2, double lng2, double lng3) {
return (tan(lat1) * sin(lng2 - lng3) + tan(lat2) * sin(lng3)) / sin(lng2);
}
/**
* Wraps the given value into the inclusive-exclusive interval between min and max.
* #param n The value to wrap.
* #param min The minimum.
* #param max The maximum.
*/
static double wrap(double n, double min, double max) {
return (n >= min && n < max) ? n : (mod(n - min, max - min) + min);
}
/**
* Returns the non-negative remainder of x / m.
* #param x The operand.
* #param m The modulus.
*/
static double mod(double x, double m) {
return ((x % m) + m) % m;
}
/**
* Returns mercator Y corresponding to latitude.
* See http://en.wikipedia.org/wiki/Mercator_projection .
*/
static double mercator(double lat) {
return log(tan(lat * 0.5 + PI/4));
}
/**
* Returns mercator(latitude-at-lng3) on the Rhumb line (lat1, lng1) to (lat2, lng2). lng1==0.
*/
private static double mercatorLatRhumb(double lat1, double lat2, double lng2, double lng3) {
return (mercator(lat1) * (lng2 - lng3) + mercator(lat2) * lng3) / lng2;
}
public static boolean containsLocation(LatLng point, List<LatLng> polygon, boolean geodesic) {
return containsLocation(point.latitude, point.longitude, polygon, geodesic);
}
/**
* Computes whether the given point lies inside the specified polygon.
* The polygon is always considered closed, regardless of whether the last point equals
* the first or not.
* Inside is defined as not containing the South Pole -- the South Pole is always outside.
* The polygon is formed of great circle segments if geodesic is true, and of rhumb
* (loxodromic) segments otherwise.
*/
public static boolean containsLocation(double latitude, double longitude, List<LatLng> polygon, boolean geodesic) {
final int size = polygon.size();
if (size == 0) {
return false;
}
double lat3 = toRadians(latitude);
double lng3 = toRadians(longitude);
LatLng prev = polygon.get(size - 1);
double lat1 = toRadians(prev.latitude);
double lng1 = toRadians(prev.longitude);
int nIntersect = 0;
for (LatLng point2 : polygon) {
double dLng3 = wrap(lng3 - lng1, -PI, PI);
// Special case: point equal to vertex is inside.
if (lat3 == lat1 && dLng3 == 0) {
return true;
}
double lat2 = toRadians(point2.latitude);
double lng2 = toRadians(point2.longitude);
// Offset longitudes by -lng1.
if (intersects(lat1, lat2, wrap(lng2 - lng1, -PI, PI), lat3, dLng3, geodesic)) {
++nIntersect;
}
lat1 = lat2;
lng1 = lng2;
}
return (nIntersect & 1) != 0;
}
/**
* Computes whether the vertical segment (lat3, lng3) to South Pole intersects the segment
* (lat1, lng1) to (lat2, lng2).
* Longitudes are offset by -lng1; the implicit lng1 becomes 0.
*/
private static boolean intersects(double lat1, double lat2, double lng2,
double lat3, double lng3, boolean geodesic) {
// Both ends on the same side of lng3.
if ((lng3 >= 0 && lng3 >= lng2) || (lng3 < 0 && lng3 < lng2)) {
return false;
}
// Point is South Pole.
if (lat3 <= -PI/2) {
return false;
}
// Any segment end is a pole.
if (lat1 <= -PI/2 || lat2 <= -PI/2 || lat1 >= PI/2 || lat2 >= PI/2) {
return false;
}
if (lng2 <= -PI) {
return false;
}
double linearLat = (lat1 * (lng2 - lng3) + lat2 * lng3) / lng2;
// Northern hemisphere and point under lat-lng line.
if (lat1 >= 0 && lat2 >= 0 && lat3 < linearLat) {
return false;
}
// Southern hemisphere and point above lat-lng line.
if (lat1 <= 0 && lat2 <= 0 && lat3 >= linearLat) {
return true;
}
// North Pole.
if (lat3 >= PI/2) {
return true;
}
// Compare lat3 with latitude on the GC/Rhumb segment corresponding to lng3.
// Compare through a strictly-increasing function (tan() or mercator()) as convenient.
return geodesic ?
tan(lat3) >= tanLatGC(lat1, lat2, lng2, lng3) :
mercator(lat3) >= mercatorLatRhumb(lat1, lat2, lng2, lng3);
}
}
Follow these -
https://developer.android.com/training/location/geofencing.html
https://developers.google.com/android/reference/com/google/android/gms/location/Geofence
These links may be what you are looking for.
Just tried Ray Casting algorithm which identifies point in polygon. This works perfect.
private boolean isPointInPolygon(LatLng tap, ArrayList<LatLng> vertices) {
int intersectCount = 0;
for (int j = 0; j < vertices.size() - 1; j++) {
if (rayCastIntersect(tap, vertices.get(j), vertices.get(j + 1))) {
intersectCount++;
}
}
return ((intersectCount % 2) == 1); // odd = inside, even = outside;
}
private boolean rayCastIntersect(LatLng tap, LatLng vertA, LatLng vertB) {
double aY = vertA.latitude;
double bY = vertB.latitude;
double aX = vertA.longitude;
double bX = vertB.longitude;
double pY = tap.latitude;
double pX = tap.longitude;
if ((aY > pY && bY > pY) || (aY < pY && bY < pY)
|| (aX < pX && bX < pX)) {
return false; // a and b can't both be above or below pt.y, and a or
// b must be east of pt.x
}
double m = (aY - bY) / (aX - bX); // Rise over run
double bee = (-aX) * m + aY; // y = mx + b
double x = (pY - bee) / m; // algebra is neat!
return x > pX;
}

Calculate the area of a polygon drawn on google maps in an Android application

I would like to calculate the are of a polygon drawn in a map fragment for a college project.
This is how I draw my polygon.
#Override
public void onMapClick(LatLng point) {
//tvLocInfo.setText("New marker added#" + point.toString());
map.addMarker(new MarkerOptions().position(point).draggable(true).title(point.toString()));
markerClicked = false;
}
#Override
public void onMapLongClick(LatLng point) {
//tvLocInfo.setText("New marker added#" + point.toString());
map.clear();
}
#Override
public boolean onMarkerClick(Marker marker) {
if(markerClicked){
if(polygon != null){
polygon.remove();
polygon = null;
}
polygonOptions.add(marker.getPosition());
polygonOptions.strokeColor(Color.RED);
polygonOptions.fillColor(Color.BLUE);
polygon = map.addPolygon(polygonOptions);
//Area = google.maps.geometry.spherical.computeArea(polygon.getPath().getArray());
}else{
if(polygon != null){
polygon.remove();
polygon = null;
}
polygonOptions = new PolygonOptions().add(marker.getPosition());
markerClicked = true;
}
I have seen this code on how to calculate the area but I am unsure how to implement it in my application and calculate the area of my polygon.
I use this code to calculate an area of a GPS with Android:
private static final double EARTH_RADIUS = 6371000;// meters
public static double calculateAreaOfGPSPolygonOnEarthInSquareMeters(final List<Location> locations) {
return calculateAreaOfGPSPolygonOnSphereInSquareMeters(locations, EARTH_RADIUS);
}
private static double calculateAreaOfGPSPolygonOnSphereInSquareMeters(final List<Location> locations, final double radius) {
if (locations.size() < 3) {
return 0;
}
final double diameter = radius * 2;
final double circumference = diameter * Math.PI;
final List<Double> listY = new ArrayList<Double>();
final List<Double> listX = new ArrayList<Double>();
final List<Double> listArea = new ArrayList<Double>();
// calculate segment x and y in degrees for each point
final double latitudeRef = locations.get(0).getLatitude();
final double longitudeRef = locations.get(0).getLongitude();
for (int i = 1; i < locations.size(); i++) {
final double latitude = locations.get(i).getLatitude();
final double longitude = locations.get(i).getLongitude();
listY.add(calculateYSegment(latitudeRef, latitude, circumference));
Log.d(LOG_TAG, String.format("Y %s: %s", listY.size() - 1, listY.get(listY.size() - 1)));
listX.add(calculateXSegment(longitudeRef, longitude, latitude, circumference));
Log.d(LOG_TAG, String.format("X %s: %s", listX.size() - 1, listX.get(listX.size() - 1)));
}
// calculate areas for each triangle segment
for (int i = 1; i < listX.size(); i++) {
final double x1 = listX.get(i - 1);
final double y1 = listY.get(i - 1);
final double x2 = listX.get(i);
final double y2 = listY.get(i);
listArea.add(calculateAreaInSquareMeters(x1, x2, y1, y2));
Log.d(LOG_TAG, String.format("area %s: %s", listArea.size() - 1, listArea.get(listArea.size() - 1)));
}
// sum areas of all triangle segments
double areasSum = 0;
for (final Double area : listArea) {
areasSum = areasSum + area;
}
// get abolute value of area, it can't be negative
return Math.abs(areasSum);// Math.sqrt(areasSum * areasSum);
}
private static Double calculateAreaInSquareMeters(final double x1, final double x2, final double y1, final double y2) {
return (y1 * x2 - x1 * y2) / 2;
}
private static double calculateYSegment(final double latitudeRef, final double latitude, final double circumference) {
return (latitude - latitudeRef) * circumference / 360.0;
}
private static double calculateXSegment(final double longitudeRef, final double longitude, final double latitude,
final double circumference) {
return (longitude - longitudeRef) * circumference * Math.cos(Math.toRadians(latitude)) / 360.0;
}
I could also use the following polygon which is static if calculating the area of the drawn polygon is not possible.
Polygon UCCpolygon = map.addPolygon(new PolygonOptions()
.add(new LatLng(51.893728, -8.491865),
new LatLng(51.893550, -8.492479),
new LatLng(51.893216, -8.492224),
new LatLng(51.893404, -8.491598))
.strokeColor(Color.RED)
.fillColor(Color.BLUE));
Thanks for the help!
Sean
There's already a library for that.
import com.google.maps.android.SphericalUtil;
//...
List<LatLng> latLngs = new ArrayList<>();
latLngs.add(new LatLng(51.893728, -8.491865));
latLngs.add(new LatLng(51.893550, -8.492479));
latLngs.add(new LatLng(51.893216, -8.492224));
latLngs.add(new LatLng(51.893404, -8.491598));
Log.i(TAG, "computeArea " + SphericalUtil.computeArea(latLngs));
For me the output is computeArea 1920.8879882782069
If you want to use SphericalUtils code without any library, you can use following code. it's taken from opensource code from SphericalUtils.java and other class. I have taken this code and used it as i was using MapBox and MapBox does not have implemented the calculateArea function in Turf.
import java.util.List;
import pojo.LatLng;
import static java.lang.Math.PI;
import static java.lang.Math.abs;
import static java.lang.Math.atan2;
import static java.lang.Math.cos;
import static java.lang.Math.sin;
import static java.lang.Math.tan;
import static java.lang.Math.toRadians;
public class PolygonUtils {
/**
* The earth's radius, in meters.
* Mean radius as defined by IUGG.
*/
static final double EARTH_RADIUS = 6371009;
/**
* Returns the area of a closed path on Earth.
* #param path A closed path.
* #return The path's area in square meters.
*/
public static double computeArea(List<LatLng> path) {
return abs(computeSignedArea(path,EARTH_RADIUS));
}
/**
* Returns the signed area of a closed path on a sphere of given radius.
* The computed area uses the same units as the radius squared.
* Used by SphericalUtilTest.
*/
static double computeSignedArea(List<LatLng> path, double radius) {
int size = path.size();
if (size < 3) { return 0; }
double total = 0;
LatLng prev = path.get(size - 1);
double prevTanLat = tan((PI / 2 - toRadians(prev.getLatitude())) / 2);
double prevLng = toRadians(prev.getLongitude());
// For each edge, accumulate the signed area of the triangle formed by the North Pole
// and that edge ("polar triangle").
for (LatLng point : path) {
double tanLat = tan((PI / 2 - toRadians(point.getLatitude())) / 2);
double lng = toRadians(point.getLongitude());
total += polarTriangleArea(tanLat, lng, prevTanLat, prevLng);
prevTanLat = tanLat;
prevLng = lng;
}
return total * (radius * radius);
}
/**
* Returns the signed area of a triangle which has North Pole as a vertex.
* Formula derived from "Area of a spherical triangle given two edges and the included angle"
* as per "Spherical Trigonometry" by Todhunter, page 71, section 103, point 2.
* See http://books.google.com/books?id=3uBHAAAAIAAJ&pg=PA71
* The arguments named "tan" are tan((pi/2 - latitude)/2).
*/
private static double polarTriangleArea(double tan1, double lng1, double tan2, double lng2) {
double deltaLng = lng1 - lng2;
double t = tan1 * tan2;
return 2 * atan2(t * sin(deltaLng), 1 + t * cos(deltaLng));
}
}

intelligent calculating distance between two geo locations in android

Look at this example:
public void start(){
//...
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, TEN_SECONDS, TEN_METERS, this);
}
#Override
public void onLocationChanged(Location location) {
if(location.distanceTo(_lastLocation) > TEN_KM_IN_METERS){
actionA(location);
_lastLocation = location;
} else {
actionB(location);
}
}
The implementation of Location#distanceTo(l) is pretty complicated and CPU-intensive. So i don't want to call this operation on every location update.
Question: is it any proper way to avoid unnecessary Location#distanceTo(l) calls
What i tried so far. According Wiki - Decimal degrees i do it that way:
private boolean closeTogether(Location a, Location b) {
double changeLat = Math.abs(a.getLatitude() - b.getLatitude());
final float myNaiveMax = 0.005;
if (changeLat > myNaiveMax) {
return false;
}
double changeLon = Math.abs(a.getLongitude() - b.getLongitude());
if (changeLon > myNaiveMax) {
return false;
}
return true;
}
#Override
public void onLocationChanged(Location location) {
if(!closeTogether(location, _lastLocation) && location.distanceTo(_lastLocation) > TEN_KM_IN_METERS){
actionA(location);
_lastLocation = location;
} else {
actionB(location);
}
}
I've found that the Haversine formula is very good for this. Works well for my delivery tracking application. Here's how I calculate the distance between two points. Should get you started :)
/**
* getDistanceBetweenTwoPoints
* #param p1 - First point
* #param p2 - Second point
* #return distance between the two specified points (as the crow flys)
*/
public static double getDistanceBetweenTwoPoints(PointF p1, PointF p2) {
double R = 6371000; // Earth radius
double dLat = Math.toRadians(p2.x - p1.x);
double dLon = Math.toRadians(p2.y - p1.y);
double lat1 = Math.toRadians(p1.x);
double lat2 = Math.toRadians(p2.x);
double a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.sin(dLon / 2)
* Math.sin(dLon / 2) * Math.cos(lat1) * Math.cos(lat2);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
double d = R * c;
return d;
}
Edit And another
public static PointF calculateDerivedPosition(PointF point,
double range, double bearing)
{
double EarthRadius = 6371000; // m
double latA = Math.toRadians(point.x);
double lonA = Math.toRadians(point.y);
double angularDistance = range / EarthRadius;
double trueCourse = Math.toRadians(bearing);
double lat = Math.asin(Math.sin(latA) * Math.cos(angularDistance) +
Math.cos(latA) * Math.sin(angularDistance) * Math.cos(trueCourse));
double dlon = Math.atan2(Math.sin(trueCourse) * Math.sin(angularDistance) * Math.cos(latA),
Math.cos(angularDistance) - Math.sin(latA) * Math.sin(lat));
double lon = ((lonA + dlon + Math.PI) % (Math.PI * 2)) - Math.PI;
lat = Math.toDegrees(lat);
lon = Math.toDegrees(lon);
PointF newPoint = new PointF((float) lat, (float) lon);
return newPoint;
}

How to draw dashed polyline with android google map sdk v2?

I've looked through the documentation of polyline and there is no option to make it dashed.
Do anybody know how to draw dashed polyline with android google map sdk v2?
Now in Polyline you can set the pattern to be Dash, Dot or Gap
simply apply the following
public static final int PATTERN_DASH_LENGTH_PX = 20;
public static final int PATTERN_GAP_LENGTH_PX = 20;
public static final PatternItem DOT = new Dot();
public static final PatternItem DASH = new Dash(PATTERN_DASH_LENGTH_PX);
public static final PatternItem GAP = new Gap(PATTERN_GAP_LENGTH_PX);
public static final List<PatternItem> PATTERN_POLYGON_ALPHA = Arrays.asList(GAP, DASH);
private void drawDashedLeg(GoogleMap googleMap, Route route) {
PolylineOptions polyOptions = new PolylineOptions();
polyOptions.color(ContextCompat.getColor(getContext(), R.color.coolgrey));
polyOptions.addAll(route.getPoints());
polyOptions.pattern(PATTERN_POLYGON_ALPHA);
Polyline polyline = googleMap.addPolyline(polyOptions);
polylines.add(polyline);
}
It is not possible in current release. Follow this issue for updates: https://code.google.com/p/gmaps-api-issues/issues/detail?id=4633
UPDATE
Recently, Google implemented this feature for polylines in Google Maps Android API v2 and marked issue 4633 as Fixed.
See information about stroke patterns in the Shapes Guide. See an example in the Polylines and Polygons tutorial.
You can also read the corresponding blog post here:
https://maps-apis.googleblog.com/2017/02/styling-and-custom-data-for-polylines.html
Alexey, I've just created a function that worked for me and I think that will help you:
public static void createDashedLine(GoogleMap map, LatLng latLngOrig, LatLng latLngDest, int color){
double difLat = latLngDest.latitude - latLngOrig.latitude;
double difLng = latLngDest.longitude - latLngOrig.longitude;
double zoom = map.getCameraPosition().zoom;
double divLat = difLat / (zoom * 2);
double divLng = difLng / (zoom * 2);
LatLng tmpLatOri = latLngOrig;
for(int i = 0; i < (zoom * 2); i++){
LatLng loopLatLng = tmpLatOri;
if(i > 0){
loopLatLng = new LatLng(tmpLatOri.latitude + (divLat * 0.25f), tmpLatOri.longitude + (divLng * 0.25f));
}
Polyline polyline = map.addPolyline(new PolylineOptions()
.add(loopLatLng)
.add(new LatLng(tmpLatOri.latitude + divLat, tmpLatOri.longitude + divLng))
.color(color)
.width(5f));
tmpLatOri = new LatLng(tmpLatOri.latitude + divLat, tmpLatOri.longitude + divLng);
}
}
I created the following function to draw dotted polyline with a list of LatLng points.
This algorithm creates lines of 0.002 kms (followed by 0.002 kms meter gaps) irrespective of zoom. This is useful when you don't want to re-plot polylines when zoom changes.
private void drawDashedPolyLine(GoogleMap mMap, ArrayList<LatLng> listOfPoints, int color) {
/* Boolean to control drawing alternate lines */
boolean added = false;
for (int i = 0; i < listOfPoints.size() - 1 ; i++) {
/* Get distance between current and next point */
double distance = getConvertedDistance(listOfPoints.get(i),listOfPoints.get(i + 1));
/* If distance is less than 0.002 kms */
if (distance < 0.002) {
if (!added) {
mMap.addPolyline(new PolylineOptions()
.add(listOfPoints.get(i))
.add(listOfPoints.get(i + 1))
.color(color));
added = true;
} else {/* Skip this piece */
added = false;
}
} else {
/* Get how many divisions to make of this line */
int countOfDivisions = (int) ((distance/0.002));
/* Get difference to add per lat/lng */
double latdiff = (listOfPoints.get(i+1).latitude - listOfPoints
.get(i).latitude) / countOfDivisions;
double lngdiff = (listOfPoints.get(i + 1).longitude - listOfPoints
.get(i).longitude) / countOfDivisions;
/* Last known indicates start point of polyline. Initialized to ith point */
LatLng lastKnowLatLng = new LatLng(listOfPoints.get(i).latitude, listOfPoints.get(i).longitude);
for (int j = 0; j < countOfDivisions; j++) {
/* Next point is point + diff */
LatLng nextLatLng = new LatLng(lastKnowLatLng.latitude + latdiff, lastKnowLatLng.longitude + lngdiff);
if (!added) {
mMap.addPolyline(new PolylineOptions()
.add(lastKnowLatLng)
.add(nextLatLng)
.color(color));
added = true;
} else {
added = false;
}
lastKnowLatLng = nextLatLng;
}
}
}
}
private double getConvertedDistance(LatLng latlng1, LatLng latlng2) {
double distance = DistanceUtil.distance(latlng1.latitude,
latlng1.longitude,
latlng2.latitude,
latlng2.longitude);
BigDecimal bd = new BigDecimal(distance);
BigDecimal res = bd.setScale(3, RoundingMode.DOWN);
return res.doubleValue();
}
Util class to calculate distance between two LatLng:
public class DistanceUtil {
public static double distance(double lat1, double lon1, double lat2,
double lon2) {
if ((lat1 == lat2) && (lon1 == lon2)) {
return 0;
} else
return distance(lat1, lon1, lat2, lon2, 'K');
}
public static double distance(double lat1, double lon1, double lat2,
double lon2, char 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 == 'K') {
dist = dist * 1.609344;
} else if (unit == 'N') {
dist = dist * 0.8684;
}
return (dist);
}
private static double deg2rad(double deg) {
return (deg * Math.PI / 180.0);
}
private static double rad2deg(double rad) {
return (rad * 180.0 / Math.PI);
}
}
Note: The above algorithm generates very large number of polylines which may take time to render. It is useful only when the list of points is small.

Categories

Resources