First of all my marker won't show up. But if it did then how would I keep it moving? I'm tracking a satellite. Iv'e done research but all i've found were folks using JSON arrays on their maps. However I have an object that needs to update across the map
I'm using a json OBJECT. Please don't give me links unless you are absolutely sure you know it can apply to my situation. Can anyone help?
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private LocationManager locationManager;
private GoogleMap mMap;
JSONParser jsonparser = new JSONParser();
private CameraPosition cameraPosition;
private GoogleMap googleMap;
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
private GoogleApiClient client;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(map);
List<MarkerOptions> markerOptions = new ArrayList<>();
Bitmap.Config conf = Bitmap.Config.ARGB_8888;
Bitmap bmp = Bitmap.createBitmap(200, 50, conf);
Canvas canvas = new Canvas(bmp);
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
}
public void animateMarker(final Marker marker, final LatLng toPosition,
final boolean hideMarker) {
MapFragment mapFragment = new MapFragment();
mapFragment.getMapAsync(this);
jobj = jsonparser.makeHttpRequest("http://api.wheretheiss.at/v1/satellites/25544");
try {
String lati = "latitude : " + jobj.getDouble("latitude");
} catch (JSONException e) {
e.printStackTrace();
}
try {
String longit = "longitude : " + jobj.getDouble("longitude");
} catch (JSONException e) {
e.printStackTrace();
}
final Handler handler = new Handler() {
};
final long start = SystemClock.uptimeMillis();
Projection proj = mMap.getProjection();
Point startPoint = proj.toScreenLocation(marker.getPosition());
final LatLng startLatLng = proj.fromScreenLocation(startPoint);
final long duration = 500;
final Interpolator interpolator = new LinearInterpolator();
handler.post(new Runnable() {
#Override
public void run() {
jobj = jsonparser.makeHttpRequest("http://api.wheretheiss.at/v1/satellites/25544");
try {
Double longit = jobj.getDouble("longitude");
Double lat = jobj.getDouble("latitude");
marker.setTitle("ISS");
marker.showInfoWindow();
marker.setPosition(new LatLng(lat, longit));
CameraUpdate center= CameraUpdateFactory.newLatLng(new LatLng(lat, longit));
CameraUpdate zoom = CameraUpdateFactory.newLatLngZoom(new LatLng(lat, longit),3);
googleMap.animateCamera(center);
googleMap.animateCamera(zoom);
} catch (JSONException e) {
e.printStackTrace();
}
long elapsed = SystemClock.uptimeMillis() - start;
float t = interpolator.getInterpolation((float) elapsed
/ duration);
if (t < 1.0) {
// Post again 16ms later.
handler.postDelayed(this, 16);
} else {
if (hideMarker) {
marker.setVisible(false);
} else {
marker.setVisible(true);
}
}
}
});
}
public void onLocationChanged(Location location) {
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(
new LatLng(location.getLatitude(), location.getLongitude()), 17));
}
}
First of all, it seems like you forgot add your marker to map. I didn't see this code in your activity.
Secondly, there is an example of working method to move markers on the google map, developed by guys from google.
#TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
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();
}
And interpolator:
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);
}
}
}
More information you can find there
Related
now i am getting latitude and longitude n time, if i move with my phone the marker also moving according latitude and longitude, but i need to draw a route line if phone change the position. example i have T1, T2, T4, T5 time latitude longitude points i need to draw route line from T1 to T2 and T2 to T3 and T3 to T4 So on in real time, i am unable draw the lines.
MainActivity
public class MainActivity extends AppCompatActivity implements OnMapReadyCallback {
private static final int MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION = 5445;
private GoogleMap googleMap;
private FusedLocationProviderClient fusedLocationProviderClient;
private Marker currentLocationMarker;
private Location currentLocation;
private boolean firstTimeFlag = true;
private final View.OnClickListener clickListener = view -> {
if (view.getId() == R.id.currentLocationImageButton && googleMap != null && currentLocation != null)
animateCamera(currentLocation);
};
private final LocationCallback mLocationCallback = new LocationCallback() {
#Override
public void onLocationResult(LocationResult locationResult) {
super.onLocationResult(locationResult);
if (locationResult.getLastLocation() == null)
return;
currentLocation = locationResult.getLastLocation();
if (firstTimeFlag && googleMap != null) {
animateCamera(currentLocation);
firstTimeFlag = false;
}
showMarker(currentLocation);
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SupportMapFragment supportMapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.mapFragment);
supportMapFragment.getMapAsync(this);
findViewById(R.id.currentLocationImageButton).setOnClickListener(clickListener);
mydb = new DatabaseHelper(this);
}
#Override
public void onMapReady(GoogleMap googleMap) {
this.googleMap = googleMap;
}
private void startCurrentLocationUpdates() {
LocationRequest locationRequest = LocationRequest.create();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setInterval(3000);
//locationRequest.setFastestInterval(1000);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ActivityCompat.checkSelfPermission(this,
android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) !=
PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);
return;
}
}
fusedLocationProviderClient.requestLocationUpdates(locationRequest, mLocationCallback,
Looper.myLooper());
}
private boolean isGooglePlayServicesAvailable() {
GoogleApiAvailability googleApiAvailability = GoogleApiAvailability.getInstance();
int status = googleApiAvailability.isGooglePlayServicesAvailable(this);
if (ConnectionResult.SUCCESS == status)
return true;
else {
if (googleApiAvailability.isUserResolvableError(status))
Toast.makeText(this, "Please Install google play services to use this application", Toast.LENGTH_LONG).show();
}
return false;
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION) {
if (grantResults[0] == PackageManager.PERMISSION_DENIED)
Toast.makeText(this, "Permission denied by uses", Toast.LENGTH_SHORT).show();
else if (grantResults[0] == PackageManager.PERMISSION_GRANTED)
startCurrentLocationUpdates();
}
}
private void animateCamera(#NonNull Location location) {
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(getCameraPositionWithBearing(latLng)));
addLines(latLng);
AddData(location);
}
#NonNull
private CameraPosition getCameraPositionWithBearing(LatLng latLng) {
addLines(latLng);
return new CameraPosition.Builder().target(latLng).zoom(16).build();
}
private void showMarker(#NonNull Location currentLocation) {
LatLng latLng = new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude());
BitmapDescriptor icon =
BitmapDescriptorFactory.fromResource(R.drawable.ic_person_pin_circle_black_24dp);
addLines(latLng);
viewAll();
if (currentLocationMarker == null)
currentLocationMarker = googleMap.addMarker(new
MarkerOptions().icon(BitmapDescriptorFactory.defaultMarker()).flat(true).position(latLng));
else
MarkerAnimation.animateMarkerToGB(currentLocationMarker, latLng, new LatLngInterpolator.Spherical());
}
#Override
protected void onStop() {
super.onStop();
if (fusedLocationProviderClient != null)
fusedLocationProviderClient.removeLocationUpdates(mLocationCallback);
}
#Override
protected void onResume() {
super.onResume();
if (isGooglePlayServicesAvailable()) {
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
startCurrentLocationUpdates();
}
}
#Override
protected void onDestroy() {
super.onDestroy();
fusedLocationProviderClient = null;
googleMap = null;
}
private void addLines(LatLng latLng) {
LatLng TIMES_SQUARE = new LatLng(latLng.latitude, latLng.longitude);
LatLng BROOKLYN_BRIDGE = new LatLng(latLng.latitude, latLng.longitude);
LatLng LOWER_MANHATTAN = new LatLng(latLng.latitude, latLng.longitude);
Log.i("===Lat", String.valueOf(latLng.latitude));
Log.i("===Longt", String.valueOf(latLng.longitude));
String polyLine = "q`epCakwfP_#EMvBEv#iSmBq#GeGg#}C]mBS{#KTiDRyCiBS";
List<LatLng> polyLineList = Collections.singletonList(TIMES_SQUARE);
LatLngBounds.Builder builder = new LatLngBounds.Builder();
for (LatLng latLng1 : polyLineList) {
builder.include(latLng1);
googleMap.addPolyline((new PolylineOptions())
//.add(TIMES_SQUARE, LOWER_MANHATTAN,TIMES_SQUARE).width(5).color(Color.RED)
//.add( new LatLng(14.2354843, 76.2484165), new LatLng(14.2251, 76.3980)).width(5).color(Color.RED)
.add(new LatLng(latLng.latitude, latLng.longitude), new LatLng(latLng.latitude, latLng.longitude)).addAll(polyLineList).width(5).color(Color.BLUE)
.geodesic(true));
PolylineOptions polylineOptions = new PolylineOptions();
polylineOptions.color(Color.BLACK);
polylineOptions.width(5);
polylineOptions.startCap(new SquareCap());
polylineOptions.endCap(new SquareCap());
polylineOptions.jointType(ROUND);
polylineOptions.addAll(polyLineList);
Polyline greyPolyLine = googleMap.addPolyline(polylineOptions);
}
;
// move camera to zoom on map
// googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(LOWER_MANHATTAN,13));
}
}
MarkerAnimation
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);
handler.postDelayed(this, 16);
}
}
});
}
}
LatLngInterpolator Interface
public interface LatLngInterpolator {
LatLng interpolate(float fraction, LatLng a, LatLng b);
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)));
}
}
}
Consider replacing your addLines method with this which maintains and redraws polyline on every update:
private List<LatLng> polyLineList = new ArrayList<>();
private Polyline greyPolyLine;
private void addToLine(LatLng pt)
{
polyLineList.add(pt);
if (greyPolyLine != null)
{
greyPolyLine.remove();
}
PolylineOptions polylineOptions = new PolylineOptions();
polylineOptions.color(Color.BLACK);
polylineOptions.width(5);
polylineOptions.startCap(new SquareCap());
polylineOptions.endCap(new SquareCap());
polylineOptions.jointType(ROUND);
polylineOptions.addAll(polyLineList);
greyPolyLine = googleMap.addPolyline(polylineOptions);
}
You addLine was simply drawing a single point on every invocation - a single point is unlikely to be visible.
Probably only need to call it in the showMarker method - not sure why you're calling addLines in the camera methods.
I am trying to use Geofire to store and display the users that are logged in on a map I am new in android studio as I am able to store location on firebase using geofire
but I am not able to retrieve the stored location from the firebase
Here is my code
public class tracking extends FragmentActivity implements
GeoQueryEventListener,OnMapReadyCallback,
GoogleMap.OnCameraChangeListener{
private static final GeoLocation INITIAL_CENTER = new GeoLocation(30.7333148, 76.7794179);
private static final int INITIAL_ZOOM_LEVEL = 14;
private static final String GEO_FIRE_DB = "https://trace-
5fa8c.firebaseio.com";
private static final String GEO_FIRE_REF = GEO_FIRE_DB + "/_geofire";
private GoogleMap mMap;
private GoogleMap map;
private Circle searchCircle;
private GeoFire geoFire;
private GeoQuery geoQuery;
private Map<String,Marker> markers;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tracking);
// Obtain the SupportMapFragment and get notified when the map is ready
to be used.
SupportMapFragment mapFragment = (SupportMapFragment)
getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync((OnMapReadyCallback) this);
// setup GeoFire
this.geoFire = new GeoFire(FirebaseDatabase.getInstance().getReferenceFromUrl(GEO_FIRE_REF));
// radius in km
this.geoQuery = this.geoFire.queryAtLocation(INITIAL_CENTER, 1);
// setup markers
this.markers = new HashMap<String, Marker>();
}
#Override
protected void onStop() {
super.onStop();
// remove all event listeners to stop updating in the background
this.geoQuery.removeAllListeners();
for (Marker marker: this.markers.values()) {
marker.remove();
}
this.markers.clear();
}
#Override
protected void onStart() {
super.onStart();
// add an event listener to start updating locations again
this.geoQuery.addGeoQueryEventListener(this);
}
#Override
public void onKeyEntered(String key, GeoLocation location) {
// Add a new marker to the map
Marker marker = this.map.addMarker(new MarkerOptions().position(new
LatLng(location.latitude, location.longitude)));
this.markers.put(key, marker);
}
#Override
public void onKeyExited(String key) {
// Remove any old marker
Marker marker = this.markers.get(key);
if (marker != null) {
marker.remove();
this.markers.remove(key);
}
}
#Override
public void onKeyMoved(String key, GeoLocation location) {
// Move the marker
Marker marker = this.markers.get(key);
if (marker != null) {
this.animateMarkerTo(marker, location.latitude, location.longitude);
}
}
#Override
public void onGeoQueryReady() {
}
#Override
public void onGeoQueryError(DatabaseError error) {
new AlertDialog.Builder(this)
.setTitle("Error")
.setMessage("There was an unexpected error querying GeoFire: " +
error.getMessage())
.setPositiveButton(android.R.string.ok, null)
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
}
// Animation handler for old APIs without animation support
private void animateMarkerTo(final Marker marker, final double lat, final
double lng) {
final Handler handler = new Handler();
final long start = SystemClock.uptimeMillis();
final long DURATION_MS = 3000;
final Interpolator interpolator = new
AccelerateDecelerateInterpolator();
final LatLng startPosition = marker.getPosition();
handler.post(new Runnable() {
#Override
public void run() {
float elapsed = SystemClock.uptimeMillis() - start;
float t = elapsed/DURATION_MS;
float v = interpolator.getInterpolation(t);
double currentLat = (lat - startPosition.latitude) * v +
startPosition.latitude;
double currentLng = (lng - startPosition.longitude) * v +
startPosition.longitude;
marker.setPosition(new LatLng(currentLat, currentLng));
// if animation is not finished yet, repeat
if (t < 1) {
handler.postDelayed(this, 16);
}
}
});
}
private double zoomLevelToRadius(double zoomLevel) {
// Approximation to fit circle into view
return 16384000/Math.pow(2, zoomLevel);
}
#Override
public void onCameraChange(CameraPosition cameraPosition) {
LatLng center = cameraPosition.target;
double radius = zoomLevelToRadius(cameraPosition.zoom);
this.searchCircle.setCenter(center);
this.searchCircle.setRadius(radius);
this.geoQuery.setCenter(new GeoLocation(center.latitude,
center.longitude));
// radius in km
this.geoQuery.setRadius(radius/1000);
}
#Override
public void onMapReady(GoogleMap googleMap) {
LatLng latLngCenter = new LatLng(INITIAL_CENTER.latitude,
INITIAL_CENTER.longitude);
this.searchCircle = this.map.addCircle(new
CircleOptions().center(latLngCenter).radius(1000));
this.searchCircle.setFillColor(Color.argb(66, 255, 0, 255));
this.searchCircle.setStrokeColor(Color.argb(66, 0, 0, 0));
this.map.moveCamera(CameraUpdateFactory.newLatLngZoom(latLngCenter,
INITIAL_ZOOM_LEVEL));
this.map.setOnCameraChangeListener(this);
}
}
I am not able to retrieve any location coordinates (log and lat)
please help
thanks in advance
This question already has answers here:
How can I show current location on a Google Map on Android Marshmallow?
(3 answers)
Closed 5 years ago.
My code create a route between two points on the map in the coordinates I'm trying to get past the coodernada from my current location to the fromPosition, using the low code. But he is giving 0,0 in Log.i;
double lat;
double lng;
LatLng fromPosition = new LatLng(lat, lng);
LatLng toPosition = new LatLng(-5.082434, -42.807364);
But I need the co-penned fromPosition to be my current position.
Thank you for any help.
public class MapsActivity2 extends FragmentActivity {
private GoogleMap map;
double lat;
double lng;
LatLng fromPosition = new LatLng(lat, lng);
LatLng toPosition = new LatLng(-5.082434, -42.807364);
ArrayList<LatLng> directionPoint;
Marker mPositionMarker;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps2);
initializeMap();
Log.i("david", "LATLNG= " + fromPosition);
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
long tempo = 1000; //5 minutos
float distancia = 1; // 30 metros
map.setMyLocationEnabled(true);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER , tempo , distancia, new LocationListener() {
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
}
#Override
public void onProviderEnabled(String arg0) {
Toast.makeText(getApplicationContext(), "GPS Habilitado", Toast.LENGTH_LONG).show();
}
#Override
public void onProviderDisabled(String arg0) {
Toast.makeText(getApplicationContext(), "GPS Desabilitado", Toast.LENGTH_LONG).show();
}
#Override
public void onLocationChanged(Location location) {
if (location == null)
return;
map.setMyLocationEnabled(true);
lat = location.getLatitude();
lng = location.getLongitude();
map.moveCamera(CameraUpdateFactory.newLatLngZoom(new
LatLng(lat, lng), 16));
if (mPositionMarker == null) {
mPositionMarker = map.addMarker(new MarkerOptions()
.flat(true)
.icon(BitmapDescriptorFactory
.fromResource(R.drawable.car))
.anchor(0.5f, 0.5f)
.position(
new LatLng(location.getLatitude(), location
.getLongitude())));
}
animateMarker(mPositionMarker, location); // Helper method for smooth
// animation
map.animateCamera(CameraUpdateFactory.newLatLng(new LatLng(location.getLatitude(), location.getLongitude())));
}
public void animateMarker(final Marker marker, final Location location) {
final Handler handler = new Handler();
final long start = SystemClock.uptimeMillis();
final LatLng startLatLng = marker.getPosition();
final double startRotation = marker.getRotation();
final long duration = 500;
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 * location.getLongitude() + (1 - t)
* startLatLng.longitude;
double lat = t * location.getLatitude() + (1 - t)
* startLatLng.latitude;
float rotation = (float) (t * location.getBearing() + (1 - t)
* startRotation);
marker.setPosition(new LatLng(lat, lng));
marker.setRotation(rotation);
if (t < 1.0) {
// Post again 16ms later.
handler.postDelayed(this, 16);
}
}
});
}
}, null);
}
private void initializeMap() {
if (map == null) {
map = ((SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map)).getMap();
new WebserviceTask(this).execute();
}
}
public void setDirectionPoints(ArrayList<LatLng> result) {
directionPoint = new ArrayList<LatLng>();
directionPoint = result;
}
protected void onResume() {
super.onResume();
initializeMap();
}
public class WebserviceTask extends
AsyncTask<Void, Void, ArrayList<LatLng>> {
MapsActivity2 mContext;
PolylineOptions rectline;
public WebserviceTask(MapsActivity2 context) {
this.mContext = context;
}
#Override
protected void onPostExecute(ArrayList<LatLng> result) {
super.onPostExecute(result);
if (result != null) {
rectline = new PolylineOptions().width(10).color(Color.BLUE);
for (int i = 0; i < result.size(); i++)
rectline.add(result.get(i));
map.addPolyline(rectline);
}
}
#Override
protected ArrayList<LatLng> doInBackground(Void... params) {
GMapV2Direction md = new GMapV2Direction();
Document doc = md.getDocument(fromPosition, toPosition,
GMapV2Direction.MODE_DRIVING);
if (doc != null) {
ArrayList<LatLng> directionPoint = md.getDirection(doc);
rectline = new PolylineOptions().width(10).color(Color.RED);
for (int i = 0; i < directionPoint.size(); i++)
rectline.add(directionPoint.get(i));
return directionPoint;
} else
return null;
}
}
}
/**Implement the code Snipet in your initializeMap() Method***/
private void initializeMap()
{
if (map == null)
{
map = ((SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map)).getMap();
new WebserviceTask(this).execute();
map.moveCamera(CameraUpdateFactory.newLatLngZoom(fromPosition, 10));
map.addMarker(new MarkerOptions()
.title("Marker Location")
.snippet("Marker Location Address")
.position(fromPosition));
map.getUiSettings().setMapToolbarEnabled(true);
}
}
Hello I am trying to update the marker from one position to another in google maps. I want to change the location of the marker with animation just like uber & Ola . Sample code below. I am not getting any error. I am just not seeing the animation. Any simple animation will do.
Code
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
private static int SPLASH_TIME_OUT = 5000;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Add a marker in tilak nagar
LatLng tilkanagar = new LatLng(28.6353, 77.0971);
LatLng Firstmarker = new LatLng(28.6350, 77.0970);
LatLng FirstmarkerTo = new LatLng(28.6356, 77.0972);
LatLng Secondmarker = new LatLng(28.6345, 77.0969);
LatLng SecondmarkerTo = new LatLng(28.6347, 77.0967);
mMap.addMarker(new MarkerOptions().position(tilkanagar).title("Hello I am at Techvision"));
Marker marker = mMap.addMarker(new MarkerOptions().position(Firstmarker).title("1 Minute Away").icon(BitmapDescriptorFactory.fromResource(R.drawable.car)));
Marker marker1 = mMap.addMarker(new MarkerOptions().position(Secondmarker).title("2 Minutes Away").icon(BitmapDescriptorFactory.fromResource(R.drawable.car)));
mMap.moveCamera(CameraUpdateFactory.newLatLng(tilkanagar));
mMap.animateCamera(CameraUpdateFactory.zoomTo(18.0f));
animateMarker(marker, FirstmarkerTo, false);
animateMarker(marker1,SecondmarkerTo,false);
}
public void animateMarker(final Marker marker, final LatLng toPosition,
final boolean hideMarker) {
Thread background = new Thread() {
public void run() {
try {
// Thread will sleep for 5 seconds
sleep(5*1000);
// After 5 seconds redirect to another intent
final Handler handler = new Handler();
final long start = SystemClock.uptimeMillis();
Projection proj = mMap.getProjection();
Point startPoint = proj.toScreenLocation(marker.getPosition());
final LatLng startLatLng = proj.fromScreenLocation(startPoint);
final long duration = 500;
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);
}
}
}
});
//Remove activity
finish();
} catch (Exception e) {
}
}
};
// start thread
background.start();
}
}
Output
You can try setting the animation through marker options. You can use setAnimation()
Or you can use interpolator, an interpolator defines the rate of change of an animation. This allows the basic animation effects (alpha, scale, translate, rotate) to be accelerated, decelerated, repeated, etc.
var marker;
public void animateMarker(final Marker marker, final LatLng toPosition,
final boolean hideMarker) {
final Handler handler = new Handler();
final long start = SystemClock.uptimeMillis();
Projection proj = mGoogleMapObject.getProjection();
Point startPoint = proj.toScreenLocation(marker.getPosition());
final LatLng startLatLng = proj.fromScreenLocation(startPoint);
final long duration = 500;
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);
}
}
}
});
}
Here's a related SO ticket, you can try the work around offered by community: How to animate marker in android map api V2?
I'm developing an Android App for Tablets, which shows two maps with markers in master-detail-layout.
Both maps contain different markers. When I start to move the camera in one of the maps, markers on the other map start to jump/flicker and sometimes even stay in wrong locations.
I was able to reproduce the problem with the google-maps android-samples
by simply adding some markers to two of the maps, nothing more. The flickering is actually far worse than visible in the gif.
gif displaying jumping markers
Here's the whole changed Activity for completeness:
public class MultiMapDemoActivity extends AppCompatActivity {
private static final LatLng BRISBANE = new LatLng(-27.47093, 153.0235);
private static final LatLng MELBOURNE = new LatLng(-37.81319, 144.96298);
private static final LatLng SYDNEY = new LatLng(-33.87365, 151.20689);
private static final LatLng ADELAIDE = new LatLng(-34.92873, 138.59995);
private static final LatLng PERTH = new LatLng(-31.952854, 115.857342);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.multimap_demo);
final SupportMapFragment firstMapFragment =
(SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map1);
firstMapFragment.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap googleMap) {
addMarkers(googleMap, multiplyMarkerPosition(BRISBANE));
addMarkers(googleMap, multiplyMarkerPosition(MELBOURNE));
addMarkers(googleMap, multiplyMarkerPosition(SYDNEY));
addMarkers(googleMap, multiplyMarkerPosition(ADELAIDE));
addMarkers(googleMap, multiplyMarkerPosition(PERTH));
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(ADELAIDE, 4f));
}
});
final SupportMapFragment secondMapFragment =
(SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map2);
secondMapFragment.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap googleMap) {
addMarkersBlue(googleMap, multiplyMarkerPosition(new LatLng(51.51, 0)));
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(51.51, 0), 4f));
}
});
}
public List<LatLng> multiplyMarkerPosition(LatLng position) {
final LinkedList<LatLng> positions = new LinkedList<>();
final double latitude = position.latitude;
final double longitude = position.longitude;
final double delta = 1;
positions.add(new LatLng(latitude, longitude + delta));
positions.add(new LatLng(latitude, longitude - delta));
positions.add(new LatLng(latitude, longitude));
positions.add(new LatLng(latitude - delta, longitude + delta));
positions.add(new LatLng(latitude - delta, longitude - delta));
positions.add(new LatLng(latitude - delta, longitude));
positions.add(new LatLng(latitude + delta, longitude + delta));
positions.add(new LatLng(latitude + delta, longitude - delta));
positions.add(new LatLng(latitude + delta, longitude));
return positions;
}
public void addMarkers(GoogleMap map, List<LatLng> positions) {
for (LatLng latLng : positions) {
map.addMarker(new MarkerOptions().position(latLng));
}
}
public void addMarkersBlue(GoogleMap map, List<LatLng> positions) {
for (LatLng latLng : positions) {
map.addMarker(
new MarkerOptions()
.position(latLng)
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
}
}
}
I couldn't find out whether this is a known bug or an unsupported mode of operation. If you have any ideas or possible workarounds, please let me know. Thanks.