Marker is not moving along to path with proper rotation - android

I have to draw a marker and a path on map; and I want to move the marker to the path, along with rotating it. My marker is moving, but not along the path. Here is my code:
Marker animation method
public void animateMarker(final int position, final LatLng startPosition, final LatLng toPosition,
final boolean hideMarker) {
Location source = new Location(LocationManager.GPS_PROVIDER);
source.setLatitude(sourceLat);
source.setLongitude(sourceLon);
Location dest = new Location(LocationManager.GPS_PROVIDER);
dest.setLatitude(destLat);
dest.setLongitude(destLon);
final Marker marker = mMap.addMarker(new MarkerOptions()
.position(startPosition)
.title("My Car")
.anchor(0.5f,0.5f)
.snippet("Gurugram")
.rotation(new Location(source).bearingTo(dest))
.icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_car)));
final Handler handler = new Handler();
final long start = SystemClock.uptimeMillis();
final long duration = 50000;
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)
* startPosition.longitude;
double lat = t * toPosition.latitude + (1 - t)
* startPosition.latitude;
marker.setPosition(new LatLng(lat, lng));
if(preLatLng==null){
preLatLng=new LatLng(lat,lng);
}
else{
float bearing = (float) bearingBetweenLocations(preLatLng,new LatLng(lat,lng));
rotateMarker(marker, bearing);
marker.setZIndex(bearing);
preLatLng=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);
}
}
}
});
}
Bearing Method
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;
}
Marker Rotation method rotateMarker rotates the marker with a rotation value.
private boolean isMarkerRotating=false;
private void rotateMarker(final Marker marker, final float toRotation) {
if(!isMarkerRotating) {
final Handler handler = new Handler();
final long start = SystemClock.uptimeMillis();
final float startRotation = marker.getRotation();
final long duration = 2000;
final Interpolator interpolator = new LinearInterpolator();
handler.post(new Runnable() {
#Override
public void run() {
isMarkerRotating = true;
long elapsed = SystemClock.uptimeMillis() - start;
float t = interpolator.getInterpolation((float) elapsed / duration);
float rot = t * toRotation + (1 - t) * startRotation;
float bearing = -rot > 180 ? rot / 2 : rot;
marker.setRotation(bearing);
if (t < 1.0) {
// Post again 16ms later.
handler.postDelayed(this, 16);
} else {
isMarkerRotating = false;
}
}
});
}
}

Related

how to smoothly slow down the rotation speed of marker in google map

i use this line to rotate the marker
marker.setRotation((float) bearingBetweenLocations(startPosition, destination));
this makes a sudden fast rotation. Is their any way to slow down the marker rotation speed
Use like
float bearing = (float) bearingBetweenLocations(startPosition, new LatLng(destination.getLatitude(), destination.getLongitude()));
// mMarker.setRotation((float) bearingBetweenLocations();
rotateMarker(mMarker, bearing);
And methods are
You can change here in rotate marker function final long duration = 500; // Change duration as you want
public 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(final Marker marker, final float toRotation) {
if (!isMarkerRotating) {
final Handler handler = new Handler();
final long start = SystemClock.uptimeMillis();
final float startRotation = marker.getRotation();
final long duration = 500; // Change duration as you want
final Interpolator interpolator = new LinearInterpolator();
handler.post(new Runnable() {
#Override
public void run() {
isMarkerRotating = true;
long elapsed = SystemClock.uptimeMillis() - start;
float t = interpolator.getInterpolation((float) elapsed / duration);
float rot = t * toRotation + (1 - t) * startRotation;
float bearing = -rot > 180 ? rot / 2 : rot;
marker.setRotation(bearing);
if (t < 1.0) {
// Post again 16ms later.
handler.postDelayed(this, 4);
} else {
isMarkerRotating = false;
}
}
});
}
}
Hope it helps.

Animate marker to new location like uber car animation whenever driver location (lat lng) changes on the server

