I am trying to compare a Polyline - overview_polyline
ruturned by Google Directions API with a set of already existing Polylines and see which part of the new polyline already contains within one of these polylines. For me polyline is a driving route representation, retrieved from Google Directions API. It is basically any route anywhere in the world. Thou for simplification we can always find routes, which belong to a concrete city or a country and compare only thise. Also, at the moment it may be at most 250kms long. Here is some example:
It doesn't matter which route is existing here and which is new. In any case I would like to get the result, that this routes are similar (ok, may be they are not 90% similar, but lets assume they are).
At the moment I am using brute forcing to compare new polyline one by one with an existing polyline. Before that I am splitting polylines into points using this algorithm and compare each point to see, if there is a match. I treat points to be the same if distance between this points is less then 100 meters.
If I found that there is already some polyline, which mostly covers new polyline, I stop processing.
It looks like this:
Polyline findExistingPolyline(Polyline[] polylines, Polyline polyline) {
LatLng[] polylinePoints = PolylineDecoder.toLatLng(polyline);
for (Polyline existing: polylines) {
LatLng[] existingPoints = PolylineDecoder.toLatLng(existing);
if (isMostlyCovered(existingPoints , polylinePoints)) {
return existing;
}
}
return null;
}
boolean isMostlyCovered(LatLng[] existingPoints, LatLng[] polylinePoints) {
int initialSize = polylinePoints.length;
for (LatLng point: polylinePoints) {
for (LatLng existingPoint: existingPoints) {
if (distanceBetween(existingPoint, point) <= 100) {
polylinePoints.remove();// I actually use iterator, here it is just demosnstration
}
}
}
// check how many points are left and decide if polyline is mostly covered
// if 90% of the points is removed - existing polylines covers new polyline
return (polylinePoints.length * 100 / initialSize) <= 10;
}
Obviously, this algorithm sucks (especially in its worst case, when there is no match for new polyline) as there are two many cycles and may be too many points to compare.
So, I was wondering, if there is more efficient approach to compare polylines with each other.