Google Maps Android permission denied - android

I'm facing google map authentication inconsistency problems whereby when i run my app it connect and works perfectly however when I rerun it again it does not connect and throws permission denied error. This issue persists for a long time and luckily again it resumes connection. I've tried to check my google api key and it appears to be fine since sometimes the app authenticates successfully.
Below is my code:
public class PlacesAutoCompleteActivity extends AppCompatActivity implements
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
View.OnClickListener, OnMapReadyCallback,
LocationListener {
protected GoogleApiClient mGoogleApiClient;
private boolean executeOnStart = false;
LocationRequest mLocationRequest;
private static final LatLngBounds BOUNDS_INDIA = new LatLngBounds(
new LatLng(-0, 0), new LatLng(0, 0));
public GoogleMap mMap;
Location mLastLocation;
Marker mCurrLocationMarker;
private String mapAddress = null;
private ImageView imageView;
private Button checkAvailability;
private StringBuilder sb = null;
private EditText mAutocompleteView;
private Geocoder geocoder;
private MarkerOptions markerOptions;
private LatLng latLng;
private boolean availabilityCheck = false;
private Marker marker;
private RecyclerView mRecyclerView;
private LinearLayoutManager mLinearLayoutManager;
private PlacesAutoCompleteAdapter mAutoCompleteAdapter;
PlacesAutoCompleteAdapter.PlaceAutocomplete item;
String featureName, locality, countryName;
String placeId;
ImageView delete;
SupportMapFragment mapFragment;
private boolean allowEditTextChangeListener = true; // disable google maps autocomplete when user clicks on map to avoid fetching location of chosen place
private LatLng pos;
static boolean invalidLocation = false; // this value confirms whether we are able to deliver to users location
private LinearLayout linearLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
buildGoogleApiClient();
setContentView(R.layout.activity_search);
mAutocompleteView = (EditText) findViewById(R.id.autocomplete_places);
mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(PlacesAutoCompleteActivity.this);
linearLayout = (LinearLayout) findViewById(R.id.linear_layout);
geocoder = new Geocoder(this, Locale.getDefault());
markerOptions = new MarkerOptions();
buildGoogleApiClient();
delete = (ImageView) findViewById(R.id.cross);
mAutoCompleteAdapter = new PlacesAutoCompleteAdapter(this, R.layout.searchview_adapter,
mGoogleApiClient, BOUNDS_INDIA, null);
mRecyclerView = (RecyclerView) findViewById(R.id.recyclerView);
mLinearLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mLinearLayoutManager);
mRecyclerView.setAdapter(mAutoCompleteAdapter);
// mRecyclerView.setLayoutFrozen(true);
delete.setOnClickListener(this);
if (allowEditTextChangeListener) {
Log.d("allowEditTextChangz1",allowEditTextChangeListener + "");
mAutocompleteView.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence s, int start, int before,
int count) {
Log.d("allowEditTextChangz1","jo");
if (!s.toString().equals("") && mGoogleApiClient.isConnected()) {
Log.d("allowEditTextChangzQ",s.toString());
mAutoCompleteAdapter.getFilter().filter(s.toString());
} else if (!mGoogleApiClient.isConnected()) {
checkAvailability.setEnabled(false);
checkAvailability.setAlpha(0.3f);
Toast.makeText(getApplicationContext(), Constants.API_NOT_CONNECTED, Toast.LENGTH_SHORT).show();
Log.e(Constants.PlacesTag, Constants.API_NOT_CONNECTED);
}
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
public void afterTextChanged(Editable s) {
}
});
}
mRecyclerView.addOnItemTouchListener(
new RecyclerItemClickListener(this, new RecyclerItemClickListener.OnItemClickListener() {
#Override
public void onItemClick(View view, int position) {
item = mAutoCompleteAdapter.getItem(position);
placeId = String.valueOf(item.placeId);
PendingResult<PlaceBuffer> placeResult = Places.GeoDataApi
.getPlaceById(mGoogleApiClient, placeId);
placeResult.setResultCallback(new ResultCallback<PlaceBuffer>() {
#Override
public void onResult(PlaceBuffer places) {
if (places.getCount() == 1) {
mAutoCompleteAdapter.clear();
mAutocompleteView.setText("");
String country = "";
try {
List<Address> addresses = geocoder.getFromLocation(places.get(0).getLatLng().latitude,
places.get(0).getLatLng().longitude, 1);
sb = new StringBuilder();
if (addresses.size() > 0) {
android.location.Address address = addresses.get(0);
featureName = address.getFeatureName();
locality = address.getLocality();
countryName = address.getCountryName();
Log.d("featureName ", featureName + "||" +
locality +"||" + countryName);
if (featureName == null) {
mapAddress = address.getLocality() + " " + address.getCountryName();
} else if (locality == null) {
mapAddress = address.getFeatureName() + ", " + address.getCountryName();
} else if (countryName == null) {
mapAddress = address.getFeatureName() + ", " + address.getLocality();
} else {
mapAddress = address.getFeatureName() + ", " + address.getLocality() + " " + address.getCountryName();
country = address.getCountryName();
Log.d("counttryy", "sasa"+country);
}
}
Log.d("mpaddress", "kaka "+mapAddress + "||" + country);
} catch (IOException e) {
e.printStackTrace();
}
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(places.get(0).getLatLng()) // Sets the center of the map to Mountain View
.zoom(12) // Sets the zoom
.bearing(90) // Sets the orientation of the camera to east
.tilt(30) // Sets the tilt of the camera to 30 degrees
.build(); // Creates a CameraPosition from the builder
marker.remove(); // remove any marker from maponclick or maponlonclick
marker = mMap.addMarker(new MarkerOptions().position(places.get(0).getLatLng())
.title("My Location"));
mMap.setTrafficEnabled(true);
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
if (countryName.toLowerCase().equals("kenya")){
availabilityCheck = true;
checkAvailability.setEnabled(true);
confirmPosition();
} else {
}
} else {
Toast.makeText(getApplicationContext(), Constants.SOMETHING_WENT_WRONG, Toast.LENGTH_SHORT).show();
}
}
});
}
})
);
imageView = (ImageView) findViewById(R.id.maps_close);
imageView.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Log.d("close", "close");
if (mAutoCompleteAdapter.getItemCount() != 0){
mAutoCompleteAdapter.clear();
}
mAutocompleteView.setText("");
}
});
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
checkLocationPermission();
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
} else {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
}
#Override
public void onLocationChanged(Location location) {
mLastLocation = location;
if (mCurrLocationMarker != null) {
mCurrLocationMarker.remove();
}
//mMap.getUiSettings().setZoomControlsEnabled(true);
final Double lat = location.getLatitude();
final Double lng = location.getLongitude();
Log.d("LATLANGz", lat + "|" + lng);
latLng = new LatLng(lat, lng);
markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("Current Positionn");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
marker = mMap.addMarker(markerOptions);
//move map camera_main
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(11));
//stop location updates
if (mGoogleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
try {
List<Address> addresses = geocoder.getFromLocation(lat, lng, 1);
sb = new StringBuilder();
if (addresses.size() > 0) {
android.location.Address address = addresses.get(0);
String featureName = address.getFeatureName();
String locality = address.getLocality();
String countryName = address.getCountryName();
System.out.println("featureName " + featureName + "||" + locality +"||" + countryName);
if (featureName == null) {
mapAddress = address.getLocality() + " " + address.getCountryName();
} else if (locality == null) {
mapAddress = address.getFeatureName() + ", " + address.getCountryName();
} else if (countryName == null) {
mapAddress = address.getFeatureName() + ", " + address.getLocality();
} else {
mapAddress = address.getFeatureName() + ", " + address.getLocality() + " " + address.getCountryName();
}
}
System.out.println("mpaddress " + mapAddress + "||" );
mAutocompleteView.setText(mapAddress);
} catch (IOException e) {
e.printStackTrace();
}
mMap.setOnMyLocationButtonClickListener(new GoogleMap.OnMyLocationButtonClickListener(){
#Override
public boolean onMyLocationButtonClick() {
// Toast.makeText(getApplicationContext(), "2> "+mapAddress + lat + lng, Toast.LENGTH_LONG).show();
return false;
}});
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.addApi(Places.GEO_DATA_API)
.build();
mGoogleApiClient.connect();
}
#Override
public void onConnectionSuspended(int i) {
Log.v("Google API Callback", "Connection Suspended");
Log.v("Code", String.valueOf(i));
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.v("Google API Callback","Connection Failed");
Log.v("Error Code", String.valueOf(connectionResult.getErrorCode()));
Toast.makeText(this, Constants.API_NOT_CONNECTED, Toast.LENGTH_SHORT).show();
}
#Override
public void onClick(View v) {
if(v==delete){
mAutocompleteView.setText("");
}
}
#Override
public void onResume() {
super.onResume();
if (!mGoogleApiClient.isConnected() && !mGoogleApiClient.isConnecting()){
Log.v("Google API","Connecting");
mGoogleApiClient.connect();
}
}
#Override
public void onPause() {
super.onPause();
if(mGoogleApiClient.isConnected()){
Log.v("Google API","Dis-Connecting");
mGoogleApiClient.disconnect();
}
}
#Override
public void onBackPressed() {
super.onBackPressed();
}
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
public boolean checkLocationPermission(){
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
Log.d("permission","permission");
// Asking user if explanation is needed
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_FINE_LOCATION)) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
} else {
Log.d("permission2","permission2");
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
}
return false;
} else {
return true;
}
}
#Override
public void onConnected(Bundle bundle) {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(1000);
mLocationRequest.setFastestInterval(1000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
if (mGoogleApiClient.isConnected()){
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_LOCATION: {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
if (mGoogleApiClient == null) {
buildGoogleApiClient();
}
// mMap.setMyLocationEnabled(true);
}
} else {
Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show();
}
return;
}
}
}
#Override
public void onStart(){
super.onStart();
buildGoogleApiClient();
if (isNetworkAvailable() == true){
if (isLocationEnabled(getApplicationContext())){
// Toast.makeText(getApplicationContext(), "enabled", Toast.LENGTH_LONG).show();
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
checkLocationPermission();
}
// 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);
} else{
Display.displaySnackbar(getApplicationContext(), linearLayout, "YOUR GPS IS CURRENTLY DISABLED");
showLocationDialog();
}
} else {
Display.displaySnackbar(getApplicationContext(), linearLayout, "YOU ARE CURRENTLY OFFLINE");
showInternetDialog();
}
}
public void showInternetDialog(){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Please turn on mobile network or Wi-Fi in Settings.")
.setTitle("WIFI Disabled")
.setCancelable(false)
.setPositiveButton("Settings",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent i = new Intent(Settings.ACTION_WIRELESS_SETTINGS);
startActivity(i);
}
}
)
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
PlacesAutoCompleteActivity.this.finish();
}
}
);
AlertDialog alert = builder.create();
alert.show();
}
public boolean isNetworkAvailable() {
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager
.getActiveNetworkInfo();
return activeNetworkInfo != null;
}
public static boolean isLocationEnabled(Context context) {
int locationMode = 0;
String locationProviders;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT){
try {
locationMode = Settings.Secure.getInt(context.getContentResolver(), Settings.Secure.LOCATION_MODE);
} catch (Settings.SettingNotFoundException e) {
e.printStackTrace();
return false;
}
return locationMode != Settings.Secure.LOCATION_MODE_OFF;
}else{
locationProviders = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
return !TextUtils.isEmpty(locationProviders);
}
}
public void showLocationDialog(){
executeOnStart = true;
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(R.string.gps_not_found_message)
.setTitle(R.string.gps_not_found_title)
.setCancelable(false)
.setPositiveButton("Settings",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent i = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(i);
}
}
)
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dg, int id) {
// dialog.dismiss();
// SignIn.dialog.dismiss();
PlacesAutoCompleteActivity.this.finish();
}
}
);
AlertDialog alert = builder.create();
alert.show();
}
}