private void GetDriverloc(HashMap<String, String> map) {
Call<DriverLocationResToCus> call = apiInterface.GetDriverLoc(map);
System.out.println("enter the currency alert api" + call.request().url());
call.enqueue(new Callback<DriverLocationResToCus>() {
#Override
public void onResponse(Call<DriverLocationResToCus> call, Response<DriverLocationResToCus> response) {
if (response.isSuccessful()) {
assert response.body() != null;
DriverStartLat = response.body().getDriverCurrentLatStart();
DriverStartLng = response.body().getDriverCurrentLngStart();
DriverEndLat = response.body().getDriverCurrentLatEnd();
DriverEndLng = response.body().getDriverCurrentLngEnd();
/here I am getting the driver's location from server. I need to pass the driver lat lnt to the loop and animate the marker accordingly. I tried to pass it directly to the startpostion and endpostion. But the marker flickers continuesly.
Utilities.printV("DriverStartLat", DriverStartLat);
ValueAnimator polylineAnimator = ValueAnimator.ofInt(0, 100);
polylineAnimator.setDuration(2000);
polylineAnimator.setInterpolator(new LinearInterpolator());
polylineAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(ValueAnimator valueAnimator) {
List<LatLng> points = greyPolyLine.getPoints();
int percentValue = (int) valueAnimator.getAnimatedValue();
int size = points.size();
int newPoints = (int) (size * (percentValue / 100.0f));
List<LatLng> p = points.subList(0, newPoints);
blackPolyline.setPoints(p);
}
});
polylineAnimator.start();
mHandler = new Handler();
index = -1;
next = 1;
mHandler.postDelayed(new Runnable() {
#Override
public void run() {
if (index < points.size() - 1) {
index++;
next = index + 1;
}
if (index < points.size() - 1) {
startPosition = points.get(index);
endPosition = points.get(next);
}
//when I pass the driver's lat lng directly to the startposition and endposition the marker moves to the new location but it comes back if it does not get new lat lat from the server and also flickers continuously.
ValueAnimator valueAnimator = ValueAnimator.ofFloat(0, 1);
valueAnimator.setDuration(3000);
valueAnimator.setInterpolator(new LinearInterpolator());
valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(ValueAnimator valueAnimator) {
v = valueAnimator.getAnimatedFraction();
lng = v * endPosition.longitude + (1 - v)
* startPosition.longitude;
lat = v * endPosition.latitude + (1 - v)
* startPosition.latitude;
LatLng newPos = new LatLng(lat, lng);
marker.setPosition(newPos);
marker.setAnchor(0.5f, 0.5f);
marker.setRotation(getBearing(startPosition, newPos));
mMap.moveCamera(CameraUpdateFactory
.newCameraPosition
(new CameraPosition.Builder()
.target(newPos)
.zoom(15.5f)
.build()));
}
});
valueAnimator.start();
mHandler.postDelayed(this, 3000);
}
}, 3000);
Utilities.printV("DriverLocationResToCus", "DriverLocationResToCus SUCCESS");
} else {
Utilities.printV("DriverLocationResToCus", "DriverLocationResToCus FAILURE");
}
}
#Override
public void onFailure(Call<DriverLocationResToCus> call, Throwable t) {
}
});
}
//can anyone help me with this pls
Download MarkerAnimation and LatLngInterpolator files from the below links
https://drive.google.com/file/d/1i-pDZYOtf-Vl8m6wnYulGnv3rb9aVMih/view
https://drive.google.com/file/d/1AypW3b6YIX6UtYFFuh1-lx7Id1lt0QqP/view
or Use the below posted code
MarkerAnimation code:
public class MarkerAnimation {
public static void animateMarkerToGB(final Marker marker, final LatLng finalPosition, final LatLngInterpolator latLngInterpolator) {
final LatLng startPosition = marker.getPosition();
final Handler handler = new Handler();
final long start = SystemClock.uptimeMillis();
final Interpolator interpolator = new AccelerateDecelerateInterpolator();
final float durationInMs = 3000;
handler.post(new Runnable() {
long elapsed;
float t;
float v;
#Override
public void run() {
// Calculate progress using interpolator
elapsed = SystemClock.uptimeMillis() - start;
t = elapsed / durationInMs;
v = interpolator.getInterpolation(t);
marker.setPosition(latLngInterpolator.interpolate(v, startPosition, finalPosition));
// Repeat till progress is complete.
if (t < 1) {
// Post again 16ms later.
handler.postDelayed(this, 16);
}
}
});
}
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
static void animateMarkerToHC(final Marker marker, final LatLng finalPosition, final LatLngInterpolator latLngInterpolator) {
final LatLng startPosition = marker.getPosition();
ValueAnimator valueAnimator = new ValueAnimator();
valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(ValueAnimator animation) {
float v = animation.getAnimatedFraction();
LatLng newPosition = latLngInterpolator.interpolate(v, startPosition, finalPosition);
marker.setPosition(newPosition);
}
});
valueAnimator.setFloatValues(0, 1); // Ignored.
valueAnimator.setDuration(3000);
valueAnimator.start();
}
#TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
public static void animateMarkerToICS(Marker marker, LatLng finalPosition, final LatLngInterpolator latLngInterpolator) {
TypeEvaluator<LatLng> typeEvaluator = new TypeEvaluator<LatLng>() {
#Override
public LatLng evaluate(float fraction, LatLng startValue, LatLng endValue) {
return latLngInterpolator.interpolate(fraction, startValue, endValue);
}
};
Property<Marker, LatLng> property = Property.of(Marker.class, LatLng.class, "position");
ObjectAnimator animator = ObjectAnimator.ofObject(marker, property, typeEvaluator, finalPosition);
animator.setDuration(3000);
animator.start();
}
}
LatLngInterpolator Code :
public interface LatLngInterpolator {
public LatLng interpolate(float fraction, LatLng a, LatLng b);
public class Linear implements LatLngInterpolator {
#Override
public LatLng interpolate(float fraction, LatLng a, LatLng b) {
double lat = (b.latitude - a.latitude) * fraction + a.latitude;
double lng = (b.longitude - a.longitude) * fraction + a.longitude;
return new LatLng(lat, lng);
}
}
public class LinearFixed implements LatLngInterpolator {
#Override
public LatLng interpolate(float fraction, LatLng a, LatLng b) {
double lat = (b.latitude - a.latitude) * fraction + a.latitude;
double lngDelta = b.longitude - a.longitude;
// Take the shortest path across the 180th meridian.
if (Math.abs(lngDelta) > 180) {
lngDelta -= Math.signum(lngDelta) * 360;
}
double lng = lngDelta * fraction + a.longitude;
return new LatLng(lat, lng);
}
}
public class Spherical implements LatLngInterpolator {
/* From github.com/googlemaps/android-maps-utils */
#Override
public LatLng interpolate(float fraction, LatLng from, LatLng to) {
// http://en.wikipedia.org/wiki/Slerp
double fromLat = toRadians(from.latitude);
double fromLng = toRadians(from.longitude);
double toLat = toRadians(to.latitude);
double toLng = toRadians(to.longitude);
double cosFromLat = cos(fromLat);
double cosToLat = cos(toLat);
// Computes Spherical interpolation coefficients.
double angle = computeAngleBetween(fromLat, fromLng, toLat, toLng);
double sinAngle = sin(angle);
if (sinAngle < 1E-6) {
return from;
}
double a = sin((1 - fraction) * angle) / sinAngle;
double b = sin(fraction * angle) / sinAngle;
// Converts from polar to vector and interpolate.
double x = a * cosFromLat * cos(fromLng) + b * cosToLat * cos(toLng);
double y = a * cosFromLat * sin(fromLng) + b * cosToLat * sin(toLng);
double z = a * sin(fromLat) + b * sin(toLat);
// Converts interpolated vector back to polar.
double lat = atan2(z, sqrt(x * x + y * y));
double lng = atan2(y, x);
return new LatLng(toDegrees(lat), toDegrees(lng));
}
private double computeAngleBetween(double fromLat, double fromLng, double toLat, double toLng) {
// Haversine's formula
double dLat = fromLat - toLat;
double dLng = fromLng - toLng;
return 2 * asin(sqrt(pow(sin(dLat / 2), 2) +
cos(fromLat) * cos(toLat) * pow(sin(dLng / 2), 2)));
}
}
}
This is the bit of code that rotates the icon(marker) on the map
private float getBearing(LatLng begin, LatLng end) {
double lat = Math.abs(begin.latitude - end.latitude);
double lng = Math.abs(begin.longitude - end.longitude);
if (begin.latitude < end.latitude && begin.longitude < end.longitude)
return (float) (Math.toDegrees(Math.atan(lng / lat)));
else if (begin.latitude >= end.latitude && begin.longitude < end.longitude)
return (float) ((90 - Math.toDegrees(Math.atan(lng / lat))) + 90);
else if (begin.latitude >= end.latitude && begin.longitude >= end.longitude)
return (float) (Math.toDegrees(Math.atan(lng / lat)) + 180);
else if (begin.latitude < end.latitude && begin.longitude >= end.longitude)
return (float) ((90 - Math.toDegrees(Math.atan(lng / lat))) + 270);
return -1;
}
This is the bit of code that you need to add after getting Lat and Lng from api.
if(marker == null) {
marker = mMap.addMarker(new MarkerOptions().position(endPosition)
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ROSE)));
MarkerAnimation.animateMarkerToGB(marker, endPosition, new LatLngInterpolator.Spherical());
marker.setRotation(getBearing(endPosition, startPosition));
} else {
MarkerAnimation.animateMarkerToICS(marker, endPosition, new LatLngInterpolator.Spherical());
marker.setRotation(getBearing(endPosition, startPosition));
}
Happy coding :)

