private void getPlaceDetails(String placeName) {
// List<Place.Field> placeFields = Arrays.asList(Place.Field.ID, Place.Field.LAT_LNG);
AutocompleteSessionToken token = AutocompleteSessionToken.newInstance();
FindAutocompletePredictionsRequest request = FindAutocompletePredictionsRequest.builder()
.setCountry("PH") // Set your desired country (optional)
.setSessionToken(token)
.setQuery(placeName)
.build();
placesC.findAutocompletePredictions(request).addOnSuccessListener((response) -> {
if (!response.getAutocompletePredictions().isEmpty()) {
AutocompletePrediction prediction = response.getAutocompletePredictions().get(0);
String placeId = prediction.getPlaceId();
List<Place.Field> placeDetailFields = Arrays.asList(Place.Field.ID, Place.Field.LAT_LNG);
FetchPlaceRequest placeRequest = FetchPlaceRequest.newInstance(placeId, placeDetailFields);
placesC.fetchPlace(placeRequest).addOnSuccessListener((placeResponse) -> {
Place place = placeResponse.getPlace();
destinationLocation = place.getLatLng();
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
}
fusedLocationClient.getLastLocation().addOnSuccessListener(this, new OnSuccessListener<Location>() {
@Override
public void onSuccess(Location location) {
if (location != null) {
LatLng originLocation = new LatLng(location.getLatitude(), location.getLongitude());
getDirections(originLocation, destinationLocation);
Log.d(TAG,"Success");
mMap.addMarker(new MarkerOptions().position(destinationLocation).title(placeName));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(destinationLocation, 16));
}
}
});
}).addOnFailureListener((exception)->{
Log.e("Place Details", "Error getting place details", exception);
});
}
}).addOnFailureListener((exception) -> {
Log.e("Place Details", "Error getting place details", exception);
});
}
private void getDirections(LatLng origin, LatLng destination){
GeoApiContext context = new GeoApiContext.Builder()
.apiKey("key")
.build();
DirectionsApiRequest request = DirectionsApi.getDirections(context,
String.format("%f,%f", origin.latitude, origin.longitude),
String.format("%f,%f", destination.latitude, destination.longitude));
try{
DirectionsResult result = request.await();
drawRouteOnMap(result.routes[0]);
}catch (Exception e){
e.printStackTrace();
}
}
private void drawRouteOnMap(DirectionsRoute route) {
List<LatLng> path = new ArrayList<>();
for (DirectionsLeg leg : route.legs) {
for (DirectionsStep step : leg.steps) {
EncodedPolyline polyline = step.polyline;
List<com.google.maps.model.LatLng> decodedPolyline = polyline.decodePath();
for (com.google.maps.model.LatLng point : decodedPolyline) {
path.add(new LatLng(point.lat, point.lng));
}
}
}
if(currentPolyLine!=null){
currentPolyLine.remove();
}
currentPolyLine = mMap.addPolyline(new PolylineOptions()
.addAll(path)
.color(Color.GREEN)
.width(10));
}
//Check location permission for Maps
private void checkLocationPermission() {
if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Permission not granted, request it
ActivityCompat.requestPermissions(this,
new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
LOCATION_PERMISSION_REQUEST_CODE);
} else {
// Permission already granted, start location updates
startLocationUpdates();
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == LOCATION_PERMISSION_REQUEST_CODE) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
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) {
return;
}
startLocationUpdates();
} else {
// Permission denied
Toast.makeText(getApplicationContext(),"Location Permission Access must be enabled!",Toast.LENGTH_LONG).show();
// You might want to show a message to the user or handle this case differently
}
}
}
private boolean shouldAutoCenterCamera = true;
private void startLocationUpdates() {
fusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
locationCallback = new LocationCallback() {
@Override
public void onLocationResult(LocationResult locationResult) {
if (locationResult != null) {
Location location = locationResult.getLastLocation();
if(location!=null){
Location smoothLocate = smoothLocationUpdate(location);
if(prevLocation==null){
prevLocation=smoothLocate;
}
double latit = smoothLocate.getLatitude();
double longit = smoothLocate.getLongitude();
LatLng userL = new LatLng(latit,longit);
String userId = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("BikersAvailable");
GeoFire geoFire = new GeoFire(ref);
geoFire.setLocation(userId, new GeoLocation(smoothLocate.getLatitude(),smoothLocate.getLongitude()));
if (shouldAutoCenterCamera) {
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(userL,17));
shouldAutoCenterCamera = false;
}
float distance = prevLocation.distanceTo(smoothLocate);
if(distance >=10){
prevLocation=smoothLocate;
if(destinationLocation!=null){
if(currentPolyLine!=null){
Log.d(TAG,"IM REMOVING THE LINE");
currentPolyLine.remove();
}
getDirections(userL,destinationLocation);
}
}
}
}
}
};
LocationRequest locationRequest = new LocationRequest();
locationRequest.setInterval(5000); // Set the desired interval for location updates (in milliseconds)
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
fusedLocationClient.requestLocationUpdates(locationRequest,
locationCallback,
Looper.getMainLooper());
}
}
private Location smoothLocationUpdate(Location newLocation) {
if (prevLocation == null) {
return newLocation;
}
double weight = 0.5; // Adjust this value to control smoothing level
double lat = prevLocation.getLatitude() + weight * (newLocation.getLatitude() - prevLocation.getLatitude());
double lng = prevLocation.getLongitude() + weight * (newLocation.getLongitude() - prevLocation.getLongitude());
Location smoothedLocation = new Location(newLocation);
smoothedLocation.setLatitude(lat);
smoothedLocation.setLongitude(lng);
return smoothedLocation;
}
}
Here is the methods I used for getting directions, locationupdate, drawRoute, smoothlocation, getPlaceDetails. The code for main maps Activity - I'm coding at android studio
I want to implement like Waze application in which if the user use the directions given by the application, as we know the directions it updates or erase the old polyline as the user is like following directions.
i know it seems not organize, im sorry. I'm calling getdirection again in StartLocationUpdates() to update the getdirection every time the user moves.
I have the code on deleting the old polyline if they past 10 meters away something from the prevlocation, if the user past 10meters away something it will remove the old polyline and draw another polyline. But it seems that this code is taking up frames in the main method. Sample Error = Skipped 33 frames! The application may be doing too much work on its main thread. I want it to be smooth as possible on constantly updating the directions as the user use the directions given by the application. I tried AsyncTask, Time interval, handler and runnable in getDirections(). but it seems the method I use provided at the code do the thing I want to show but it is laggy. Can someone help on my code on making it less laggy and creating a smooth direction update or maybe also location update.