Skip to content

Instantly share code, notes, and snippets.

@rogergcc
Created October 21, 2022 12:25
Show Gist options
  • Save rogergcc/39731af5715c3bd91b9cd8de9e89a6da to your computer and use it in GitHub Desktop.
Save rogergcc/39731af5715c3bd91b9cd8de9e89a6da to your computer and use it in GitHub Desktop.
package com.rogergcc.workplaycontacts.ui;
import android.content.Intent;
import android.content.IntentSender;
import android.graphics.BitmapFactory;
import android.location.Location;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import com.google.android.gms.common.api.ResolvableApiException;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.LocationSettingsRequest;
import com.google.android.gms.location.LocationSettingsResponse;
import com.google.android.gms.location.SettingsClient;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.mapbox.android.core.permissions.PermissionsListener;
import com.mapbox.android.core.permissions.PermissionsManager;
import com.mapbox.geojson.Point;
import com.mapbox.mapboxsdk.Mapbox;
import com.mapbox.mapboxsdk.camera.CameraUpdateFactory;
import com.mapbox.mapboxsdk.geometry.LatLng;
import com.mapbox.mapboxsdk.location.LocationComponent;
import com.mapbox.mapboxsdk.location.LocationComponentActivationOptions;
import com.mapbox.mapboxsdk.location.modes.CameraMode;
import com.mapbox.mapboxsdk.location.modes.RenderMode;
import com.mapbox.mapboxsdk.maps.MapboxMap;
import com.mapbox.mapboxsdk.maps.OnMapReadyCallback;
import com.mapbox.mapboxsdk.maps.Style;
import com.mapbox.mapboxsdk.style.layers.Layer;
import com.mapbox.mapboxsdk.style.layers.SymbolLayer;
import com.mapbox.mapboxsdk.style.sources.GeoJsonSource;
import com.rogergcc.workplaycontacts.R;
import com.rogergcc.workplaycontacts.common.CommonAppUtils;
import com.rogergcc.workplaycontacts.databinding.ActivityLocationPickerBinding;
import com.rogergcc.workplaycontacts.helper.GPSUtility;
import java.util.List;
import static com.mapbox.mapboxsdk.style.layers.Property.NONE;
import static com.mapbox.mapboxsdk.style.layers.Property.VISIBLE;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.iconAllowOverlap;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.iconIgnorePlacement;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.iconImage;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.visibility;
public class LocationPickerActivity extends AppCompatActivity implements PermissionsListener, OnMapReadyCallback {
private static final String DROPPED_MARKER_LAYER_ID = "DROPPED_MARKER_LAYER_ID";
private static final LatLng MIDDLE_OF_TCP_COORDINATES = new LatLng(-18.013943322250014, -70.25056307865663);
public static LocationComponent locationComponent;
private MapboxMap mapboxMap;
private PermissionsManager permissionsManager;
private ImageView hoveringMarker;
private Layer droppedMarkerLayer;
private ActivityLocationPickerBinding binding;
private static final int REQUEST_CHECK_SETTINGS = 0x1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Mapbox access token is configured here. This needs to be called either in your application
// object or in the same activity which contains the mapview.
Mapbox.getInstance(this, getString(R.string.access_token));
// This contains the MapView in XML and needs to be called after the access token is configured.
// setContentView(R.layout.activity_location_picker);
binding = ActivityLocationPickerBinding.inflate(getLayoutInflater());
View view = binding.getRoot();
setContentView(view);
// Initialize the mapboxMap view
binding.mapView.onCreate(savedInstanceState);
binding.mapView.getMapAsync(this);
}
@Override
public void onMapReady(@NonNull final MapboxMap mapboxMap) {
LocationPickerActivity.this.mapboxMap = mapboxMap;
// mapboxMap.setStyle(Style.MAPBOX_STREETS, new Style.OnStyleLoaded() {
mapboxMap.setStyle(Style.DARK, new Style.OnStyleLoaded() {
@Override
public void onStyleLoaded(@NonNull final Style style) {
enableLocationPlugin(style);
// Toast instructing user to tap on the mapboxMap
Toast.makeText(
LocationPickerActivity.this,
getString(R.string.move_map_instruction), Toast.LENGTH_SHORT).show();
// When user is still picking a location, we hover a marker above the mapboxMap in the center.
// This is done by using an image view with the default marker found in the SDK. You can
// swap out for your own marker image, just make sure it matches up with the dropped marker.
hoveringMarker = new ImageView(LocationPickerActivity.this);
hoveringMarker.setImageResource(R.drawable.red_marker);
FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.CENTER);
hoveringMarker.setLayoutParams(params);
binding.mapView.addView(hoveringMarker);
// Initialize, but don't show, a SymbolLayer for the marker icon which will represent a selected location.
initDroppedMarker(style);
// Button for user to drop marker or to pick marker back up.
binding.selectLocationButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (hoveringMarker.getVisibility() == View.VISIBLE) {
// Use the map target's coordinates to make a reverse geocoding search
final LatLng mapTargetLatLng = mapboxMap.getCameraPosition().target;
// Hide the hovering red hovering ImageView marker
hoveringMarker.setVisibility(View.INVISIBLE);
// Transform the appearance of the button to become the cancel button
binding.selectLocationButton.setBackgroundColor(
ContextCompat.getColor(LocationPickerActivity.this, R.color.colorDarkDialog));
binding.selectLocationButton.setText(getString(R.string.location_picker_select_location_button_cancel));
// Show the SymbolLayer icon to represent the selected map location
if (style.getLayer(DROPPED_MARKER_LAYER_ID) != null) {
GeoJsonSource source = style.getSourceAs("dropped-marker-source-id");
if (source != null) {
source.setGeoJson(Point.fromLngLat(mapTargetLatLng.getLongitude(), mapTargetLatLng.getLatitude()));
}
droppedMarkerLayer = style.getLayer(DROPPED_MARKER_LAYER_ID);
if (droppedMarkerLayer != null) {
droppedMarkerLayer.setProperties(visibility(VISIBLE));
}
}
// Use the map camera target's coordinates to make a reverse geocoding search
Toast.makeText(LocationPickerActivity.this, "Lat:" + mapTargetLatLng.getLatitude() + "\nLong" + mapTargetLatLng.getLongitude(), Toast.LENGTH_SHORT).show();
Intent resultIntent = new Intent();
resultIntent.putExtra("Lat", mapTargetLatLng.getLatitude() + "");
resultIntent.putExtra("Long", mapTargetLatLng.getLongitude() + "");
setResult(RESULT_OK, resultIntent);
finish();
//reverseGeocode(Point.fromLngLat(mapTargetLatLng.getLongitude(), mapTargetLatLng.getLatitude()));
} else {
// Switch the button appearance back to select a location.
binding.selectLocationButton.setBackgroundColor(
ContextCompat.getColor(LocationPickerActivity.this, R.color.colorDark));
binding.selectLocationButton.setText(getString(R.string.location_picker_select_location_button_select));
// Show the red hovering ImageView marker
hoveringMarker.setVisibility(View.VISIBLE);
// Hide the selected location SymbolLayer
droppedMarkerLayer = style.getLayer(DROPPED_MARKER_LAYER_ID);
if (droppedMarkerLayer != null) {
droppedMarkerLayer.setProperties(visibility(NONE));
}
}
}
});
binding.deviceLocationFab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
LocationRequest locationRequest = LocationRequest.create();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setInterval(10000);
locationRequest.setFastestInterval(10000/2);
LocationSettingsRequest.Builder locationSettingsRequestBuilder = new LocationSettingsRequest.Builder();
locationSettingsRequestBuilder.addLocationRequest(locationRequest);
locationSettingsRequestBuilder.setAlwaysShow(true);
SettingsClient settingsClient = LocationServices.getSettingsClient(LocationPickerActivity.this);
Task<LocationSettingsResponse> task = settingsClient.checkLocationSettings(locationSettingsRequestBuilder.build());
task.addOnSuccessListener(LocationPickerActivity.this, new OnSuccessListener<LocationSettingsResponse>() {
@Override
public void onSuccess(LocationSettingsResponse locationSettingsResponse) {
CommonAppUtils.showLogError("LocationPicker", "Location settings (GPS) is ON.");
}
});
task.addOnFailureListener(LocationPickerActivity.this, new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
// textView.setText("Location settings (GPS) is OFF.");
CommonAppUtils.showLogError("LocationPicker", "Location settings (GPS) is OFF.");
if (e instanceof ResolvableApiException){
try {
ResolvableApiException resolvableApiException = (ResolvableApiException) e;
resolvableApiException.startResolutionForResult(LocationPickerActivity.this,
REQUEST_CHECK_SETTINGS);
} catch (IntentSender.SendIntentException sendIntentException) {
sendIntentException.printStackTrace();
}
}
}
});
GPSUtility gps = new GPSUtility(LocationPickerActivity.this);
Location location = gps.getLocation();
if (location == null) {
CommonAppUtils.showLogError("LocationPicker", "Gps should be activated");
return;
}
mapboxMap.animateCamera(CameraUpdateFactory.newLatLngZoom(
locationComponent != null && locationComponent.getLastKnownLocation() != null ?
new LatLng(locationComponent.getLastKnownLocation()) : MIDDLE_OF_TCP_COORDINATES, 15), 15);
}
});
}
});
}
private void initDroppedMarker(@NonNull Style loadedMapStyle) {
// Add the marker image to map
loadedMapStyle.addImage("dropped-icon-image", BitmapFactory.decodeResource(
getResources(), R.drawable.blue_marker));
loadedMapStyle.addSource(new GeoJsonSource("dropped-marker-source-id"));
loadedMapStyle.addLayer(new SymbolLayer(DROPPED_MARKER_LAYER_ID,
"dropped-marker-source-id").withProperties(
iconImage("dropped-icon-image"),
visibility(NONE),
iconAllowOverlap(true),
iconIgnorePlacement(true)
));
}
@Override
public void onResume() {
super.onResume();
binding.mapView.onResume();
}
@Override
@SuppressWarnings({"MissingPermission"})
protected void onStart() {
super.onStart();
binding.mapView.onStart();
}
@Override
protected void onStop() {
super.onStop();
binding.mapView.onStop();
}
@Override
public void onPause() {
super.onPause();
binding.mapView.onPause();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
binding.mapView.onSaveInstanceState(outState);
}
@Override
protected void onDestroy() {
super.onDestroy();
binding.mapView.onDestroy();
}
@Override
public void onLowMemory() {
super.onLowMemory();
binding.mapView.onLowMemory();
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
permissionsManager.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
@Override
public void onExplanationNeeded(List<String> permissionsToExplain) {
Toast.makeText(this, R.string.user_location_permission_explanation, Toast.LENGTH_LONG).show();
}
@Override
public void onPermissionResult(boolean granted) {
if (granted && mapboxMap != null) {
Style style = mapboxMap.getStyle();
if (style != null) {
enableLocationPlugin(style);
}
} else {
Toast.makeText(this, R.string.user_location_permission_not_granted, Toast.LENGTH_LONG).show();
finish();
}
}
/**
* This method is used to reverse geocode where the user has dropped the marker.
*
* @param //point The location to use for the search
*/
// private void reverseGeocode(final Point point) {
// try {
// MapboxGeocoding client = MapboxGeocoding.builder()
// .accessToken(getString(R.string.access_token))
// .query(Point.fromLngLat(point.longitude(), point.latitude()))
// .geocodingTypes(GeocodingCriteria.TYPE_ADDRESS)
// .build();
//
// client.enqueueCall(new Callback<GeocodingResponse>() {
// @Override
// public void onResponse(Call<GeocodingResponse> call, Response<GeocodingResponse> response) {
//
// if (response.body() != null) {
// List<CarmenFeature> results = response.body().features();
// if (results.size() > 0) {
// CarmenFeature feature = results.get(0);
//
// // If the geocoder returns a result, we take the first in the list and show a Toast with the place name.
// mapboxMap.getStyle(new Style.OnStyleLoaded() {
// @Override
// public void onStyleLoaded(@NonNull Style style) {
// if (style.getLayer(DROPPED_MARKER_LAYER_ID) != null) {
// Toast.makeText(LocationPickerActivity.this,
// String.format(getString(R.string.location_picker_place_name_result),
// feature.placeName()), Toast.LENGTH_SHORT).show();
// }
// }
// });
//
// } else {
// Toast.makeText(LocationPickerActivity.this,
// getString(R.string.location_picker_dropped_marker_snippet_no_results), Toast.LENGTH_SHORT).show();
// }
// }
// }
//
// @Override
// public void onFailure(Call<GeocodingResponse> call, Throwable throwable) {
//// Timber.e("Geocoding Failure: %s", throwable.getMessage());
// }
// });
// } catch (ServicesException servicesException) {
//// Timber.e("Error geocoding: %s", servicesException.toString());
// servicesException.printStackTrace();
// }
// }
@SuppressWarnings({"MissingPermission"})
private void enableLocationPlugin(@NonNull Style loadedMapStyle) {
// Check if permissions are enabled and if not request
if (PermissionsManager.areLocationPermissionsGranted(this)) {
// Get an instance of the component. Adding in LocationComponentOptions is also an optional
// parameter
locationComponent = mapboxMap.getLocationComponent();
locationComponent.activateLocationComponent(LocationComponentActivationOptions.builder(
this, loadedMapStyle).build());
locationComponent.setLocationComponentEnabled(true);
// Set the component's camera mode
locationComponent.setCameraMode(CameraMode.TRACKING);
locationComponent.setRenderMode(RenderMode.NORMAL);
double getLat = 0.0f;
double getLon = 0.0f;
if (locationComponent.getLastKnownLocation() != null) {
getLat = locationComponent.getLastKnownLocation().getLatitude();
getLon = locationComponent.getLastKnownLocation().getLongitude();
}
String preferencesLocation = "[" + getLat + "," + getLon + "]";
// MySharedPreference.getInstance(getApplicationContext()).saveFavoritesMarkers(preferencesLocation);
mapboxMap.animateCamera(CameraUpdateFactory.newLatLngZoom(
new LatLng(Double.parseDouble("-18.006624"), Double.parseDouble("-70.242021"))
, 12), 15);
} else {
permissionsManager = new PermissionsManager(this);
permissionsManager.requestLocationPermissions(this);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment