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

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.

Related

without turn on location not showing current location in android

Hi in the below code am setting current location to my application.If it is turn on the location by manually it was showing current location.
If am not turn it on it was showing nothing in my map.
But i want to display the permission to turn on location and have written the code but it is not working .
can any one please help to resolve this issue.
MapsActivity.java:
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {
private static final int LOCATION_REQUESTOR = 101;
#Bind(R.id.back)
TextView mBack;
#Bind(R.id.location)
TextView mLocation;
#Bind(R.id.toolBar)
Toolbar mToolBar;
#Bind(R.id.map_address)
TextView mMapAddress;
#Bind(R.id.latitude)
EditText mLatitude;
#Bind(R.id.longitude)
EditText mLongitude;
#Bind(R.id.setLocation)
Button mSetLocation;
private Location mLastLocation;
private GoogleMap mMap;
Marker mCurrLocationMarker;
private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;
private SharedPreferences mPref;
private SolarBLEPacket mSolarController = new SolarBLEPacket();
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
ButterKnife.bind(this);
mPref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
final SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
}
#Override
public void onConnected(#Nullable 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 onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
#Override
public void onLocationChanged(Location location) {
mLastLocation = location;
if (mCurrLocationMarker != null) {
mCurrLocationMarker.remove();
}
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("Current Position");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
mCurrLocationMarker = mMap.addMarker(markerOptions);
//move map camera
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng,11));
mLongitude.setText(latLng.longitude + "");
mLatitude.setText(latLng.latitude + "");
}
#Override
public void onMapReady(GoogleMap googleMap)
{
mMap=googleMap;
mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
//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) {
//Location Permission already granted
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
} else {
//Request Location Permission
checkLocationPermission();
}
}
else {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
}
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
public boolean checkLocationPermission() {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
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.
new AlertDialog.Builder(this)
.setTitle(R.string.title_location_permission)
.setMessage(R.string.text_location_permission)
.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
//Prompt the user once explanation has been shown
ActivityCompat.requestPermissions(MapsActivity.this,
new String[]{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[]{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, yay! Do the
// location-related task you need to do.
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
//Request location updates:
//.requestLocationUpdates(provider, 400, 1, this);
}
} else {
// permission denied, boo! Disable the
// functionality that depends on this permission.
}
return;
}
}
}
#OnClick(R.id.setLocation)
public void onClick() {
Intent intent = new Intent();
String longtitude = mLongitude.getText().toString();
if (!TextUtils.isEmpty(longtitude)) {
intent.putExtra(Constants.LONGITUDE, longtitude);
} else {
Toast.makeText(this, R.string.please_enter_longitude, Toast.LENGTH_SHORT).show();
return;
}
String latitude = mLatitude.getText().toString();
if (!TextUtils.isEmpty(latitude)) {
intent.putExtra(Constants.LATITUDE, latitude);
} else {
Toast.makeText(this, R.string.please_enter_latitude, Toast.LENGTH_SHORT).show();
return;
}
String latCommand = mSolarController.generatePacket("lat " +latitude,"00");
String longitudeCmd = mSolarController.generatePacket("lon "+longtitude,"00");
mPref.edit().putString(Constants.LAT_COMMAND,latCommand).commit();
mPref.edit().putString(Constants.LONG_COMMAND,longitudeCmd).commit();
mPref.edit().putString(Constants.LAST_LATITUDE,latitude).commit();
mPref.edit().putString(Constants.LAST_LONGITUDE,latitude).commit();
setResult(RESULT_OK, intent);
finish();
}
#OnClick({R.id.back, R.id.location})
public void onClick(View view) {
switch (view.getId()) {
case R.id.back:
setResult(RESULT_OK, new Intent());
finish();
break;
case R.id.location:
Intent intent = new Intent();
String longtitude = mLongitude.getText().toString();
if (!TextUtils.isEmpty(longtitude)) {
intent.putExtra(Constants.LONGITUDE, longtitude);
} else {
Toast.makeText(this, R.string.please_enter_longitude, Toast.LENGTH_SHORT).show();
return;
}
String latitude = mLatitude.getText().toString();
if (!TextUtils.isEmpty(latitude)) {
intent.putExtra(Constants.LATITUDE, latitude);
} else {
Toast.makeText(this, R.string.please_enter_latitude, Toast.LENGTH_SHORT).show();
return;
}
Float lat = Float.parseFloat(latitude);
if (lat > 90 || lat < -90) {
Toast.makeText(this, R.string.longitude_alert, Toast.LENGTH_SHORT).show();
return;
}
float lan = Float.parseFloat(longtitude);
if (lan > 180 || lan < -180) {
Toast.makeText(this, R.string.latitude_alert, Toast.LENGTH_SHORT).show();
return;
}
String latCommand = mSolarController.generatePacket("lat "+latitude,"00");
String longitudeCmd = mSolarController.generatePacket("long "+longtitude,"00");
mPref.edit().putString(Constants.LAT_COMMAND,latCommand).commit();
mPref.edit().putString(Constants.LONG_COMMAND,longitudeCmd).commit();
mPref.edit().putString(Constants.LAST_LATITUDE,latitude).commit();
mPref.edit().putString(Constants.LAST_LONGITUDE,latitude).commit();
setResult(RESULT_OK, intent);
finish();
break;
}
}
}
You are just checking the permission, You need to check whether is location is enable of the device or not.
LocationManager lm = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
boolean gps_enabled = false;
boolean network_enabled = false;
try {
gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch(Exception ex) {}
try {
network_enabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch(Exception ex) {}
if(!gps_enabled && !network_enabled) {
// notify user
AlertDialog.Builder dialog = new AlertDialog.Builder(context);
dialog.setMessage(context.getResources().getString(R.string.gps_network_not_enabled));
dialog.setPositiveButton(context.getResources().getString(R.string.open_location_settings), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
// TODO Auto-generated method stub
Intent myIntent = new Intent( Settings.ACTION_LOCATION_SOURCE_SETTINGS);
context.startActivity(myIntent);
//get gps
}
});
dialog.setNegativeButton(context.getString(R.string.Cancel), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
// TODO Auto-generated method stub
}
});
dialog.show();
}

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 Android permission denied

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

I want to show Multiple Markers at runtime on the screen which have different id's that received from the server

I want to show Multiple Markers at runtime on the screen which have different id's that received from the server and longitude and latitude also change or save on server.
** Code work fine in 1 to 1 tracking but not work on multiple Id's PLEASE HELP ME..**
public class MainActivity extends AppCompatActivity
implements GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
static final LatLng HAMBURG1 = new LatLng(74.3226214, 31.5003567);
static final LatLng HAMBURG = new LatLng(74.3229122, 31.5003193);
private static MainActivity instance;
private static final int ERROR_DIALOG_REQUEST = 9001;
GoogleMap mMap;
int i = 0;
protected static String longitudeServer;
protected static String latitudeServer;
protected static String uniqueidSserver;
protected static String latitudeLast;
protected static String logitudeLast;
protected static String uniqueidlast;
protected static double latilasdoublet;
protected static double longilastdouble;
double latitude = 0;
double longitude = 0;
private GoogleApiClient mLocationClient;
private com.google.android.gms.location.LocationListener mListener;
private Marker marker;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (servicesOK()) {
setContentView(R.layout.activity_map);
if (initMap()) {
// gotoLocation(SEATTLE_LAT, SEATTLE_LNG, 15);
mLocationClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
mLocationClient.connect();
mMap.setMyLocationEnabled(true);
} else {
Toast.makeText(this, "Map not connected!", Toast.LENGTH_SHORT).show();
}
} else {
setContentView(R.layout.activity_main);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
//Add menu handling code
switch (id) {
case R.id.mapTypeNone:
mMap.setMapType(GoogleMap.MAP_TYPE_NONE);
break;
case R.id.mapTypeNormal:
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
break;
case R.id.mapTypeSatellite:
mMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
break;
case R.id.mapTypeTerrain:
mMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
break;
case R.id.mapTypeHybrid:
mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
break;
}
return super.onOptionsItemSelected(item);
}
public boolean servicesOK() {
int isAvailable = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (isAvailable == ConnectionResult.SUCCESS) {
return true;
} else if (GooglePlayServicesUtil.isUserRecoverableError(isAvailable)) {
Dialog dialog =
GooglePlayServicesUtil.getErrorDialog(isAvailable, this, ERROR_DIALOG_REQUEST);
dialog.show();
} else {
Toast.makeText(this, "Can't connect to mapping service", Toast.LENGTH_SHORT).show();
}
return false;
}
private boolean initMap() {
if (mMap == null && i == 0) {
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mMap = mapFragment.getMap();
mMap.setMyLocationEnabled(true);
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
}
return (mMap != null);
}
private void gotoLocation(double lat, double lng, float zoom) {
LatLng latLng = new LatLng(lat, lng);
CameraUpdate update = CameraUpdateFactory.newLatLngZoom(latLng, zoom);
mMap.moveCamera(update);
}
public void showCurrentLocation(MenuItem item) {
Location currentLocation = LocationServices.FusedLocationApi
.getLastLocation(mLocationClient);
if (currentLocation == null) {
Toast.makeText(this, "Couldn't connect!", Toast.LENGTH_SHORT).show();
} else {
LatLng latLng = new LatLng(
currentLocation.getLatitude(),
currentLocation.getLongitude()
);
CameraUpdate update = CameraUpdateFactory.newLatLngZoom(
latLng, 10
);
mMap.animateCamera(update);
}
}
#Override
public void onConnected(Bundle bundle) {
Toast.makeText(this, "Ready to map!", Toast.LENGTH_SHORT).show();
mListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
latitude = location.getLatitude();
longitude = location.getLongitude();
LatLng latLng = new LatLng(latitude, longitude);
// mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
Toast.makeText(MainActivity.this, "Location : " + location.getLatitude() + ", " + location.getLongitude(), Toast.LENGTH_LONG).show();
if (i == 0) {
gotoLocation(location.getLatitude(), location.getLongitude(), 15);
i = 1;
}
AppUtill.UniqueId();
if (AppStatus.getInstance(getContext()).isOnline()) {
new JSONAsyncTask().execute("http://ip/hajjapi/api/GPSLocator/GetLocations");
} else {
Toast.makeText(MainActivity.this, "Turn On your WIFI ", Toast.LENGTH_LONG).show();
}
///HOW I CAN DISPLAY MULTIPLE MARKERS WHICH HAVE DIFFERENT ID'S RECEIVED FROM THE SERVER PLEASE HELP ME PLEASE...
if (marker != null) {
marker.remove();
}
MarkerOptions options = new MarkerOptions().title("User Name").position(new LatLng(latilasdoublet, longilastdouble)).icon(BitmapDescriptorFactory.fromResource(R.drawable.female4));
marker = mMap.addMarker(options);
}
};
LocationRequest request = LocationRequest.create();
request.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
request.setInterval(5000);
request.setFastestInterval(5000);
LocationServices.FusedLocationApi.requestLocationUpdates(mLocationClient, request, mListener);
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
public void showcurrentLocation() {
mMap.animateCamera(CameraUpdateFactory.zoomTo(15));
i = 1;
}
class JSONAsyncTask extends AsyncTask<String, Void, Boolean> {
ProgressDialog dialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Boolean doInBackground(String... urls) {
try {
//------------------>>
HttpGet httpGet = new HttpGet(urls[0]);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httpGet);
int status = response.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONArray jsonarray = new JSONArray(data);
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject obj = jsonarray.getJSONObject(i);
longitudeServer = obj.getString("longi");
latitudeServer = obj.getString("lati");
uniqueidSserver = obj.getString("uniqueid");
}
////LAST LONGITUDE AND LATITUDE THAT RECEIVED FROM SERVER
List<String> longitude = Arrays.asList(longitudeServer);
logitudeLast = longitude.get(longitude.size() - 1);
System.out.println(logitudeLast + " logitude ");
List<String> latitude = Arrays.asList(latitudeServer);
latitudeLast = latitude.get(latitude.size() - 1);
System.out.println(latitudeLast + " latitude ");
List<String> uniqueid = Arrays.asList(uniqueidSserver);
uniqueidlast = uniqueid.get(uniqueid.size() - 1);
System.out.println(uniqueidlast + " unique id ");
latilasdoublet = Double.parseDouble(latitudeLast);
longilastdouble = Double.parseDouble(logitudeLast);
return true;
}
//------------------>>
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
protected void onPostExecute(Boolean result) {
if (result == false)
Toast.makeText(getApplicationContext(), "Unable to fetch data from server", Toast.LENGTH_LONG).show();
}
}
#Override
protected void onStop() {
super.onStop();
startService(new Intent(getContext(), Services.class));
}
public MainActivity() {
instance = this;
}
public static Context getContext() {
return instance;
}
}
you are using only two double variables for lat and lng. create an arrayList of LatLng objects. for all the urls you get in response, add the LatLng to the arrayList.
add a field
private ArrayList<LatLng> latLngList;
initialize in oncreate function
latLngList = new ArrayList<>();
instead of
latilasdoublet = Double.parseDouble(latitudeLast);
longilastdouble = Double.parseDouble(logitudeLast);
add
for(int i=0; i< latitude.size(); i++){
LatLng latLng = new LatLng(Double.parseDouble(latitude.get(i)), Double.parseDouble(longitude.get(i)));
latLngList.add(latLng);
}
in place of
MarkerOptions options = new MarkerOptions().title("User Name").position(new LatLng(latilasdoublet, longilastdouble)).icon(BitmapDescriptorFactory.fromResource(R.drawable.female4));
marker = mMap.addMarker(options);
use
ArrayList<MarkerOptions> list = new ArrayList<>();
for (LatLng object : latLngList){
MarkerOptions options = new MarkerOptions().title("User Name").position(object).icon(BitmapDescriptorFactory.fromResource(R.drawable.female4));
mMap.addMarker(options);
list.add(options); //if you want to keep track of all your markers
}
use mMap.clear() to clear all markers and clustering refer
More info on markers.

