Как переместить изображение по пути между двумя местоположениями на карте в android



Я работаю над проектом, в котором показываю два случайных местоположения и путь между ними.Я использовалЭтот учебник для выполнения.



Теперь я хочу показать движущееся изображение из одного места в другое.Я уже поставил метки на этих двух местах.а также я сохранил свою позицию в arraylist.

Я нашел несколько похожих сообщений, но не смог решить свою проблему.



Вот мой код для перемещения drawable:



mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
final Handler handler = new Handler();
int i = 0;

@Override
public boolean onMarkerClick(Marker marker) {
// System.out.println("Marker size:- " + MarkerPoints.size());
handler.post(new Runnable() {

@Override
public void run() {

BitmapDescriptor icon = BitmapDescriptorFactory.fromResource(R.drawable.truck_16);

while (i < MarkerPoints.size()) {
MarkerOptions markerOptions = new MarkerOptions().position(MarkerPoints.get(i))
.title("Current Location")
icon(icon);

System.out.println(MarkerPoints.get(i));
mMap.addMarker(markerOptions);
i++;
handler.postDelayed(this, 3000);
}
}
});

return true;
}
});
493   3  

3 ответов:

   private double bearingBetweenLocations(LatLng latLng1, LatLng latLng2) {
    final double PI = 3.14159;
    final double lat1 = latLng1.latitude * PI / 180;
    final double long1 = latLng1.longitude * PI / 180;
    final double lat2 = latLng2.latitude * PI / 180;
    final double long2 = latLng2.longitude * PI / 180;

    final double dLon = (long2 - long1);

    final double y = Math.sin(dLon) * Math.cos(lat2);
    final double x = Math.cos(lat1) * Math.sin(lat2) - Math.sin(lat1)
            * Math.cos(lat2) * Math.cos(dLon);

    double brng = Math.atan2(y, x);

    brng = Math.toDegrees(brng);
    brng = (brng + 360) % 360;

    return brng;
}

Предположим, что у вас есть текущие и конечные координаты, как показано ниже.

private LatLng CURRENT_LOC = new LatLng(23.013171, 72.522300);
private LatLng DESTINATION_LOC = new LatLng(23.013481, 72.522496);

После этого добавьте маркер на карту google

if (googleMap != null)
{
    BitmapDescriptor icon = BitmapDescriptorFactory.fromResource(R.drawable.truck_16);

    MarkerOptions current = new MarkerOptions().position(CURRENT_LOC).title("Current Point");
    current_marker = googleMap.addMarker(current);
    current_marker.setIcon(icon);
    current_marker.setFlat(true);

    MarkerOptions destination = new MarkerOptions().position(DESTINATION_LOC).title("Destination Point");
    destination_marker = googleMap.addMarker(destination);
    destination_marker.setFlat(true);
}

И переместить маркер по щелчку

@Override
public void onClick(View v)
{
    switch (v.getId())
    {
        case R.id.btn_move:

        float rotate = (float) bearingBetweenLocations(CURRENT_LOC, DESTINATION_LOC);

        rotateMarker(rotate);

        break;
    }
}

Ниже приведены методы, которые перемещают маркер из текущего местоположения в destnation

private double bearingBetweenLocations(LatLng latLng1,LatLng latLng2)
{
    double PI = 3.14159;
    double lat1 = latLng1.latitude * PI / 180;
    double long1 = latLng1.longitude * PI / 180;
    double lat2 = latLng2.latitude * PI / 180;
    double long2 = latLng2.longitude * PI / 180;

    double dLon = (long2 - long1);

    double y = Math.sin(dLon) * Math.cos(lat2);
    double x = Math.cos(lat1) * Math.sin(lat2) - Math.sin(lat1)
            * Math.cos(lat2) * Math.cos(dLon);

    double brng = Math.atan2(y, x);

    brng = Math.toDegrees(brng);
    brng = (brng + 360) % 360;

    return brng;
}