Related

How to click on marker produced by places API and find the lat/long of that marker and then upload to firebase

I am using the places API to show places as markers on my map, I then want to be able to click on one of markers and save its information to firebase. At the moment when I save it to firebase it saves my current location instead of the markers lat long. pls help :)
mStar is the button that is clicked that once clicked I want to add the location to firebase...
mStar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Toast.makeText(NearbyLocations.this, "Rating......", Toast.LENGTH_SHORT).show();
/*latitude = marker.getPosition().latitude;
longitude = marker.getPosition().longitude;*/
LocationInformation locInfo = new LocationInformation(name, latitude, longitude);
FirebaseUser user = mAuth.getCurrentUser();
String userID = user.getUid();
saveLocations.child(userID).child("Locations").setValue(locInfo)
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Toast.makeText(NearbyLocations.this, "Location saved", Toast.LENGTH_LONG).show();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(NearbyLocations.this, "Error location not saved", Toast.LENGTH_LONG).show();
}
});
}
});
this is the whole class as per requested in the comments.. thank you!!!!!
//imports
public class NearbyLocations extends AppCompatActivity implements
OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {
private GoogleMap mMap;
private GoogleApiClient googleApiClient;
private LocationRequest locationRequest;
private Location lastLocation;
private String name, selPlace;
private double latitude, longitude;
private Marker currentUserLocationMarker;
private static final int Request_User_Location_Code = 99;
private ImageButton mStar, mHeart;
private LatLng selPlaceLatLng;
private String apiKey = "AIzaSyAiXcwMQY9v2ba4GvxLPsF_G-FPUJA5DUU";
private FirebaseAuth mAuth;
private FirebaseDatabase mFirebaseDatabase;
private FirebaseAuth.AuthStateListener mAuthListener;
private DatabaseReference saveLocations;
private int ProximityRadius = 10000;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_nearby_locations);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
checkUserLocationPermission();
}
Places.initialize(getApplicationContext(), apiKey);
// Create a new Places client instance.
PlacesClient placesClient = Places.createClient(this);
mAuth = FirebaseAuth.getInstance();
mFirebaseDatabase = FirebaseDatabase.getInstance();
saveLocations = mFirebaseDatabase.getReference();
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// 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);
mStar = (ImageButton) findViewById(R.id.btnStar);
//mHeart = (ImageButton) findViewById(R.id.btnHeart);
mStar.setVisibility(View.GONE);
//mHeart.setVisibility(View.GONE);
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
//if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION))
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
#Override
public boolean onMarkerClick(Marker marker) {
mStar.setVisibility(View.VISIBLE);
// mHeart.setVisibility(View.VISIBLE);
return false;
}
});
/*AutocompleteSupportFragment autocompleteFragment = (AutocompleteSupportFragment)
getSupportFragmentManager().findFragmentById(R.id.autocomplete_fragment);
autocompleteFragment.setPlaceFields(Arrays.asList(Place.Field.ID, Place.Field.NAME));
autocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {
#Override
public void onPlaceSelected(Place place) {
// TODO: Get info about the selected place.
Log.i(TAG, "Place: " + place.getName() + ", " + place.getId());
}
#Override
public void onError(Status status) {
// TODO: Handle the error.
Log.i(TAG, "An error occurred: " + status);
}
});*/
mStar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Toast.makeText(NearbyLocations.this, "Rating......", Toast.LENGTH_SHORT).show();
/*latitude = marker.getPosition().latitude;
longitude = marker.getPosition().longitude;*/
LocationInformation locInfo = new LocationInformation(name, latitude, longitude);
FirebaseUser user = mAuth.getCurrentUser();
String userID = user.getUid();
saveLocations.child(userID).child("Locations").setValue(locInfo).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Toast.makeText(NearbyLocations.this, "Location saved", Toast.LENGTH_LONG).show();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(NearbyLocations.this, "Error location not saved", Toast.LENGTH_LONG).show();
}
});
}
});
}
public void starClick(Marker marker){
Toast.makeText(NearbyLocations.this, "Rating......", Toast.LENGTH_SHORT).show();
}
/*public void heartClick(Marker marker) {
Toast.makeText(NearbyLocations.this, "savig......", Toast.LENGTH_SHORT).show();
}
/*latitude = marker.getPosition().latitude;
longitude = marker.getPosition().longitude;
LocationInformation locInfo = new LocationInformation(name, latitude, longitude);
FirebaseUser user = mAuth.getCurrentUser();
String userID = user.getUid();
saveLocations.child(userID).child("Locations").setValue(locInfo).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Toast.makeText(NearbyLocations.this, "Location saved", Toast.LENGTH_LONG).show();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(NearbyLocations.this, "Error location not saved", Toast.LENGTH_LONG).show();
}
});*/
/*public void pinClick(){
mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
#Override
public void onMapClick(LatLng latLng) {
mMap.addMarker(new MarkerOptions().position(latLng).title("Clicked Location"));
}
});
}*/
protected synchronized void buildGoogleApiClient() {
googleApiClient = new GoogleApiClient.Builder(this).addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
googleApiClient.connect();
}
public boolean checkUserLocationPermission() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION)) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, Request_User_Location_Code);
} else {
ActivityCompat.requestPermissions(this, new String[]
{Manifest.permission.ACCESS_FINE_LOCATION}, Request_User_Location_Code);
}
return false;
} else {
return true;
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode){
case Request_User_Location_Code:
if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
if(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED){
if (googleApiClient == null ){
buildGoogleApiClient();
}
mMap.setMyLocationEnabled(true);
}
}
else {
Toast.makeText(this, "Permission Denied", Toast.LENGTH_SHORT).show();
}
return;
}
}
#Override
public void onLocationChanged(Location location) {
latitude = location.getLatitude();
longitude = location.getLongitude();
lastLocation = location;
if (currentUserLocationMarker != null){
currentUserLocationMarker.remove();
}
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("user Current Location");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
currentUserLocationMarker = mMap.addMarker(markerOptions);
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomBy(12));
if(googleApiClient != null){
LocationServices.FusedLocationApi.removeLocationUpdates(googleApiClient, this);
}
}
public void onClick(View v)
{
String hotel = "hotel";
String night_club = "night_club";
String restaurant = "restaurant";
Object transferData[] = new Object[2];
GetNearbyPlaces getNearbyPlaces = new GetNearbyPlaces();
//String url = getUrl(latitude, longitude);
switch (v.getId())
{
/*case R.id.search_address:
EditText addressField = (EditText) findViewById(R.id.location_search);
String address = addressField.getText().toString();
List<Address> addressList = null;
MarkerOptions userMarkerOptions = new MarkerOptions();
if (!TextUtils.isEmpty(address))
{
Geocoder geocoder = new Geocoder(this);
try
{
addressList = geocoder.getFromLocationName(address, 6);
if (addressList != null)
{
for (int i=0; i<addressList.size(); i++)
{
Address userAddress = addressList.get(i);
LatLng latLng = new LatLng(userAddress.getLatitude(), userAddress.getLongitude());
userMarkerOptions.position(latLng);
userMarkerOptions.title(address);
userMarkerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ORANGE));
mMap.addMarker(userMarkerOptions);
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(10));
}
}
else
{
Toast.makeText(this, "Location not found...", Toast.LENGTH_SHORT).show();
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
else
{
Toast.makeText(this, "please write any location name...", Toast.LENGTH_SHORT).show();
}
break;*/
case R.id.hotels_nearby:
mMap.clear();
String url = getUrl(latitude, longitude, hotel);
transferData[0] = mMap;
transferData[1] = url;
getNearbyPlaces.execute(transferData);
Toast.makeText(this, "Showing Nearby hotels...", Toast.LENGTH_SHORT).show();
break;
case R.id.clubs_nearby:
mMap.clear();
url = getUrl(latitude, longitude, night_club);
transferData[0] = mMap;
transferData[1] = url;
getNearbyPlaces.execute(transferData);
Toast.makeText(this, "Showing Nearby Night Clubs...", Toast.LENGTH_SHORT).show();
break;
case R.id.restaurants_nearby:
mMap.clear();
url = getUrl(latitude, longitude, restaurant);
transferData[0] = mMap;
transferData[1] = url;
getNearbyPlaces.execute(transferData);
Toast.makeText(this, "Showing Nearby Restaurants...", Toast.LENGTH_SHORT).show();
break;
}
}
private String getUrl(double latitude, double longitude, String nearbyPlace)
{
StringBuilder googleURL = new StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
googleURL.append("location=" + latitude + "," + longitude);
googleURL.append("&radius=" + ProximityRadius);
googleURL.append("&type=" + nearbyPlace);
googleURL.append("&sensor=true");
googleURL.append("&key=" + "AIzaSyAvKd4mDYNodZp-WfsT_AfpyyleH4BrKOI");
Log.d("NearbyLocations", "url = " + googleURL.toString());
return googleURL.toString();
}
#Override
public void onConnected(#Nullable Bundle bundle) {
locationRequest = new LocationRequest();
locationRequest.setInterval(1100);
locationRequest.setFastestInterval(1100);
locationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
if(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, this);
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menuLogout:
FirebaseAuth.getInstance().signOut();
finish();
startActivity(new Intent(this, LoginActivity.class));
break;
case R.id.menuProfile:
Intent intent = new Intent(this, ProfileActivity.class);
this.startActivity(intent);
break;
case R.id.menuAllUsers:
Intent intent1 = new Intent(this, AllUsers.class);
this.startActivity(intent1);
break;
case R.id.accountDetails:
Intent intent3 = new Intent(this, UpdateProfile.class);
this.startActivity(intent3);
break;
case R.id.menuLocation:
Intent intent2 = new Intent(this, MapsActivity.class);
this.startActivity(intent2);
break;
}
return true;
}
}
By looking at your code i found that you are assigning latitude and longitude inside void onLocationChanged(Location location) and that is why you are getting current location while clicking on star.
You should assign latitude and longitude inside onclick of marker as following.
mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
#Override
public boolean onMarkerClick(Marker marker) {
latitude = marker.getPosition().latitude;
longitude = marker.getPosition().longitude;
return true;
}
});
Remove any other assignments and then click on star button,you should get proper location.