LocationListener and memory leaks

According to the sample app that finds the user location it is a good idea to listen for location changes in the activity:
class MyActivity extends Activity implements LocationListener {
#Inject
private LocationManager locationManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
}
#Override
public void onLocationChanged(Location location) {
// do something with location
}
// ...
}
However, I'm not sure about that. When there is a configuration change, my activity gets destroyed and recreated, registering itself as listener next time. The reference to the old Activity is held in the LocationManager, isn't it?
If I extract the LocationListener to separate object, still I have the problem of how to notify the current activity about new location (not necessarily the same as the requesting activity).
Is there any common pattern to solve this?
In this example you have also another problem: your GPS listener will work always and will drain battery.
The better practice is:
1) register LocationListener into Activity's onStart()
2) remove LocationListener into Activity's onStop()
This will fix both problems.
If you need that your app track user position in background (for example, GPS tracker) use Service (http://developer.android.com/reference/android/app/Service.html)
I had memory leaks using all these suggestions. I got them to stop by applying this method at the point I didn't need the Listener anymore, to onDestroy, and onStop. I also added it to onPause, but you'll have to decide if this is best for your application.
private void stopLocationListener() {
if (locationManager !=null) locationManager.removeUpdates(locationListener);
if (locationManager !=null) locationManager =null;
if (locationListener !=null) locationListener =null;
}
You can make a separate class to do the same and then implement the LocationListenerFinder.onLocationChanged interface to your activity
Now you won't face the leak problem.
public class LocationListenerFinder implements LocationListener {
onLocationChanged onLocationChanged;
public LocationListenerFinder(Context context) {
onLocationChanged = (LocationListenerFinder.onLocationChanged) context;
}
#Override
public void onLocationChanged(Location location) {
onLocationChanged.onLocationChanged(location);
onLocationChanged = null;
}
public interface onLocationChanged {
void onLocationChanged(Location location);
}
}
In my case activity was this... you can refer the same and can convert as per your need.
public class ActivityMapNearByPlace extends FragmentActivity implements OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener, LocationListenerFinder.onLocationChanged {
private GoogleMap mMap;
ArrayList<LatLng> listMarkerPoints;
GoogleApiClient mGoogleApiClient;
Location mLastLocation;
Marker mCurrLocationMarker;
LocationRequest mLocationRequest;
private boolean locationPermission;
private ArrayList<NearByPlaces> listNearByFacility;
private int facilityPosition, locationPosition;
private ImageView ivBack, ivMyLocation;
private TextView tvPlaceOriginName, tvPlaceDestinationName, tvPlaceKmDistance, tvPlaceTime;
private TableRow trPlaceTimeKm;
private Marker currentSelectedMarker;
private Map<Integer, Map<String, Object>> mapDistancePathData;
private Polyline polyline;
private boolean flagCalculatingPath = false;
private FetchUrl fetchUrl;
private SupportMapFragment mapFragment;
private LocationListenerFinder locationListenerFinder;
//private WeakLocationListener locationListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map_near_by_place);
initView();
initListener();
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
checkLocationPermission();
} else {
locationPermission = true;
}
// Initializing
listMarkerPoints = new ArrayList<>();
getBundleData();
listNearByFacility.get(0).getNearBy();
LatLng origin = new LatLng(Double.valueOf(listNearByFacility.get(0).getGeoLocLat()), Double.valueOf(listNearByFacility.get(0).getGeoLocLong()));
listMarkerPoints.add(origin);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
#Override
protected void onRestart() {
super.onRestart();
//if (mGoogleApiClient != null) mGoogleApiClient.connect();
}
#Override
protected void onStop() {
super.onStop();
//if (mGoogleApiClient != null) mGoogleApiClient.disconnect();
}
#Override
protected void onDestroy() {
super.onDestroy();
if (mGoogleApiClient != null && mGoogleApiClient.isConnected()) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, locationListenerFinder);
mGoogleApiClient.disconnect();
mGoogleApiClient.unregisterConnectionCallbacks(this);
mGoogleApiClient.unregisterConnectionFailedListener(this);
// locationListener.clearData();
locationListenerFinder = null;
}
mGoogleApiClient = null;
fetchUrl.cancel(true);
if (mMap != null) mMap.setMyLocationEnabled(false);
//if (mapFragment != null) mapFragment.onDestroy();
}
#Override
public void onBackPressed() {
finish();
}
private void initListener() {
ivBack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onBackPressed();
}
});
ivMyLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (mCurrLocationMarker.getTag() != null && !flagCalculatingPath) {
locationPosition = (int) mCurrLocationMarker.getTag();
if (mapDistancePathData.get(locationPosition) != null) {
if (polyline != null) {
polyline.remove();
}
Map<String, Object> hashMapDistancePathInfo = mapDistancePathData.get(locationPosition);
setPathInfo((String) hashMapDistancePathInfo.get("duration"), (String) hashMapDistancePathInfo.get("distance"), (PolylineOptions) hashMapDistancePathInfo.get("polyLineOptions"), "Current Location");
trPlaceTimeKm.setVisibility(View.VISIBLE);
} else {
Locations locations = new Locations();
locations.setName("Current Location");
locations.setLatitude(String.valueOf(mLastLocation.getLatitude()));
locations.setLongitude(String.valueOf(mLastLocation.getLongitude()));
findDistanceAndMarkDirection(locations);
}
}
//mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
//mMap.animateCamera(CameraUpdateFactory.zoomTo(11));
}
});
}
private void initView() {
ivBack = (ImageView) findViewById(R.id.iv_back_btn);
ivMyLocation = (ImageView) findViewById(R.id.iv_my_location);
tvPlaceOriginName = (TextView) findViewById(R.id.tv_near_by_place_origin);
tvPlaceDestinationName = (TextView) findViewById(R.id.tv_near_by_place_destination);
tvPlaceKmDistance = (TextView) findViewById(R.id.tv_near_by_place_km);
tvPlaceTime = (TextView) findViewById(R.id.tv_near_by_place_time);
trPlaceTimeKm = (TableRow) findViewById(R.id.tr_near_by_place_km_time);
}
private void getBundleData() {
listNearByFacility = (ArrayList<NearByPlaces>) getIntent().getBundleExtra("nearByLocationBundle").getSerializable("nearByLocationData");
facilityPosition = getIntent().getIntExtra("facilityPosition", 0);
locationPosition = getIntent().getIntExtra("locationPosition", 0);
}
/**
* 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 (locationPermission) {
buildGoogleApiClient();
checkLocationStatus();
//mMap.setMyLocationEnabled(true);
loadMap();
}
mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
#Override
public boolean onMarkerClick(Marker marker) {
if (marker.getTag() != null && !flagCalculatingPath) {
locationPosition = (int) marker.getTag();
if (mapDistancePathData.get(locationPosition) != null) {
if (polyline != null) {
polyline.remove();
}
Map<String, Object> hashMapDistancePathInfo = mapDistancePathData.get(locationPosition);
setPathInfo((String) hashMapDistancePathInfo.get("duration"), (String) hashMapDistancePathInfo.get("distance"), (PolylineOptions) hashMapDistancePathInfo.get("polyLineOptions"), listNearByFacility.get(0).getNearBy().get(facilityPosition).getLocations().get(locationPosition).getName());
trPlaceTimeKm.setVisibility(View.VISIBLE);
} else {
findDistanceAndMarkDirection(listNearByFacility.get(0).getNearBy().get(facilityPosition).getLocations().get(locationPosition));
}
}
return false;
}
});
mMap.getUiSettings().setMyLocationButtonEnabled(false);
mMap.getUiSettings().setRotateGesturesEnabled(false);
}
private void loadMap() {
NearByPlaces originLocation = listNearByFacility.get(0);
if (listMarkerPoints.size() > 1) {
mMap.clear();
listMarkerPoints.remove(1);
}
// Adding new item to the ArrayList
NearBy nearBy = listNearByFacility.get(0).getNearBy().get(facilityPosition);
tvPlaceOriginName.setText(originLocation.getProjectName());
//tvPlaceDestinationName.setText(nearBy.getLocations().get(locationPosition).getName());
if (mapDistancePathData == null) {
mapDistancePathData = new HashMap<>();
}
// .get(locationPosition);
// LatLng destination = new LatLng(Double.valueOf(location.getLatitude()), Double.valueOf(location.getLongitude()));
//listMarkerPoints.add(destination);
MarkerOptions options = new MarkerOptions();
options.position(listMarkerPoints.get(0));
options.icon(BitmapDescriptorFactory.fromBitmap(getBitmapMarker(originLocation.getProjectName(), R.drawable.ic_marker_red)));
//options.title(originLocation.getProjectName());
mMap.addMarker(options).showInfoWindow();
for (int position = 0; position < nearBy.getLocations().size(); position++) {
Locations locations = nearBy.getLocations().get(position);
// Creating MarkerOptions
options = new MarkerOptions();
LatLng markerPosition = new LatLng(Double.valueOf(locations.getLatitude()), Double.valueOf(locations.getLongitude()));
// Setting the videoPlayPosition of the marker
options.position(markerPosition);
/**
* For the start location, the color of marker is GREEN and
* for the end location, the color of marker is RED.
*/
options.icon(BitmapDescriptorFactory.fromBitmap(getBitmapMarker(locations.getName(), 0)));
//options.title(locationRanges.getName());
// Add new marker to the Google Map Android API V2
Marker marker = mMap.addMarker(options);
// marker.showInfoWindow();
marker.setTag(position);
}
findDistanceAndMarkDirection(nearBy.getLocations().get(locationPosition));
}
public Bitmap getBitmapMarker(String title, int id) {
View customMarkerView = this.getLayoutInflater().inflate(R.layout.layout_marker_with_title, null);
customMarkerView.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
customMarkerView.layout(0, 0, customMarkerView.getMeasuredWidth(), customMarkerView.getMeasuredHeight());
TextView tvMarkerProjectName = (TextView) customMarkerView.findViewById(R.id.tv_marker_project_name);
if (id != 0) {
ImageView ivMarkerImage = (ImageView) customMarkerView.findViewById(R.id.iv_marker_image);
ivMarkerImage.setImageResource(id);
}
tvMarkerProjectName.setText(title);
customMarkerView.setDrawingCacheEnabled(true);
customMarkerView.buildDrawingCache();
Bitmap bm = customMarkerView.getDrawingCache();
return bm;
}
private void findDistanceAndMarkDirection(Locations destinationLocation) {
flagCalculatingPath = true;
if (polyline != null) {
polyline.remove();
}
trPlaceTimeKm.setVisibility(View.INVISIBLE);
tvPlaceDestinationName.setText(destinationLocation.getName());
// Checks, whether start and end locationRanges are captured
LatLng latLngDest = new LatLng(Double.valueOf(destinationLocation.getLatitude()), Double.valueOf(destinationLocation.getLongitude()));
LatLng origin = listMarkerPoints.get(0);
// Getting URL to the Google Directions API
String url = getUrl(origin, latLngDest);
//Log.d("onMapClick", url.toString());
fetchUrl = new FetchUrl();
// Start downloading json data from Google Directions API
fetchUrl.execute(url);
//move map camera
mMap.moveCamera(CameraUpdateFactory.newLatLng(origin));
mMap.animateCamera(CameraUpdateFactory.zoomTo(12));
}
private void setPathInfo(String duration, String distance, PolylineOptions polylineOptions, String destName) {
tvPlaceTime.setText(duration);
tvPlaceKmDistance.setText(distance);
polyline = mMap.addPolyline(polylineOptions);
tvPlaceDestinationName.setText(destName);
}
private String getUrl(LatLng origin, LatLng dest) {
// Origin of route
String str_origin = "origin=" + origin.latitude + "," + origin.longitude;
// Destination of route
String str_dest = "destination=" + dest.latitude + "," + dest.longitude;
// Sensor enabled
String sensor = "sensor=false";
// Building the parameters to the web service
String parameters = str_origin + "&" + str_dest + "&" + sensor;
// Output format
String output = "json";
// Building the url to the web service
String url = "https://maps.googleapis.com/maps/api/directions/" + output + "?" + parameters;
return url;
}
/**
* A method to download json data from url
*/
private String downloadUrl(String strUrl) throws IOException {
String data = "";
InputStream iStream = null;
HttpURLConnection urlConnection = null;
try {
URL url = new URL(strUrl);
// Creating an http connection to communicate with url
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setReadTimeout(15000 /* milliseconds */);
urlConnection.setConnectTimeout(15000 /* milliseconds */);
urlConnection.setDoInput(true);
// Connecting to url
urlConnection.connect();
// Reading data from url
iStream = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
StringBuffer sb = new StringBuffer();
String line = "";
while ((line = br.readLine()) != null) {
sb.append(line);
}
data = sb.toString();
//Log.d("downloadUrl", data.toString());
br.close();
} catch (Exception e) {
// Log.d("Exception", e.toString());
} finally {
iStream.close();
urlConnection.disconnect();
}
return data;
}
// Fetches data from url passed
private class FetchUrl extends AsyncTask<String, Void, String> {
#Override
protected void onCancelled() {
//super.onCancelled();
}
#Override
protected String doInBackground(String... url) {
// For storing data from web service
String data = "";
try {
// Fetching the data from web service
data = downloadUrl(url[0]);
//Log.d("Background Task data", data.toString());
} catch (Exception e) {
// Log.d("Background Task", e.toString());
}
return data;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (!TextUtils.isEmpty(result)) {
ParserTask parserTask = new ParserTask();
// Invokes the thread for parsing the JSON data
parserTask.execute(result);
} else {
flagCalculatingPath = false;
}
}
}
/**
* A class to parse the Google Places in JSON format
*/
private class ParserTask extends AsyncTask<String, Integer, List<List<HashMap<String, String>>>> {
// Parsing the data in non-ui thread
#Override
protected List<List<HashMap<String, String>>> doInBackground(String... jsonData) {
JSONObject jObject;
List<List<HashMap<String, String>>> routes = null;
try {
jObject = new JSONObject(jsonData[0]);
//Log.d("ParserTask", jsonData[0].toString());
DataParser parser = new DataParser();
//Log.d("ParserTask", parser.toString());
// Starts parsing data
routes = parser.parse(jObject);
//Log.d("ParserTask", "Executing routes");
//Log.d("ParserTask", routes.toString());
} catch (Exception e) {
//Log.d("ParserTask", e.toString());
e.printStackTrace();
}
return routes;
}
// Executes in UI thread, after the parsing process
#Override
protected void onPostExecute(List<List<HashMap<String, String>>> result) {
ArrayList<LatLng> points;
PolylineOptions lineOptions = null;
HashMap<String, Object> hashMapDistancePathInfo = null;
// Traversing through all the routes
for (int i = 0; i < result.size(); i++) {
points = new ArrayList<>();
lineOptions = new PolylineOptions();
// Fetching i-th route
List<HashMap<String, String>> path = result.get(i);
// Fetching all the points in i-th route
for (int j = 1; j < path.size(); j++) {
HashMap<String, String> point = path.get(j);
double lat = Double.parseDouble(point.get("lat"));
double lng = Double.parseDouble(point.get("lng"));
LatLng position = new LatLng(lat, lng);
points.add(position);
}
// Adding all the points in the route to LineOptions
lineOptions.addAll(points);
lineOptions.width(5);
lineOptions.color(Color.RED);
tvPlaceTime.setText(path.get(0).get("duration"));
tvPlaceKmDistance.setText(path.get(0).get("distance"));
trPlaceTimeKm.setVisibility(View.VISIBLE);
hashMapDistancePathInfo = new HashMap<>();
hashMapDistancePathInfo.put("duration", path.get(0).get("duration"));
hashMapDistancePathInfo.put("distance", path.get(0).get("distance"));
hashMapDistancePathInfo.put("polyLineOptions", lineOptions);
//Log.d("onPostExecute", "onPostExecute lineoptions decoded");
}
// Drawing polyline in the Google Map for the i-th route
if (lineOptions != null) {
mapDistancePathData.put(locationPosition, hashMapDistancePathInfo);
polyline = mMap.addPolyline(lineOptions);
} else {
//Log.d("onPostExecute", "without Polylines drawn");
}
flagCalculatingPath = false;
}
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(getApplicationContext())
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
}
#Override
public void onConnected(Bundle bundle) {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(1000);
mLocationRequest.setFastestInterval(1000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationListenerFinder = new LocationListenerFinder(this);
if (locationPermission) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, locationListenerFinder);
}
}
#Override
public void onConnectionSuspended(int i) {
mLocationRequest = null;
}
#Override
public void onLocationChanged(Location location) {
mLastLocation = location;
if (mCurrLocationMarker != null) {
mCurrLocationMarker.remove();
}
int size = listNearByFacility.get(0).getNearBy().get(facilityPosition).getLocations().size();
ivMyLocation.setVisibility(View.VISIBLE);
//Place current location marker
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.icon(BitmapDescriptorFactory.fromBitmap(getBitmapMarker("Current Location", R.drawable.ic_marker_blue)));
//MarkerOptions markerOptions = new MarkerOptions();
//markerOptions.videoPlayPosition(latLng);
//markerOptions.title("Current Location");
//markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
mCurrLocationMarker = mMap.addMarker(markerOptions);
mCurrLocationMarker.setTag(size + 1);
//move map camera
// mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
//mMap.animateCamera(CameraUpdateFactory.zoomTo(11));
if (mGoogleApiClient != null && mGoogleApiClient.isConnected()) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, locationListenerFinder);
mGoogleApiClient.disconnect();
mGoogleApiClient.unregisterConnectionCallbacks(this);
mGoogleApiClient.unregisterConnectionFailedListener(this);
//locationListener.clearData();
mLocationRequest = null;
locationListenerFinder = null;
}
mGoogleApiClient = null;
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
public void checkLocationPermission() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (!Utility.isPermissionAllowed(this, Manifest.permission.ACCESS_FINE_LOCATION)) {
Utility.showPermissionDialog(this, Manifest.permission.ACCESS_FINE_LOCATION, BookingKARConstants.PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);
locationPermission = false;
return;
} else {
locationPermission = true;
return;
}
}
locationPermission = true;
}
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
//Checking the request code of our request
if (requestCode == BookingKARConstants.PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION) {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted. Do the
locationPermission = true;
if (mGoogleApiClient == null) {
buildGoogleApiClient();
checkLocationStatus();
}
loadMap();
//mMap.setMyLocationEnabled(true);
} else {
// Permission denied, Disable the functionality that depends on this permission.
Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show();
finish();
}
return;
}
// other 'case' lines to check for other permissions this app might request.
// You can add here other case statements according to your requirement.
}
private void checkLocationStatus() {
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
boolean gps_enabled = false;
boolean network_enabled = false;
try {
gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch (Exception ex) {
}
try {
network_enabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch (Exception ex) {
}
if (!gps_enabled && !network_enabled) {
// notify user
AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setMessage(getResources().getString(R.string.gps_network_not_enabled));
dialog.setPositiveButton(getResources().getString(R.string.open_location_settings), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
// TODO Auto-generated method stub
Intent myIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(myIntent);
//get gps
}
});
dialog.setNegativeButton(getString(R.string.Cancel), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
// TODO Auto-generated method stub
}
});
dialog.show();
}
}
/*class WeakLocationListener implements LocationListener {
private final WeakReference<LocationListener> locationListenerRef;
public WeakLocationListener(#NonNull LocationListener locationListener) {
locationListenerRef = new WeakReference<>(WeakLocationListener.this);
}
#Override
public void onLocationChanged(android.location.Location location) {
if (locationListenerRef.get() == null) {
return;
}
locationListenerRef.get().onLocationChanged(location);
}
public interface onLocationChanged {
void onLocationChanged(Location location);
}
public void clearData() {
if (locationListenerRef.get() != null) {
locationListenerRef.clear();
}
}*/
//}
}
#Override
public void onDestroy() {
super.onDestroy();
mLocationManager.removeUpdates(locationListener);
}

Categories

Resources