1

I have used tutorial from the link below to display Google map route in Android app. My question is how can I calculate distance to polyline points on map? Like when I use Google maps app and it tells when a street turn is getting close. I want to implement similar feature in my app. I am able to display the route polyline on the map and it updates itself while I drive along it but I want it to warn me 500 feet in advance of a coming turn. How can I do that?

Here is the link:

http://jigarlikes.wordpress.com/2013/04/26/driving-distance-and-travel-time-duration-between-two-locations-in-google-map-android-api-v2/

Kara
  • 6,115
  • 16
  • 50
  • 57
Sean Kilb
  • 959
  • 5
  • 16
  • 27

1 Answers1

0

I use this method for Markers. Assuming you have Latitude and Longitude of the points that make up the Polyline this should do:

public class MapUtils {

public static float distBetween(LatLng pos1, LatLng pos2) {
    return distBetween(pos1.latitude, pos1.longitude, pos2.latitude,
            pos2.longitude);
}

/** distance in meters **/
public static float distBetween(double lat1, double lng1, double lat2, double lng2) {
    double earthRadius = 3958.75;
    double dLat = Math.toRadians(lat2 - lat1);
    double dLng = Math.toRadians(lng2 - lng1);
    double a = Math.sin(dLat / 2) * Math.sin(dLat / 2)
            + Math.cos(Math.toRadians(lat1))
            * Math.cos(Math.toRadians(lat2)) * Math.sin(dLng / 2)
            * Math.sin(dLng / 2);
    double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
    double dist = earthRadius * c;

    int meterConversion = 1609;

    return (float) (dist * meterConversion);
}
}

To determine wether the road is turning, I would look into euclidean angle between vectors (x being current location and y being a polyline point)

Simply take your current location and a LatLng from some distance ahead for this.

Calculation is based on: http://en.wikipedia.org/wiki/Euclidean_space#Angle

Location currentLocation; // obtained somewhere in your code
LatLng polylinePoint; // a point further ahead

double cLat = currentLocation.getLatitude();
double cLon = currentLocation.getLongitude();

double pLat = polylinePoint.latitude;
double pLon = polylinePoint.longitude;

double angle = Math.acos(
        (cLat*pLat+cLon+pLon) / norm(cLat,cLon)*norm(pLat,cLon));

private double norm(double x, double y) {
    return Math.sqrt(Math.pow(x, 2)*Math.pow(y, 2));    
}

This is untested so might contain error.

cYrixmorten
  • 7,110
  • 3
  • 25
  • 33