public void rotateMarker(float rotate)
{
    if (current_marker != null)
    {
        //final LatLngInterpolator latLngInterpolator = new LatLngInterpolator.LinearFixed();
        ValueAnimator valueAnimator = new ValueAnimator();
        //final LatLng startPosition = current_marker.getPosition();
        final float startRotation = current_marker.getRotation();
        final float angle = 180 - Math.abs(Math.abs(startRotation - rotate) - 180);
        final float right = WhichWayToTurn(startRotation, rotate);

        valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener()
        {
            @Override
            public void onAnimationUpdate(ValueAnimator animation)
            {
                try
                {
                    if (current_marker == null) // oops... destroying map during animation...
                    {
                        return;
                    }
                    float v = animation.getAnimatedFraction();
                    //newPosition = latLngInterpolator.interpolate(v, startPosition, toLatLng(location));
                    float rotation = startRotation + right * v * angle;
                    current_marker.setRotation(rotation);
                    //current_marker.setPosition(newPosition);
                }
                catch (Exception ex)
                {
                    ex.printStackTrace();
                }
            }
        });

        valueAnimator.addListener(new AnimatorListenerAdapter()
        {
            @Override
            public void onAnimationEnd(Animator animation)
            {
                //current_marker.setPosition(newPosition);
                animateMarker(current_marker, DESTINATION_LOC, false);
            }
        });

        valueAnimator.setFloatValues(0, 1);
        valueAnimator.setDuration(1000);
        valueAnimator.start();
    }
}

public void animateMarker(final Marker marker, final LatLng toPosition, final boolean hideMarker)
{
    final Handler handler = new Handler();
    final long start = SystemClock.uptimeMillis();
    Projection proj = googleMap.getProjection();
    Point startPoint = proj.toScreenLocation(marker.getPosition());
    final LatLng startLatLng = proj.fromScreenLocation(startPoint);
    final long duration = 5000;

    final Interpolator interpolator = new LinearInterpolator();

    handler.post(new Runnable() {
        @Override
        public void run() {
            long elapsed = SystemClock.uptimeMillis() - start;
            float t = interpolator.getInterpolation((float) elapsed / duration);
            double lng = t * toPosition.longitude + (1 - t) * startLatLng.longitude;
            double lat = t * toPosition.latitude + (1 - t) * startLatLng.latitude;
            marker.setPosition(new LatLng(lat, lng));

            if (t < 1.0) {
                // Post again 16ms later.
                handler.postDelayed(this, 16);
            } else {
                if (hideMarker) {
                    marker.setVisible(false);
                } else {
                    marker.setVisible(true);
                }
            }
        }
    });
}

private float WhichWayToTurn(float currentDirection, float targetDirection)
{
    float diff = targetDirection - currentDirection;
    if (Math.abs(diff) == 0)
    {
        return 0;
    }
    if(diff > 180)
    {
        return -1;
    }
    else
    {
        return 1;
    }
}

Надеюсь, это поможет вам.

В конце концов я нашел способ сделать это.Может быть, это не лучший способ, но он решает проблему.Я публикую это, чтобы в будущем, если кому-то нужно делать такие вещи,это может быть полезно.

Я сохранил все точки в ArrayList под названием MarkerPoints, который мы получаем из API и используем его для рисования изображения на любой точке.

Вот код:

public class MyActivity extends FragmentActivity implements Runnable
{
private Thread thread = null;
volatile boolean isRunning;
private ArrayList<LatLng> MarkerPoints; //This arrayList contains all points that are on the route
int i = 0;
Marker marker;


@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_on_trip_maps);

        isRunning = true;
    }

    @Override
    public void run() {

        while (isRunning) {

            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    update();
                }
            });

            control();

        }
    }

    public void update() {

        if (marker != null) {
            marker.remove();
        }
        BitmapDescriptor icon = BitmapDescriptorFactory.fromResource(R.drawable.truck_16);
        marker = mMap.addMarker(new MarkerOptions().position(MarkerPoints.get(i))
                .title("Current Location")
                .icon(icon));

        System.out.println(MarkerPoints.get(i));
        i++;
        if (i > MarkerPoints.size() - 1) {
            isRunning = false;

        }
    }

    public void control() {
        try {
            thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }


}

Это даст движущийся эффект.

Comments

    Ничего не найдено.