draw route line between real time latitude and longitude - android

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.

Related

Polyline behind marker not working on google map

I am new to android development currently trying to build car tracking app. Car marker is on the current location and it will move along with polyline as i move. I have implemented everything but polyline is not drawing behind marker need some suggestions where i am making mistake. Thank you in advance!
public class Map extends FragmentActivity implements OnMapReadyCallback,
GoogleMap.OnInfoWindowClickListener, GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener, LocationListener {
private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 1000;
private static final int REQUEST_LOCATION = 0;
private Location mLastLocation;
// Google client to interact with Google API
private GoogleApiClient mGoogleApiClient;
// boolean flag to toggle periodic location updates
private boolean mRequestingLocationUpdates = false;
private LocationRequest mLocationRequest;
private static final String TAG = "";
private GoogleMap mMap;
private int markerCount;
TextView locationText;
String lat, longi, address1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map17);
locationText = (TextView) findViewById(R.id.locationText);
markerCount = 0;
//Check If Google Services Is Available
if (getServicesAvailable()) {
// Building the GoogleApi client
buildGoogleApiClient();
createLocationRequest();
Toast.makeText(this, "Google Service Is Available!!", Toast.LENGTH_SHORT).show();
}
//Create The MapView Fragment
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
startTrackerService();
}
private void startTrackerService() {
startService(new Intent(this, TrackerService.class));
}
/**
* GOOGLE MAPS AND MAPS OBJECTS
*/
// After Creating the Map Set Initial Location
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission
(this, 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;
}
//Uncomment To Show Google Location Blue Pointer
// mMap.setMyLocationEnabled(true);
}
Marker mk = null;
// Add A Map Pointer To The MAp
public void addMarker(GoogleMap googleMap, double lat, double lon) {
if (markerCount == 1) {
animateMarker(mLastLocation, mk);
} else if (markerCount == 0) {
//Set Custom BitMap for Pointer
int height = 80;
int width = 45;
BitmapDrawable bitmapdraw = (BitmapDrawable) getResources().getDrawable(R.mipmap.icon_car);
Bitmap b = bitmapdraw.getBitmap();
Bitmap smallMarker = Bitmap.createScaledBitmap(b, width, height, false);
mMap = googleMap;
LatLng latlong = new LatLng(lat, lon);
mk = mMap.addMarker(new MarkerOptions().position(new LatLng(lat, lon))
//.icon(BitmapDescriptorFactory.fromResource(R.drawable.pin3))
.icon(BitmapDescriptorFactory.fromBitmap((smallMarker))));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latlong, 16));
//Set Marker Count to 1 after first marker is created
markerCount = 1;
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
return;
}
//mMap.setMyLocationEnabled(true);
startLocationUpdates();
}
}
#Override
public void onInfoWindowClick(Marker marker) {
Toast.makeText(this, marker.getTitle(), Toast.LENGTH_LONG).show();
}
public boolean getServicesAvailable() {
GoogleApiAvailability api = GoogleApiAvailability.getInstance();
int isAvailable = api.isGooglePlayServicesAvailable(this);
if (isAvailable == ConnectionResult.SUCCESS) {
return true;
} else if (api.isUserResolvableError(isAvailable)) {
Dialog dialog = api.getErrorDialog(this, isAvailable, 0);
dialog.show();
} else {
Toast.makeText(this, "Cannot Connect To Play Services", Toast.LENGTH_SHORT).show();
}
return false;
}
/**
* LOCATION LISTENER EVENTS
*/
#Override
protected void onStart() {
super.onStart();
if (mGoogleApiClient != null) {
mGoogleApiClient.connect();
}
// startLocationUpdates();
}
#Override
protected void onResume() {
super.onResume();
getServicesAvailable();
// Resuming the periodic location updates
if (mGoogleApiClient.isConnected() && mRequestingLocationUpdates) {
startLocationUpdates();
}
}
#Override
protected void onStop() {
super.onStop();
if (mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
}
#Override
protected void onPause() {
super.onPause();
}
//Method to display the location on UI
private void displayLocation() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// Check Permissions Now
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
REQUEST_LOCATION);
} else {
mLastLocation = LocationServices.FusedLocationApi
.getLastLocation(mGoogleApiClient);
String location = String.valueOf(mLastLocation);
Log.d("lat:", location);
if (mLastLocation != null) {
double latitude = mLastLocation.getLatitude();
double longitude = mLastLocation.getLongitude();
String loc = "" + latitude + " ," + longitude + " ";
Toast.makeText(this, loc, Toast.LENGTH_SHORT).show();
Constants.lat1 = String.valueOf(latitude);
Constants.lat2 = String.valueOf(longitude);
Log.d("lat:", lat1);
Log.d("lat:", lat2);
//Add pointer to the map at location
addMarker(mMap, latitude, longitude);
try {
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
List<Address> addresses = geocoder.getFromLocation(mLastLocation.getLatitude(), mLastLocation.getLongitude(), 1);
locationText.setText(locationText.getText() + "\n" + addresses.get(0).getAddressLine(0) + ", " +
addresses.get(0).getAddressLine(1) + ", " + addresses.get(0).getAddressLine(2));
address1 = String.valueOf(addresses.get(0).getAddressLine(0) + ", " +
addresses.get(0).getAddressLine(1) + ", " + addresses.get(0).getAddressLine(2));
Constants.address1 = address1;
Log.d("lat:", address1);
/* lat = String.valueOf(mLastLocation.getLatitude());
longi = String.valueOf(mLastLocation.getLongitude());
Log.d("lat:",lat);
Log.d("lat:","true1");
Log.d("longi:", longi);
Log.d("lat:","true2");
Constants.lattitude = lat;
Log.d("lat:",Constants.lattitude);
Log.d("lat:","true3");
Constants.longitude = longi;
Log.d("longi:", Constants.longitude);
Log.d("lat:","true4");
*/
} catch (Exception e) {
}
new ReplyAsync(getApplicationContext(), new ReplyAsync.getReplyAsyncCallback() {
#Override
public void onStart(boolean status) {
Log.e("Result true", "Result true................");
// progressDialog = new ProgressDialog(getApplicationContext());
// progressDialog.setTitle(Constants.company_name);
// progressDialog.setMessage(Constants.loadingMessage);
// progressDialog.show();
}
#Override
public void onResult(boolean result) {
if (result) {
Toast.makeText(Map.this, "Entered Successfully", Toast.LENGTH_SHORT).show();
Log.e("Result true", "Result true");
}
}
}).execute(Constants.latlonginsertlink);
} else {
Toast.makeText(this, "Couldn't get the location. Make sure location is enabled on the device",
Toast.LENGTH_SHORT).show();
}
}
}
// Creating google api client object
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API).build();
}
//Creating location request object
protected void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(AppConstants.UPDATE_INTERVAL);
mLocationRequest.setFastestInterval(AppConstants.FATEST_INTERVAL);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setSmallestDisplacement(AppConstants.DISPLACEMENT);
}
//Starting the location updates
protected void startLocationUpdates() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission
(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// Check Permissions Now
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
REQUEST_LOCATION);
} else {
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, this);
}
}
//Stopping location updates
protected void stopLocationUpdates() {
LocationServices.FusedLocationApi.removeLocationUpdates(
mGoogleApiClient, this);
}
/**
* Google api callback methods
*/
#Override
public void onConnectionFailed(ConnectionResult result) {
Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = "
+ result.getErrorCode());
}
#Override
public void onConnected(Bundle arg0) {
// Once connected with google api, get the location
displayLocation();
if (mRequestingLocationUpdates) {
startLocationUpdates();
}
}
#Override
public void onConnectionSuspended(int arg0) {
mGoogleApiClient.connect();
}
public void onLocationChanged(Location location) {
// Assign the new location
mLastLocation = location;
Toast.makeText(getApplicationContext(), "Location changed!",
Toast.LENGTH_SHORT).show();
// Displaying the new location on UI
displayLocation();
}
public static void animateMarker(final Location destination, final Marker marker) {
if (marker != null) {
final LatLng startPosition = marker.getPosition();
final LatLng endPosition = new LatLng(destination.getLatitude(), destination.getLongitude());
final float startRotation = marker.getRotation();
final LatLngInterpolator latLngInterpolator = new LatLngInterpolator.LinearFixed();
ValueAnimator valueAnimator = ValueAnimator.ofFloat(0, 1);
valueAnimator.setDuration(1000); // duration 1 second
valueAnimator.setInterpolator(new LinearInterpolator());
valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(ValueAnimator animation) {
try {
float v = animation.getAnimatedFraction();
LatLng newPosition = latLngInterpolator.interpolate(v, startPosition, endPosition);
marker.setPosition(newPosition);
marker.setRotation(computeRotation(v, startRotation, destination.getBearing()));
} catch (Exception ex) {
// I don't care atm..
}
}
});
valueAnimator.start();
}
}
private static float computeRotation(float fraction, float start, float end) {
float normalizeEnd = end - start; // rotate start to 0
float normalizedEndAbs = (normalizeEnd + 360) % 360;
float direction = (normalizedEndAbs > 180) ? -1 : 1; // -1 = anticlockwise, 1 = clockwise
float rotation;
if (direction > 0) {
rotation = normalizedEndAbs;
} else {
rotation = normalizedEndAbs - 360;
}
float result = fraction * rotation + start;
return (result + 360) % 360;
}
private interface LatLngInterpolator {
LatLng interpolate(float fraction, LatLng a, LatLng b);
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);
}
}
}
}

I am trying to use Geofire to store location and now I want to display the saved coordinates on a map

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

Location zero in Android Maps API [duplicate]

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);
}
}

I am having trouble making this work

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

Android : Unable to animate marker from one position to another in Google maps

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?

Categories

Resources