Google Maps Nearby Places shows only Toasts

I'm working on a final year project and downloaded this code it was working but now I can't understand why it stops working it shows only Toasts, maybe a problem with API key can you help me please.
public class MapActivity extends FragmentActivity implements OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener,
GoogleMap.OnMarkerClickListener,
GoogleMap.OnMarkerDragListener {
private GoogleMap mMap;
GoogleApiClient mGoogleApiClient;
Location mLastLocation;
Marker mCurrLocationMarker;
LocationRequest mLocationRequest;
int PROXIMITY_RADIUS = 20000;
double latitude, longitude;
double end_latitude, end_longitude;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
checkLocationPermission();
}
//Check if Google Play Services Available or not
if (!CheckGooglePlayServices()) {
Log.d("onCreate", "Finishing test case since Google Play Services are not available");
finish();
}
else {
Log.d("onCreate","Google Play Services available.");
}
// 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 boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater= getMenuInflater();
menuInflater.inflate(R.menu.menu_item_maps, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Object dataTransfer[] = new Object[2];
GetNearbyPlacesData getNearbyPlacesData = new GetNearbyPlacesData();
switch (item.getItemId()){
case R.id.map_menuitemresto:
mMap.clear();
dataTransfer = new Object[2];
String restaurant = "restaurant";
String url = getUrl(latitude, longitude, restaurant);
getNearbyPlacesData = new GetNearbyPlacesData();
dataTransfer[0] = mMap;
dataTransfer[1] = url;
getNearbyPlacesData.execute(dataTransfer);
Toast.makeText(MapActivity.this, "Showing Nearby Restaurants", Toast.LENGTH_LONG).show();
break;
}
return super.onOptionsItemSelected(item);
}
private boolean CheckGooglePlayServices() {
GoogleApiAvailability googleAPI = GoogleApiAvailability.getInstance();
int result = googleAPI.isGooglePlayServicesAvailable(this);
if(result != ConnectionResult.SUCCESS) {
if(googleAPI.isUserResolvableError(result)) {
googleAPI.getErrorDialog(this, result,
0).show();
}
return false;
}
return true;
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
//Initialize Google Play Services
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
} else {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
mMap.setOnMarkerDragListener(this);
mMap.setOnMarkerClickListener(this);
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
}
public void onClick(View v)
{
Object dataTransfer[] = new Object[2];
GetNearbyPlacesData getNearbyPlacesData = new GetNearbyPlacesData();
switch(v.getId()) {
case R.id.B_search: {
EditText tf_location = (EditText) findViewById(R.id.TF_location);
String location = tf_location.getText().toString();
List<Address> addressList = null;
MarkerOptions markerOptions = new MarkerOptions();
Log.d("location = ", location);
if (!location.equals("")) {
Geocoder geocoder = new Geocoder(this);
try {
addressList = geocoder.getFromLocationName(location, 5);
} catch (IOException e) {
e.printStackTrace();
}
if (addressList != null) {
for (int i = 0; i < addressList.size(); i++) {
Address myAddress = addressList.get(i);
LatLng latLng = new LatLng(myAddress.getLatitude(), myAddress.getLongitude());
markerOptions.position(latLng);
mMap.addMarker(markerOptions);
mMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
}
}
}
}
break;
case R.id.B_hotels:
//mMap.clear();
String hospital = "hotel";
String url = getUrl(latitude, longitude, hospital);
dataTransfer[0] = mMap;
dataTransfer[1] = url;
getNearbyPlacesData.execute(dataTransfer);
Toast.makeText(MapActivity.this, "Showing Nearby Hotels", Toast.LENGTH_LONG).show();
break;
case R.id.B_restaurant:
//mMap.clear();
dataTransfer = new Object[2];
String restaurant = "restaurant";
url = getUrl(latitude, longitude, restaurant);
getNearbyPlacesData = new GetNearbyPlacesData();
dataTransfer[0] = mMap;
dataTransfer[1] = url;
getNearbyPlacesData.execute(dataTransfer);
Toast.makeText(MapActivity.this, "Showing Nearby Restaurants", Toast.LENGTH_LONG).show();
break;
case R.id.B_diver:
//mMap.clear();
String school = "hotel";
dataTransfer = new Object[2];
url = getUrl(latitude, longitude, school);
getNearbyPlacesData = new GetNearbyPlacesData();
dataTransfer[0] = mMap;
dataTransfer[1] = url;
getNearbyPlacesData.execute(dataTransfer);
Toast.makeText(MapActivity.this, "Showing Nearby Hotels", Toast.LENGTH_LONG).show();
break;
case R.id.B_to:
dataTransfer = new Object[3];
url = getDirectionsUrl();
GetDirectionsData getDirectionsData = new GetDirectionsData();
dataTransfer[0] = mMap;
dataTransfer[1] = url;
dataTransfer[2] = new LatLng(end_latitude, end_longitude);
getDirectionsData.execute(dataTransfer);
break;
}
}
private String getDirectionsUrl()
{
StringBuilder googleDirectionsUrl = new StringBuilder("https://maps.googleapis.com/maps/api/directions/json?");
googleDirectionsUrl.append("origin="+latitude+","+longitude);
googleDirectionsUrl.append("&destination="+end_latitude+","+end_longitude);
googleDirectionsUrl.append("&key="+"AIzaSyBH5BAD65au_keEdICl_7KFxUzfT8OheVY");
return googleDirectionsUrl.toString();
}
private String getUrl(double latitude, double longitude, String nearbyPlace)
{
StringBuilder googlePlacesUrl = new StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
googlePlacesUrl.append("location=" + latitude + "," + longitude);
googlePlacesUrl.append("&radius=" + PROXIMITY_RADIUS);
googlePlacesUrl.append("&type=" + nearbyPlace);
googlePlacesUrl.append("&sensor=true");
googlePlacesUrl.append("&key=" + "AIzaSyDN7RJFmImYAca96elyZlE5s_fhX-MMuhk");
Log.d("getUrl", googlePlacesUrl.toString());
return (googlePlacesUrl.toString());
}
#Override
public void onConnected(Bundle bundle) {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(1000);
mLocationRequest.setFastestInterval(1000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onLocationChanged(Location location) {
Log.d("onLocationChanged", "entered");
mLastLocation = location;
if (mCurrLocationMarker != null) {
mCurrLocationMarker.remove();
}
latitude = location.getLatitude();
longitude = location.getLongitude();
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.draggable(true);
markerOptions.title("Current Position");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
mCurrLocationMarker = mMap.addMarker(markerOptions);
//move map camera
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(11));
Toast.makeText(MapActivity.this,"Your Current Location", Toast.LENGTH_LONG).show();
//stop location updates
if (mGoogleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
Log.d("onLocationChanged", "Removing Location Updates");
}
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
public boolean checkLocationPermission(){
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Asking user if explanation is needed
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_FINE_LOCATION)) {
// Show an explanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
//Prompt the user once explanation has been shown
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
}
return false;
} else {
return true;
}
}
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_LOCATION: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted. Do the
// contacts-related task you need to do.
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
if (mGoogleApiClient == null) {
buildGoogleApiClient();
}
mMap.setMyLocationEnabled(true);
}
} else {
// Permission denied, Disable the functionality that depends on this permission.
Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show();
}
return;
}
// other 'case' lines to check for other permissions this app might request.
// You can add here other case statements according to your requirement.
}
}
#Override
public boolean onMarkerClick(Marker marker) {
marker.setDraggable(true);
return false;
}
#Override
public void onMarkerDragStart(Marker marker) {
}
#Override
public void onMarkerDrag(Marker marker) {
}
#Override
public void onMarkerDragEnd(Marker marker) {
end_latitude = marker.getPosition().latitude;
end_longitude = marker.getPosition().longitude;
Log.d("end_lat",""+end_latitude);
Log.d("end_lng",""+end_longitude);
}
public void changeTypeMap(View view) {
if (mMap.getMapType() == GoogleMap.MAP_TYPE_NORMAL) {
mMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
} else
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
}
}
I have a button to show nearby places with onClickListener
But this will not filter the places
private static final String TAG = "MapActivity";
private static final int PLACE_PICKER_REQUEST = 1;
YOUR_BUTTON = (Button) findViewById(R.id.YOUR_BUTTON_ID)
YOUR_BUTTON.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
PlacePicker.IntentBuilder builder = new PlacePicker.IntentBuilder();
try {
startActivityForResult(builder.build(MapActivity.this), PLACE_PICKER_REQUEST);
} catch (GooglePlayServicesRepairableException e) {
Log.e(TAG, "onClick: Repairable: " + e.getMessage() );
} catch (GooglePlayServicesNotAvailableException e) {
Log.e(TAG, "onClick: NotAvailable: " + e.getMessage() );
}
}
});

google maps touch listener not working in recyclerview android

I have implemented google maps inside RecyclerView. I'm trying to implement both the Places API functionality and google maps both to be on the same activity. The problem is the Places Api is working fine but the google maps interface is unresponsive. When I try to zoom in the google map or click on it there is no response, it is static.
Below is my code:
public class PlacesAutoCompleteAdapter
extends RecyclerView.Adapter<PlacesAutoCompleteAdapter.PredictionHolder> implements Filterable {
private static final String TAG = "PlacesAutoCompleteAdapter";
private ArrayList<PlaceAutocomplete> mResultList;
private GoogleApiClient mGoogleApiClient;
private LatLngBounds mBounds;
private AutocompleteFilter mPlaceFilter;
private Context mContext;
private int layout;
public PlacesAutoCompleteAdapter(Context context, int resource, GoogleApiClient googleApiClient,
LatLngBounds bounds, AutocompleteFilter filter) {
mContext = context;
layout = resource;
mGoogleApiClient = googleApiClient;
mBounds = bounds;
mPlaceFilter = filter;
}
public void setBounds(LatLngBounds bounds) {
mBounds = bounds;
}
#Override
public Filter getFilter() {
Filter filter = new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
if (constraint != null) {
mResultList = getAutocomplete(constraint);
if (mResultList != null) {
results.values = mResultList;
results.count = mResultList.size();
}
}
return results;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
if (results != null && results.count > 0) {
notifyDataSetChanged();
} else {
}
}
};
return filter;
}
private ArrayList<PlaceAutocomplete> getAutocomplete(CharSequence constraint) {
if (mGoogleApiClient.isConnected()) {
Log.i("", "Starting autocomplete query for: " + constraint);
PendingResult<AutocompletePredictionBuffer> results =
Places.GeoDataApi
.getAutocompletePredictions(mGoogleApiClient, constraint.toString(),
mBounds, mPlaceFilter);
thread. Block and wait for at most 60s
AutocompletePredictionBuffer autocompletePredictions = results
.await(60, TimeUnit.SECONDS);
final Status status = autocompletePredictions.getStatus();
if (!status.isSuccess()) {
Toast.makeText(mContext, "Error contacting API: " + status.toString(),
Toast.LENGTH_SHORT).show();
Log.e("", "Error getting autocomplete prediction API call: " + status.toString());
autocompletePredictions.release();
return null;
}
Log.i("", "Query completed. Received " + autocompletePredictions.getCount()
+ " predictions.");
Iterator<AutocompletePrediction> iterator = autocompletePredictions.iterator();
ArrayList resultList = new ArrayList<>(autocompletePredictions.getCount());
while (iterator.hasNext()) {
AutocompletePrediction prediction = iterator.next();
resultList.add(new PlaceAutocomplete(prediction.getPlaceId(),
prediction.getDescription()));
}
autocompletePredictions.release();
return resultList;
}
Log.e("", "Google API client is not connected for autocomplete query.");
return null;
}
#Override
public PredictionHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
LayoutInflater layoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View convertView = layoutInflater.inflate(layout, viewGroup, false);
PredictionHolder mPredictionHolder = new PredictionHolder(convertView);
return mPredictionHolder;
}
#Override
public void onBindViewHolder(final PredictionHolder mPredictionHolder, final int i) {
}
#Override
public int getItemCount() {
if(mResultList != null)
return mResultList.size();
else
return 0;
}
public PlaceAutocomplete getItem(int position) {
return mResultList.get(position);
}
public class PredictionHolder extends RecyclerView.ViewHolder {
private TextView mPrediction;
private RelativeLayout mRow;
public PredictionHolder(View itemView) {
super(itemView);
mPrediction = (TextView) itemView.findViewById(R.id.address);
mRow=(RelativeLayout)itemView.findViewById(R.id.predictedRow);
}
}
public void clear() {
mResultList.clear();
notifyDataSetChanged();
}
public class PlaceAutocomplete {
public CharSequence placeId;
public CharSequence description;
PlaceAutocomplete(CharSequence placeId, CharSequence description) {
this.placeId = placeId;
this.description = description;
}
#Override
public String toString() {
return description.toString();
}
}
}
public class PlacesAutoCompleteActivity extends AppCompatActivity implements
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
View.OnClickListener, OnMapReadyCallback,
LocationListener {
protected GoogleApiClient mGoogleApiClient;
private boolean executeOnStart = false;
LocationRequest mLocationRequest;
MarkerOptions markerOptions;
private static final LatLngBounds BOUNDS_INDIA = new LatLngBounds(
new LatLng(-0, 0), new LatLng(0, 0));
private GoogleMap mMap;
Location mLastLocation;
Marker mCurrLocationMarker;
private String mapAddress = null;
private StringBuilder sb = null;
private EditText mAutocompleteView;
private Geocoder geocoder;
private RecyclerView mRecyclerView;
private LinearLayoutManager mLinearLayoutManager;
private PlacesAutoCompleteAdapter mAutoCompleteAdapter;
PlacesAutoCompleteAdapter.PlaceAutocomplete item;
String featureName, locality, countryName;
String placeId;
ImageView delete;
private LatLng pos;
static boolean invalidLocation = false; // this value confirms whether we are able to deliver to users location
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
buildGoogleApiClient();
setContentView(R.layout.activity_search);
mAutocompleteView = (EditText) findViewById(R.id.autocomplete_places);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(PlacesAutoCompleteActivity.this);
geocoder = new Geocoder(this, Locale.getDefault());
markerOptions = new MarkerOptions();
buildGoogleApiClient();
delete = (ImageView) findViewById(R.id.cross);
mAutoCompleteAdapter = new PlacesAutoCompleteAdapter(this, R.layout.searchview_adapter,
mGoogleApiClient, BOUNDS_INDIA, null);
mRecyclerView = (RecyclerView) findViewById(R.id.recyclerView);
mLinearLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mLinearLayoutManager);
mRecyclerView.setAdapter(mAutoCompleteAdapter);
delete.setOnClickListener(this);
mAutocompleteView.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence s, int start, int before,
int count) {
if (!s.toString().equals("") && mGoogleApiClient.isConnected()) {
mAutoCompleteAdapter.getFilter().filter(s.toString());
} else if (!mGoogleApiClient.isConnected()) {
Toast.makeText(getApplicationContext(), Constants.API_NOT_CONNECTED, Toast.LENGTH_SHORT).show();
Log.e(Constants.PlacesTag, Constants.API_NOT_CONNECTED);
}
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
public void afterTextChanged(Editable s) {
}
});
mRecyclerView.addOnItemTouchListener(
new RecyclerItemClickListener(this, new RecyclerItemClickListener.OnItemClickListener() {
#Override
public void onItemClick(View view, int position) {
item = mAutoCompleteAdapter.getItem(position);
placeId = String.valueOf(item.placeId);
PendingResult<PlaceBuffer> placeResult = Places.GeoDataApi
.getPlaceById(mGoogleApiClient, placeId);
placeResult.setResultCallback(new ResultCallback<PlaceBuffer>() {
#Override
public void onResult(PlaceBuffer places) {
if (places.getCount() == 1) {
mAutoCompleteAdapter.clear();
mAutocompleteView.setText("");
String country = "";
try {
List<Address> addresses = geocoder.getFromLocation(places.get(0).getLatLng().latitude,
places.get(0).getLatLng().longitude, 1);
sb = new StringBuilder();
if (addresses.size() > 0) {
android.location.Address address = addresses.get(0);
featureName = address.getFeatureName();
locality = address.getLocality();
countryName = address.getCountryName();
Log.d("featureName ", featureName + "||" +
locality +"||" + countryName);
if (featureName == null) {
mapAddress = address.getLocality() + " " + address.getCountryName();
} else if (locality == null) {
mapAddress = address.getFeatureName() + ", " + address.getCountryName();
} else if (countryName == null) {
mapAddress = address.getFeatureName() + ", " + address.getLocality();
} else {
mapAddress = address.getFeatureName() + ", " + address.getLocality() + " " + address.getCountryName();
country = address.getCountryName();
Log.d("counttryy", "sasa"+country);
}
}
Log.d("mpaddress", "kaka "+mapAddress + "||" + country);
} catch (IOException e) {
e.printStackTrace();
}
//Do the things here on Click.....
Toast.makeText(getApplicationContext(), "Hello {}" +countryName+"{}"+featureName+"{}"+"{}"+ String.valueOf(places.get(0).getLatLng()), Toast.LENGTH_SHORT).show();
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(places.get(0).getLatLng()) // Sets the center of the map to Mountain View
.zoom(12) // Sets the zoom
.bearing(90) // Sets the orientation of the camera to east
.tilt(30) // Sets the tilt of the camera to 30 degrees
.build(); // Creates a CameraPosition from the builder
mMap.addMarker(new MarkerOptions().position(places.get(0).getLatLng())
.title("My Location"));
mMap.setTrafficEnabled(true);
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
} else {
Toast.makeText(getApplicationContext(), Constants.SOMETHING_WENT_WRONG, Toast.LENGTH_SHORT).show();
}
}
});
Log.i("TAG", "Clicked: " + item.description);
Log.i("TAG", "Called getPlaceById to get Place details for " + item.placeId);
}
})
);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
checkLocationPermission();
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
Toast.makeText(getApplicationContext(), "YOOOOOO", Toast.LENGTH_SHORT).show();
mMap = googleMap;
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
mMap.getUiSettings().setZoomControlsEnabled(true);
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
} else {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
}
#Override
public void onLocationChanged(Location location) {
mLastLocation = location;
if (mCurrLocationMarker != null) {
mCurrLocationMarker.remove();
}
LatLng latLng = null;
final Double lat = location.getLatitude();
final Double lng = location.getLongitude();
Log.d("LATLANG", lat + "|" + lng);
LatLng latLng2 = new LatLng(lat, lng);
MarkerOptions markerOptions2 = new MarkerOptions();
markerOptions2.position(latLng);
markerOptions2.title("Current Positionn");
markerOptions2.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng2));
mMap.animateCamera(CameraUpdateFactory.zoomTo(11));
if (mGoogleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
try {
List<Address> addresses = geocoder.getFromLocation(lat, lng, 1);
sb = new StringBuilder();
if (addresses.size() > 0) {
android.location.Address address = addresses.get(0);
String featureName = address.getFeatureName();
String locality = address.getLocality();
String countryName = address.getCountryName();
System.out.println("featureName " + featureName + "||" + locality +"||" + countryName);
if (featureName == null) {
mapAddress = address.getLocality() + " " + address.getCountryName();
} else if (locality == null) {
mapAddress = address.getFeatureName() + ", " + address.getCountryName();
} else if (countryName == null) {
mapAddress = address.getFeatureName() + ", " + address.getLocality();
} else {
mapAddress = address.getFeatureName() + ", " + address.getLocality() + " " + address.getCountryName();
}
}
System.out.println("mpaddress " + mapAddress + "||" );
} catch (IOException e) {
e.printStackTrace();
}
mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
#Override
public void onMapClick(LatLng latlng) {
}
});
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.addApi(Places.GEO_DATA_API)
.build();
mGoogleApiClient.connect();
}
#Override
public void onConnectionSuspended(int i) {
Log.v("Google API Callback", "Connection Suspended");
Log.v("Code", String.valueOf(i));
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.v("Google API Callback","Connection Failed");
Log.v("Error Code", String.valueOf(connectionResult.getErrorCode()));
Toast.makeText(this, Constants.API_NOT_CONNECTED, Toast.LENGTH_SHORT).show();
}
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
public boolean checkLocationPermission(){
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
Log.d("permission","permission");
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_FINE_LOCATION)) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
} else {
Log.d("permission2","permission2");
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
}
return false;
} else {
return true;
}
}
#Override
public void onConnected(Bundle bundle) {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(1000);
mLocationRequest.setFastestInterval(1000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
if (mGoogleApiClient.isConnected()){
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
}
}
}

