How to update marker using live location along a polyline?

前端 未结 2 1343
野性不改
野性不改 2020-12-11 14:06

My question titles seems to be an existing one, but here is my complete scenario.

I have an activity for Map based operations, where am drawing a polyline along a ro

2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-11 14:39

    I know this question is old, but just in case anyone needs it, adding to Andrii Omelchenko's answer, this is one way you could use SphericalUtil.interpolate() to find the point exactly on the segment:

    private LatLng getMarkerProjectionOnSegment(LatLng carPos, List segment, Projection projection) {
            Point a = projection.toScreenLocation(segment.get(0));
            Point b = projection.toScreenLocation(segment.get(1));
            Point p = projection.toScreenLocation(carPos);
    
            if(a.equals(b.x, b.y)) return segment.get(0); // Projected points are the same, segment is very short
            if(p.equals(a.x, a.y) || p.equals(b.x, b.y)) return carPos;
    
            /*
            If you're interested in the math (d represents point on segment you are trying to find):
            
            angle between 2 vectors = inverse cos of (dotproduct of 2 vectors / product of the magnitudes of each vector)
            angle = arccos(ab.ap/|ab|*|ap|)
            ad magnitude = magnitude of vector ap multiplied by cos of (angle).
            ad = ap*cos(angle) --> basic trig adj = hyp * cos(opp)
            below implementation is just a simplification of these equations
             */
    
            float dotproduct = ((b.x-a.x)*(p.x-a.x)) + ((b.y-a.y)*(p.y-a.y));
            float absquared = (float) (Math.pow(a.x-b.x, 2) + Math.pow(a.y-b.y, 2)); // Segment magnitude squared
    
            // Get the fraction for SphericalUtil.interpolate
            float fraction = dotproduct / absquared;
    
            if(fraction > 1) return segment.get(1);
            if(fraction < 0) return segment.get(0);
            return SphericalUtil.interpolate(segment.get(0), segment.get(1), fraction);
        }
    

提交回复
热议问题