my marker in google maps keeps on changing position.Is there anyway to solve this issue?

i am trying to place a marker to a map according to location, and my activity refreshes after every 10 sec so that I can get location from database every 10.
What I am expecting is to change marker location every 10 sec but marker keeps on changing position frequently that is 5 to 6 times every 10 sec.
And my cab marker also keeps on dissapearing I this its the map.clear(), but without it 2 to 4 markers keeps on reappearing
For placing markers
LatLngBounds.Builder builder = new LatLngBounds.Builder();
ArrayList<Marker> markers = new ArrayList<>();
mMap.clear(); // to clear markers and polylines
drivLat1 = driverLocation.getLatitude();
drivLng1 = driverLocation.getLongitude();
drivLat2 = driverChangedLocation.getLatitude();
drivLng2 = driverChangedLocation.getLongitude();
bearingBetweenLocations(drivLat1,drivLng1,drivLat2,drivLng2);
BitmapDescriptor icon = BitmapDescriptorFactory.fromResource(R.drawable.car_marker);
markers.add(0,mMap.addMarker(new MarkerOptions().position(new LatLng(driverLocation.getLatitude(), driverLocation.getLongitude()))
.icon(icon)
.title("Driver Location")));
markers.add(1,mMap.addMarker(new MarkerOptions().position(new LatLng(location.getLatitude(), location.getLongitude())).title("User Location")));
rotateMarker(markers.get(0), (float) bearingBetweenLocations(drivLat1,drivLng1,drivLat2,drivLng2));
for (Marker marker : markers) {
builder.include(marker.getPosition());
}
LatLngBounds bounds = builder.build();
int padding = 100;
CameraUpdate cu = CameraUpdateFactory.newLatLngBounds(bounds, padding);
mMap.animateCamera(cu);
private double bearingBetweenLocations(double lat11 ,double long11,double lat22 ,double long22) {
double PI = 3.14159;
double lat1 = lat11 * PI / 180;
double long1 = long11 * PI / 180;
double lat2 = lat22 * PI / 180;
double long2 = long22 * 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;
}
private void rotateMarker(final Marker marker, final float toRotation) {
if (!isMarkerRotating) {
final Handler handler = new Handler();
final long start = SystemClock.uptimeMillis();
final float startRotation = marker.getRotation();
final long duration = 1000;
final Interpolator interpolator = new LinearInterpolator();
handler.post(new Runnable() {
#Override
public void run() {
isMarkerRotating = true;
long elapsed = SystemClock.uptimeMillis() - start;
float t = interpolator.getInterpolation((float) elapsed / duration);
float rot = t * toRotation + (1 - t) * startRotation;
marker.setRotation(-rot > 180 ? rot / 2 : rot);
if (t < 1.0) {
// Post again 16ms later.
handler.postDelayed(this, 16);
} else {
isMarkerRotating = false;
}
}
});
}
}
And this is how I set accuracy, bcoz I think that this can be a problem
if (location.hasAccuracy()) {
// Accuracy is in rage of 20 meters, stop listening we have a fix
if (location.getAccuracy() < 20) {
LocationServices.FusedLocationApi.removeLocationUpdates(client, this);
}
}
What I want is that markers only change position when data gets updated