How to update longitude and latitude in every 10 seconds in mysql database?

I'm trying to get latitude and longitude from Android device and send it to MySQL database. when any one register his current latitude and longitude saved in the database.but i want to know that how to update saved latitude and longitude in every 10 seconds.here is my code:
public class MainActivity extends AppCompatActivity implements OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener, GoogleMap.OnCameraMoveListener {
GoogleMap mGoogleMap;
SupportMapFragment mapFrag;
LocationRequest mLocationRequest;
GoogleApiClient mGoogleApiClient;
Location mLastLocation;
Marker mCurrLocationMarker;
double latitude, longitude;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mapFrag = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFrag.getMapAsync(this);
}
#Override
public void onPause() {
super.onPause();
if (mGoogleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
}
#Override
public void onConnected(#Nullable Bundle bundle) {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(1000);
mLocationRequest.setFastestInterval(1000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
#Override
public void onLocationChanged(Location location) {
mLastLocation = location;
if (mCurrLocationMarker != null) {
mCurrLocationMarker.remove();
}
mGoogleMap.clear();
latitude = location.getLatitude();
longitude = location.getLongitude();
LatLng latLng = new LatLng(latitude, longitude);
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("Current Position");
mCurrLocationMarker = mGoogleMap.addMarker(markerOptions);
mCurrLocationMarker.setPosition(latLng);
CameraPosition liberty = CameraPosition.builder().target(new LatLng(latitude, longitude)).zoom(15.5f).bearing(0).tilt(45).build();
mGoogleMap.moveCamera(CameraUpdateFactory.newCameraPosition(liberty));
Intent intent = new Intent(MainActivity.this, Register.class);
intent.putExtra("Latitude", latitude);
intent.putExtra("Longitude", longitude);
startActivity(intent);
callAsynchronousTask();
mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 11));
}
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
private void checkLocationPermission() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_FINE_LOCATION)) {
new AlertDialog.Builder(this)
.setTitle("Location Permission Needed")
.setMessage("This app needs the Location permission, please accept to use location functionality")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
}
})
.create()
.show();
} else {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
}
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
mGoogleMap = googleMap;
mGoogleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
buildGoogleApiClient();
mGoogleMap.setMyLocationEnabled(true);
} else {
checkLocationPermission();
}
} else {
buildGoogleApiClient();
mGoogleMap.setMyLocationEnabled(true);
}
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
}
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_LOCATION: {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
if (mGoogleApiClient == null) {
buildGoogleApiClient();
}
mGoogleMap.setMyLocationEnabled(true);
}
} else {
Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show();
}
return;
}
}
}
#Override
public void onCameraMove() {
mCurrLocationMarker.setPosition(mGoogleMap.getCameraPosition().target);
}
public void callAsynchronousTask() {
final Handler handler = new Handler();
Timer timer = new Timer();
TimerTask doAsynchronousTask = new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
public void run() {
try {
Register performBackgroundTask = new Register();
performBackgroundTask.onSupportContentChanged();
} catch (Exception e) {
// TODO Auto-generated catch block
}
}
});
}
};
timer.schedule(doAsynchronousTask, 0, 50000);
}
}
Register class:-
public class Register extends AppCompatActivity {
EditText name_txt, email_txt, mobile_txt;
String getname, getemail, getmobilenumber;
Button upload, register;
TextView image_text;
TypedFile avatarFile1 = null;
String picturePath = "";
private String userChoosenTask;
private int REQUEST_CAMERA = 0, SELECT_FILE = 1;
File uri;
double getlatitude;
double getlongitude;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
Find_view_by_id();
Bundle extras = getIntent().getExtras();
getlatitude = extras.getDouble("Latitude");
getlongitude = extras.getDouble("Longitude");
Toast.makeText(this, "Your Location is - \nLat: " + getlatitude + "\nLong: " + getlongitude, Toast.LENGTH_SHORT).show();
}
private void Find_view_by_id() {
name_txt = (EditText) findViewById(R.id.name);
email_txt = (EditText) findViewById(R.id.email);
mobile_txt = (EditText) findViewById(R.id.mobilenumber);
upload = (Button) findViewById(R.id.upload_image);
image_text = (TextView) findViewById(R.id.upload_image_text);
register = (Button) findViewById(R.id.register);
upload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectImage();
}
});
register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getname = name_txt.getText().toString();
getemail = email_txt.getText().toString();
getmobilenumber = mobile_txt.getText().toString();
if (getname.trim().equalsIgnoreCase("")) {
name_txt.setError("Please Enter First Name");
name_txt.requestFocus();
} else if (getemail.trim().equalsIgnoreCase("")) {
email_txt.setError("Please Enter email address");
email_txt.requestFocus();
} else if (!getemail.matches("[a-zA-Z0-9._-]+#[a-z]+.[a-z]+")) {
email_txt.setError("Please Enter valid email address");
email_txt.requestFocus();
} else if (getmobilenumber.trim().equalsIgnoreCase("")) {
mobile_txt.setError("Please enter mobile number");
mobile_txt.requestFocus();
} else if (getmobilenumber.length() < 10) {
mobile_txt.setError("Please Enter correct mobile number");
mobile_txt.requestFocus();
} else {
Register_user(getname, getemail, getmobilenumber, picturePath, getlatitude, getlongitude);
}
}
private void Register_user(String name, String email, String mobilenumber, String avatarFile, Double latitud_e, Double longitud_e) {
if (avatarFile != null) {
avatarFile1 = new TypedFile("image/*", new File(String.valueOf(avatarFile)));
}
RestAdapter restAdapter = new RestAdapter.Builder().setEndpoint(Constant.constant).build();
Register_API registerapi = restAdapter.create(Register_API.class);
registerapi.getuser(name, email, mobilenumber, avatarFile1, latitud_e, longitud_e, new Callback<RegisterModel>() {
#Override
public void success(RegisterModel registerModel, Response response) {
Long status = registerModel.getSuccess();
if (status == 1) {
name_txt.setText("");
email_txt.setText("");
mobile_txt.setText("");
image_text.setText("");
Toast.makeText(Register.this, "Successful ", Toast.LENGTH_SHORT).show();
Intent i = new Intent(Register.this, Show_List_Activity.class);
startActivity(i);
}
}
#Override
public void failure(RetrofitError error) {
Toast.makeText(Register.this, "Failure ", Toast.LENGTH_SHORT).show();
}
});
}
});
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case Utility.MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (userChoosenTask.equals("Take Photo"))
cameraIntent();
else if (userChoosenTask.equals("Choose from Library"))
galleryIntent();
} else {
}
break;
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == SELECT_FILE) {
onSelectFromGalleryResult(data);
} else if (requestCode == REQUEST_CAMERA) {
Log.e("log path", "" + uri);
String myImagename = getImageName(String.valueOf(uri));
image_text.setText(myImagename);
}
}
}
private String getImageName(String picturePath) {
String Imagename = null;
String[] name_array = picturePath.split("/");
Log.e("size of array", "" + name_array.length);
Imagename = name_array[name_array.length - 1];
Log.e("name of image", "" + Imagename);
return Imagename;
}
private void selectImage() {
final CharSequence[] items = {"Take Photo", "Choose from Library",
"Cancel"};
AlertDialog.Builder builder = new AlertDialog.Builder(Register.this);
builder.setTitle("Add Photo!");
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
boolean result = Utility.checkPermission(Register.this);
if (items[item].equals("Take Photo")) {
userChoosenTask = "Take Photo";
if (result)
cameraIntent();
} else if (items[item].equals("Choose from Library")) {
userChoosenTask = "Choose from Library";
if (result)
galleryIntent();
} else if (items[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
private void galleryIntent() {
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, SELECT_FILE);
}
private void cameraIntent() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
uri = getOutputMediaFile(MEDIA_TYPE_IMAGE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
startActivityForResult(intent, REQUEST_CAMERA);
}
private static File getOutputMediaFile(int type) {
File mediaStorageDir = new File(Environment.getExternalStorageDirectory() + "/.Dope/");
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
return null;
}
}
File mediaFile;
java.util.Date date = new java.util.Date();
if (type == MEDIA_TYPE_IMAGE) {
mediaFile = new File(mediaStorageDir, Long.toString(System.currentTimeMillis()) + "IMG_" + new Timestamp(date.getTime()).toString() + ".jpg");
} else {
return null;
}
return mediaFile;
}
#SuppressWarnings("deprecation")
private void onSelectFromGalleryResult(Intent data) {
Bitmap bm = null;
if (data != null) {
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
picturePath = cursor.getString(columnIndex);
cursor.close();
String myimagename = getImageName(picturePath);
image_text.setText(myimagename);
}
}
}
You have to use threads for this purpose , with time out of 10 seconds so every 10 seconds your code in thread will run
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
// This method will be executed once the timer is over
// insert your data to db here
// close this activity
finish();
}
}, TIME_OUT);
And set time out as
private static int TIME_OUT = 10000;
Here you go :)
Create a background service class like this
public class LocationBackGroundService extends Service implements LocationListener,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
private static final String TAG = "LocationBackGroundService";
private static final long INTERVAL = 100;
private static final long FASTEST_INTERVAL = 100;
LocationRequest mLocationRequest;
GoogleApiClient mGoogleApiClient;
Location mCurrentLocation;
Context mCOntext;
public void LocationBackGroundService(Context mContext) {
this.mCOntext = mContext;
}
protected void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(INTERVAL);
mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
#Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
mGoogleApiClient.connect();
}
#Override
public void onCreate() {
super.onCreate();
if (!isGooglePlayServicesAvailable()) {
// finish();
}
createLocationRequest();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
if (mGoogleApiClient.isConnected()) {
startLocationUpdates();
}
}
private boolean isGooglePlayServicesAvailable() {
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (ConnectionResult.SUCCESS == status) {
return true;
} else {
return false;
}
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onConnected(Bundle bundle) {
startLocationUpdates();
}
protected void startLocationUpdates() {
PendingResult<Status> pendingResult = LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, this);
Log.d(TAG, "Location update started ..............: ");
}
#Override
public void onConnectionSuspended(int i) {
Toast.makeText(this, "OnConnection Suspended", Toast.LENGTH_SHORT).show();
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Toast.makeText(this, "OnConnection Failed", Toast.LENGTH_SHORT).show();
}
#Override
public void onLocationChanged(Location location) {
if (null != mCurrentLocation) {
mCurrentLocation = location;
String lat = String.valueOf(mCurrentLocation.getLatitude());
String lng = String.valueOf(mCurrentLocation.getLongitude());
}
}
}
And call when activity starts like this
startService(new Intent(this, yourBackgroundServiceName.class));
and in menifest
<service android:name=".yourBackgroundServiceName"></service>
and don;t forget to add run time permissions before stating a service
Instead saving your lat lon to LocalDB you can use Shared Preferences.
For more help about shared Preferences use given link https://www.tutorialspoint.com/android/android_shared_preferences.htm
Make different class and make a method to save your lat lon when ever you get after 10 second.
THanks!