How to move an image over the path between two location on map in android

I am working on a project in which I am showing two random location and the path between them.I have used this tutorial to accomplish.
Now i want to show the moving image from one location to another.I have already put markers on that two locations.and also I have saved the position in an arraylist.
I had found some similar posts but couldn't solve my issue.
Here is my code for moving the 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;
}
});
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;
}
Suppose you have current and destination co-ordinates like below.
private LatLng CURRENT_LOC = new LatLng(23.013171, 72.522300);
private LatLng DESTINATION_LOC = new LatLng(23.013481, 72.522496);
After that add marker on google map
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);
}
And move marker on click
#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;
}
}
below all are methods that move marker from current location to 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;
}
}
Hope this would help you.
Finally I found a way to accomplish this.May be this is not the best way but it solves the problem.I am posting this so in future if someone needs to do stuff like that,It can be helpful.
I have store all the points in an ArrayList called MarkerPoints that we get from the API and use it to draw the image on ever point.
Here is the code:
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();
}
}
}
This will give the moving effect.

Rotate marker/car icon in google maps - Android

I am trying to crate a app like ola/uber. I want to move the icon and rotate when road turn left or right. I am using following code.
private void rotateMarker(final Marker marker, final float toRotation) {
if(!isMarkerRotating) {
final Handler handler = new Handler();
final long start = SystemClock.uptimeMillis();
final float startRotation = marker.getRotation();
final long duration = 1000;
final Interpolator interpolator = new LinearInterpolator();
handler.post(new Runnable() {
#Override
public void run() {
isMarkerRotating = true;
long elapsed = SystemClock.uptimeMillis() - start;
float t = interpolator.getInterpolation((float) elapsed / duration);
float rot = t * toRotation + (1 - t) * startRotation;
marker.setRotation(-rot > 180 ? rot / 2 : rot);
if (t < 1.0) {
// Post again 16ms later.
handler.postDelayed(this, 16);
} else {
isMarkerRotating = false;
}
}
});
}
}
To calculate bearing:
currentLocation = location;
if(previousLocaton!=null){
previousLocaton = tempLocation;
tempLocation = currentLocation;
Log.d("previousLocaton=====> ",""+previousLocaton);
Log.d("currentLocation=====> ",""+currentLocation);
bearing = previousLocaton.bearingTo(currentLocation) ;
}else{
previousLocaton = location;
tempLocation = location;
}
To set the bearing:
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(latLng).zoom(14).bearing(bearing).build();
To rotate the marker I call roateMarker method in onLocationChanged changed method:
currLocationMarker = mMap.addMarker(markerOptions);
rotateMarker(currLocationMarker,bearing);
Now my icon is rotating. But google map also get rotating. I want rotate icon alone. I refer the following link for animate and move the marker. Link 1. Please let me any idea to solve my issue.
there is simple method available for marker
marker.rotation(float value)
Sets the rotation of the marker in degrees clockwise about the marker's anchor point. The axis of rotation is perpendicular to the marker. A rotation of 0 corresponds to the default position of the marker. When the marker is flat on the map, the default position is North aligned and the rotation is such that the marker always remains flat on the map. When the marker is a billboard, the default position is pointing up and the rotation is such that the marker is always facing the camera. The default value is 0.
To rotate only the marker set rotation to marker using setRotation(float) method.
static public void rotateMarker(final Marker marker, final float toRotation) {
final Handler handler = new Handler();
final long start = SystemClock.uptimeMillis();
final float startRotation = marker.getRotation();
final long duration = 1000;
final Interpolator interpolator = new LinearInterpolator();
L.d("Bearing: "+toRotation);
handler.post(new Runnable() {
#Override
public void run() {
long elapsed = SystemClock.uptimeMillis() - start;
float t = interpolator.getInterpolation((float) elapsed / duration);
float rot = t * toRotation + (1 - t) * startRotation;
marker.setRotation(-rot > 180 ? rot / 2 : rot);
if (t < 1.0) {
// Post again 10ms later.
handler.postDelayed(this, 10);
}
}
});
}
Try this :
public void animateMarker(final LatLng toPosition, final LatLng startLatLng,
final boolean hideMarker) {
final Handler handler = new Handler();
final long start = SystemClock.uptimeMillis();
Projection proj = map.getProjection();
Point startPoint = proj.toScreenLocation(d_marker.getPosition());
final LatLng startLatLng = proj.fromScreenLocation(startPoint);
// final CameraPosition newcameraPosition = null;
final Interpolator interpolator = new LinearInterpolator();
handler.post(new Runnable() {
#Override
public void run() {
Location prevLoc = new Location("service Provider");
prevLoc.setLatitude(startLatLng.latitude);
prevLoc.setLongitude(startLatLng.longitude);
Location newLoc = new Location("service Provider");
newLoc.setLatitude(toPosition.latitude);
newLoc.setLongitude(toPosition.longitude);
System.out.println("Locations ---- " + prevLoc + "-" + newLoc);
float bearing = prevLoc.bearingTo(newLoc);
long elapsed = SystemClock.uptimeMillis() - start;
float t = interpolator.getInterpolation((float) elapsed
/ 1000);
double lng = t * toPosition.longitude + (1 - t)
* startLatLng.longitude;
double lat = t * toPosition.latitude + (1 - t)
* startLatLng.latitude;
d_marker.setPosition(new LatLng(lat, lng));
d_marker.setRotation(bearing);
d_marker.setFlat(true);
// googleMap.moveCamera(CameraUpdateFactory.newCameraPosition(newcameraPosition));
if (t < 1.0) {
// Post again 16ms later.
handler.postDelayed(this, 16);
} else {
if (hideMarker) {
d_marker.setVisible(false);
} else {
d_marker.setVisible(true);
}
}
}
});
}
Try Below method:
public void animateMarker(final LatLng toPosition,
final boolean hideMarker) {
final Handler handler = new Handler();
final long start = SystemClock.uptimeMillis();
Projection proj = googleMap.getProjection();
Point startPoint = proj.toScreenLocation(cabMarker.getPosition());
final LatLng startLatLng = proj.fromScreenLocation(startPoint);
// final CameraPosition newcameraPosition = null;
final Interpolator interpolator = new LinearInterpolator();
handler.post(new Runnable() {
#Override
public void run() {
Location prevLoc = new Location("service Provider");
prevLoc.setLatitude(startLatLng.latitude);
prevLoc.setLongitude(startLatLng.longitude);
Location newLoc = new Location("service Provider");
newLoc.setLatitude(toPosition.latitude);
newLoc.setLongitude(toPosition.longitude);
System.out.println("Locations ---- " + prevLoc + "-" + newLoc);
float bearing = prevLoc.bearingTo(newLoc);
long elapsed = SystemClock.uptimeMillis() - start;
float t = interpolator.getInterpolation((float) elapsed
/ 1000);
double lng = t * toPosition.longitude + (1 - t)
* startLatLng.longitude;
double lat = t * toPosition.latitude + (1 - t)
* startLatLng.latitude;
cabMarker.setPosition(new LatLng(lat, lng));
cabMarker.setRotation(bearing);
// googleMap.moveCamera(CameraUpdateFactory.newCameraPosition(newcameraPosition));
if (t < 1.0) {
// Post again 16ms later.
handler.postDelayed(this, 16);
} else {
if (hideMarker) {
cabMarker.setVisible(false);
} else {
cabMarker.setVisible(true);
}
}
}
});
}

Categories

Resources