How to calculate accurate distance travelled by the user using google maps?

I am having two doubts because today only i started doing projects on google maps my first doubt is
How to calculate distance traveled by user when using google maps ?
like how taxi app is calculating the distance, now let me explain my problem in depth regarding this question i have checkin and check out button in map when user click the checkin button i will take that exact lat and long of that user when user checkout i will fetch the lat and long from where he checked out, after i will send this source latlong and destination latlong to google api this will return the kilometer. But what i need is wherever he traveled he may traveled extra bit of kilometer i need to calculate that also how can i do that.
My second doubt is my google maps taking long time to plot the blue mark in my map it shows searching for gps in notification bar how can i achieve this ?
Below is my complete Code
VisitTravel.java
public class VisitTravel extends FragmentActivity implements OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {
private List < LatLng > obj;
private GoogleMap mGoogleMap;
private Double latitue, longtitue, Start_lat, Start_long;
private SupportMapFragment mapFrag;
private LocationRequest mLocationRequest;
private GoogleApiClient mGoogleApiClient;
private Location mLastLocation;
private ImageView cancel_bottomsheet;
protected static final int REQUEST_CHECK_SETTINGS = 0x1;
private Bundle bundle;
private ProgressDialog progressDialog;
private String Checkin, parsedDistance, duration, JsonResponse;
private VisitDAO visitDAO;
private Long primaryID;
private ArrayList < LatLng > points;
private Integer id, flag, incidentid, userid;
private TextView heading, duration_textview, dot_source, destination, distance;
private PowerManager.WakeLock wakeLock;
private BottomSheetBehavior bottomSheetBehavior;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_visit_travel);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
mapFrag = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFrag.getMapAsync(this);
InternetCheck internetCheck = new InternetCheck();
boolean check = internetCheck.isNetworkAvailable(VisitTravel.this);
if (!check) {
showAlertDialog();
} else {
createLocationRequest();
buildGoogleApiClient();
Settingsapi();
progressDialog = new ProgressDialog(VisitTravel.this);
// polylineOptions = new PolylineOptions();
cancel_bottomsheet = (ImageView) findViewById(R.id.cancel);
heading = (TextView) findViewById(R.id.heading);
dot_source = (TextView) findViewById(R.id.dot_source);
distance = (TextView) findViewById(R.id.distance);
duration_textview = (TextView) findViewById(R.id.duration);
destination = (TextView) findViewById(R.id.destination);
progressDialog.setMessage("Fetching Location Updates");
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.show();
View bottomSheet = findViewById(R.id.bottom_sheet);
LoginDAO loginobj = new LoginDAO(this);
userid = loginobj.getUserID();
bottomSheetBehavior = BottomSheetBehavior.from(bottomSheet);
bottomSheetBehavior.setState(BottomSheetBehavior.STATE_HIDDEN);
cancel_bottomsheet.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
bottomSheetBehavior.setState(BottomSheetBehavior.STATE_HIDDEN);
}
});
bundle = getIntent().getExtras();
if (bundle != null) {
flag = bundle.getInt("flag");
latitue = bundle.getDouble("destination_lat");
longtitue = bundle.getDouble("destination_long");
incidentid = bundle.getInt("incidentid");
if (flag == 1) {
} else {
// time = bundle.getString("checkin");
id = bundle.getInt("id");
incidentid = bundle.getInt("incidentid");
Start_lat = bundle.getDouble("lat");
Checkin = bundle.getString("checkin");
Start_long = bundle.getDouble("long");
String address = bundle.getString("startaddress");
String distance = bundle.getString("estimateddistance");
setBottomSheet(address, distance);
}
}
obj = new ArrayList < > ();
final FloatingActionButton startfab = (FloatingActionButton) findViewById(R.id.start);
final FloatingActionButton stopfab = (FloatingActionButton) findViewById(R.id.stopfab);
PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
"WakelockTag");
wakeLock.acquire();
visitDAO = new VisitDAO(getApplicationContext());
if (flag == 2) {
startfab.setVisibility(View.INVISIBLE);
}
startfab.setBackgroundResource(R.drawable.ic_play_circle_outline_black_24dp);
final SharedPreferences preferences = getSharedPreferences("lat_long", Context.MODE_PRIVATE);
startfab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (mLastLocation != null) {
String checkin_to_server = dateFormat.format(new Date());
Date date = null;
try {
date = dateFormat.parse(checkin_to_server);
} catch (ParseException e) {
e.printStackTrace();
}
String checkin_view = dateview.format(date);
double startinglat = mLastLocation.getLatitude();
double startinglong = mLastLocation.getLongitude();
// String addres=address(startinglat,startinglong);
String jsonresponse = null;
try {
jsonresponse = new GetDistance().execute(startinglat, startinglong, 12.951601, 80.184641).get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
ParserTask parserTask = new ParserTask();
if (jsonresponse != null) {
Log.d("responsejson", jsonresponse);
parserTask.execute(jsonresponse);
}
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(jsonresponse);
} catch (JSONException e) {
e.printStackTrace();
}
//Here il save the userlocation in db
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Toast.makeText(getApplicationContext(), "Please Wait Till We Recieve Location Updates", Toast.LENGTH_SHORT).show();
}
}
});
stopfab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (mLastLocation != null) {
double lat = mLastLocation.getLatitude();
double longt = mLastLocation.getLongitude();
String startlat = preferences.getString("startlat", "");
Log.d("startlat", startlat);
String startlong = preferences.getString("startlong", "");
// Calculating distance
String distance = getKilometer(Double.valueOf(startlat), Double.valueOf(startlong), lat, longt);
Intent intent = new Intent(VisitTravel.this, IncidentView.class);
setResult(RESULT_OK, intent);
finish();
} else {
Toast.makeText(getApplicationContext(), "Please Wait Fetching Location", Toast.LENGTH_SHORT).show();
}
}
});
}
}
#Override
public void onStart() {
super.onStart();
Log.d("start", "onStart fired ..............");
mGoogleApiClient.connect();
}
private void showAlertDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(VisitTravel.this);
builder.setTitle("Network Connectivity")
.setMessage("Please Check Your Network Connectivity")
.setCancelable(false)
.setNegativeButton("Close", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent intent = new Intent(getApplicationContext(), IncidentView.class);
setResult(RESULT_OK, intent);
finish();
}
});
AlertDialog alert = builder.create();
alert.show();
}
#Override
public void onPause() {
super.onPause();
// progressDialog.dismiss();
if (wakeLock.isHeld()) {
wakeLock.release();
}
//stop location updates when Activity is no longer active
if (mGoogleApiClient.isConnected()) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
mGoogleApiClient.disconnect();
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
mGoogleMap = googleMap;
mGoogleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
map_marker_End(12.951601, 80.184641, "Destination");
if (flag == 2) {
map_marker_start(Start_lat, Start_long, Checkin);
}
//Initialize Google Play Services
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(this,
android.Manifest.permission.ACCESS_FINE_LOCATION) ==
PackageManager.PERMISSION_GRANTED) {
//Location Permission already granted
createLocationRequest();
buildGoogleApiClient();
mGoogleMap.setMyLocationEnabled(true);
} else {
//Request Location Permission
checkLocationPermission();
}
} else {
buildGoogleApiClient();
mGoogleMap.setMyLocationEnabled(true);
}
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
mGoogleApiClient.connect();
}
protected void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(1000 * 10);
mLocationRequest.setFastestInterval(1000 * 5);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
#Override
public void onConnected(Bundle bundle) {
startLocationUpdates();
}
protected void startLocationUpdates() {
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
Toast.makeText(this, "LocationNotUpdated", Toast.LENGTH_SHORT).show();
ActivityCompat.requestPermissions(VisitTravel.this,
new String[] {
android.Manifest.permission
.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION
},
20);
} else {
if (mGoogleApiClient.isConnected()) {
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, this);
Log.d("Loc", "Location update started ..............: ");
// Toast.makeText(this, "LocationUpdatedStart", Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onConnectionSuspended(int i) {}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
public void map_marker_start(Double lat, Double longt, String title) {
MarkerOptions markerOptions = new MarkerOptions();
LatLng latLng = new LatLng(lat, longt);
Log.d("lat", String.valueOf(latLng.longitude));
markerOptions.position(latLng);
markerOptions.title(title);
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
mGoogleMap.addMarker(markerOptions).showInfoWindow();
}
public void map_marker_End(Double lat, Double longt, String title) {
final MarkerOptions markerOptions_end = new MarkerOptions();
LatLng latLng = new LatLng(lat, longt);
Log.d("lat", String.valueOf(latLng.longitude));
markerOptions_end.position(latLng);
markerOptions_end.title(title);
markerOptions_end.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
mGoogleMap.addMarker(markerOptions_end).showInfoWindow();
mGoogleMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
#Override
public boolean onMarkerClick(Marker marker) {
String title = marker.getTitle();
if (title.equals("Destination")) {
dot_source.setText("\u2022");
bottomSheetBehavior.setState(BottomSheetBehavior.STATE_EXPANDED);
heading.setText("TEST");
duration_textview.setText("Duration:" + " " + duration);
return true;
} else {
bottomSheetBehavior.setState(BottomSheetBehavior.STATE_HIDDEN);
return true;
}
}
});
}
#Override
public void onLocationChanged(Location location) {
mLastLocation = location;
PolylineOptions polylineOptions = new PolylineOptions();
Log.d("location", mLastLocation.toString());
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
obj.add(latLng);
polylineOptions.addAll(obj);
polylineOptions.width(9);
polylineOptions.color(Color.parseColor("#2196f3"));
mGoogleMap.addPolyline(polylineOptions);
progressDialog.dismiss();
mGoogleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(
latLng, 12);
mGoogleMap.animateCamera(cameraUpdate);
}
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
private void checkLocationPermission() {
if (ContextCompat.checkSelfPermission(VisitTravel.this, android.Manifest.permission.ACCESS_FINE_LOCATION) !=
PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
android.Manifest.permission.ACCESS_FINE_LOCATION)) {
// Show an explanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
new AlertDialog.Builder(this)
.setTitle("Location Permission Needed")
.setMessage("This app needs the Location permission, please accept to use location functionality")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
//Prompt the user once explanation has been shown
ActivityCompat.requestPermissions(VisitTravel.this,
new String[] {
android.Manifest.permission.ACCESS_FINE_LOCATION
},
MY_PERMISSIONS_REQUEST_LOCATION);
}
})
.create()
.show();
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(this,
new String[] {
android.Manifest.permission.ACCESS_FINE_LOCATION
},
MY_PERMISSIONS_REQUEST_LOCATION);
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_LOCATION:
{
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0 &&
grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted, yay! Do the
// location-related task you need to do.
if (ContextCompat.checkSelfPermission(this,
android.Manifest.permission.ACCESS_FINE_LOCATION) ==
PackageManager.PERMISSION_GRANTED) {
if (mGoogleApiClient == null) {
buildGoogleApiClient();
}
createLocationRequest();
/// buildGoogleApiClient();
// Settingsapi();
mGoogleMap.setMyLocationEnabled(true);
}
} else {
// permission denied, boo! Disable the
// functionality that depends on this permission.
Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show();
}
return;
}
// other 'case' lines to check for other
// permissions this app might request
}
}
public String getKilometer(final double lat1, final double lon1, final double lat2, final double lon2) {
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
try {
URL url = new URL("http://maps.googleapis.com/maps/api/directions/json?origin=" + lat1 + "," + lon1 + "&destination=" + lat2 + "," + lon2 + "&sensor=false&units=metric&mode=driving");
final HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
InputStream in = new BufferedInputStream(conn.getInputStream());
StringBuilder buffer = new StringBuilder();
BufferedReader reader = null;
reader = new BufferedReader(new InputStreamReader( in ));
String inputLine;
while ((inputLine = reader.readLine()) != null)
buffer.append(inputLine + "\n");
if (buffer.length() == 0) {
// Stream was empty. No point in parsing.
Log.e("empty", "empty");
}
JsonResponse = buffer.toString();
Log.d("response", JsonResponse);
JSONObject jsonObject = new JSONObject(JsonResponse);
JSONArray array = jsonObject.getJSONArray("routes");
JSONObject routes = array.getJSONObject(0);
JSONArray legs = routes.getJSONArray("legs");
JSONObject steps = legs.getJSONObject(0);
JSONObject distance = steps.getJSONObject("distance");
parsedDistance = distance.getString("text");
} catch (ProtocolException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
});
thread.start();
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
return parsedDistance;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
// Check for the integer request code originally supplied to startResolutionForResult().
case REQUEST_CHECK_SETTINGS:
switch (resultCode) {
case Activity.RESULT_OK:
startLocationUpdates();
break;
case Activity.RESULT_CANCELED:
Intent intent = new Intent(this, Incident.class);
startActivity(intent);
break;
}
break;
}
}
#Override
protected void onStop() {
super.onStop();
if (wakeLock.isHeld()) {
wakeLock.release();
}
}
#Override
public void onBackPressed() {
super.onBackPressed();
Intent intent = new Intent(this, IncidentView.class);
if (mGoogleApiClient.isConnected()) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
mGoogleApiClient.disconnect();
}
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
setResult(RESULT_OK, intent);
finish();
}
}
Searched alot and not getting proper way to start with? Any help would really valuable.
--Thanks!
This worked for me:
Capture the latitude and longitude at regular intervals and store. Calculate and sum the distance between each stored value.

Categories

Resources