I want to make my first app to add a polyline in the map as i move (route tracking). I want to start draw the polyline when i press ButtonStart and stop when i press ButtonEnd. When i run it, it does not draw the polyline.
I run it in my phone and i disconnect it from the pc so i can move and see if it will draw the polyline.
public class MapsActivityCreateNewPath extends FragmentActivity implements
OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener, View.OnClickListener {
private GoogleMap mMap;
private GoogleApiClient googleApiClient;
private LocationRequest locationRequest;
private Location lastLocation;
private Marker currentUserLocationMarker;
private static final int Request_User_Location_Code = 99;
private ArrayList<LatLng> listPoints;
Polyline line;
int count = 0;
Button ButtonStart;
Button ButtonEnd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps_create_new_path);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
{
checkUserLocationPermission();
}
// 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);
listPoints = new ArrayList<LatLng>();
ButtonStart = (Button) findViewById(R.id.ButtonStart);
ButtonEnd = (Button) findViewById(R.id.ButtonEnd);
if (count == 0)
{
ButtonEnd.setEnabled(false);
ButtonStart.setEnabled(true);
}
ButtonStart.setOnClickListener(new View.OnClickListener(){public void onClick (View v) {next_page(v);}});
ButtonEnd.setOnClickListener(new View.OnClickListener() {public void onClick (View v) {next_page(v);}});
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)
{
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
}
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;
}
}
protected synchronized void buildGoogleApiClient()
{
googleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
googleApiClient.connect();
}
#Override
public void onLocationChanged(Location location) {
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_ORANGE));
currentUserLocationMarker = mMap.addMarker(markerOptions);
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomBy(14));
if (googleApiClient != null)
{
LocationServices.FusedLocationApi.removeLocationUpdates(googleApiClient, this);
}
double latitude = location.getLatitude();
double longitude = location.getLongitude();
LatLng latLng1 = new LatLng(latitude, longitude);
listPoints.add(latLng1);
redrawLine();
}
#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) {
}
public void next_page(View v){
switch(v.getId())
{
case R.id.ButtonStart:
count++;
ButtonStart.setEnabled(false);
ButtonEnd.setEnabled(true);
break;
case R.id.ButtonEnd:
count--;
ButtonStart.setEnabled(true);
ButtonEnd.setEnabled(false);
break;
}
if (count == 1) {
redrawLine();
}
}
#Override
public void onClick(View v) {
}
private void redrawLine()
{
if (count == 0)
{
return;
}
mMap.clear();
PolylineOptions options = new PolylineOptions().width(5).color(Color.BLUE).geodesic(true);
for (int i = 0; i < listPoints.size(); i++)
{
LatLng point = listPoints.get(i);
options.add(point);
}
line = mMap.addPolyline(options);
}
}
Related
When the user first enters the GoogleMapsActivity it does not automatically take them to their location, the user has to click the little location icon button at the top right and it will take them to their location.
I have tried using newLatLngZoom(latLng, zoom) but that didn't work. And I went through all the suggested questions before posting this question, and none worked. Some were in iOS too. I am using Android.
public class AppetiteMapsActivity extends FragmentActivity implements OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, com.google.android.gms.location.LocationListener
{
private GoogleMap mMap;
private GoogleApiClient googleApiClient;
private LocationRequest locationRequest;
private static final String TAG = "AppetiteMapsActivity";
private Location lastLocation;
private Marker currentUserLocationMarker;
private LocationManager locationManager;
private com.google.android.gms.location.LocationListener listener;
private static final int Request_User_Location_Code= 99;
private long UPDATE_INTERVAL = 2 * 1000; /* 10 secs */
private long FASTEST_INTERVAL = 2000; /* 2 sec */
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_appetite_maps);
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
{
checkUserLocationPermission();
}
// 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);
checkLocation();
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Add a marker in current user location and move the camera
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)
{
buildGoogleApiClient();
// Call current location of user
mMap.setMyLocationEnabled(true);
}
}
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, R.string.on_request_permission_gps_not_located, Toast.LENGTH_LONG).show();
}
return;
}
}
protected synchronized void buildGoogleApiClient()
{
googleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
googleApiClient.connect();
}
#Override
public void onConnected(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) {
Log.i(TAG, "Connection Suspended");
googleApiClient.connect();
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.i(TAG, "Connection failed. Error: " + connectionResult.getErrorCode());
}
#Override
protected void onStart() {
super.onStart();
if (googleApiClient != null) {
googleApiClient.connect();
}
}
#Override
protected void onStop() {
super.onStop();
if (googleApiClient.isConnected()) {
googleApiClient.disconnect();
}
}
protected void startLocationUpdates() {
// Create the location request
locationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(UPDATE_INTERVAL)
.setFastestInterval(FASTEST_INTERVAL);
// Request location updates
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient,
locationRequest, this);
Log.d("reque", "--->>>>");
}
#Override
public void onLocationChanged(Location location)
{
lastLocation = location;
if (currentUserLocationMarker!=null)
{
currentUserLocationMarker.remove();
}
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title(getString(R.string.user_current_location_marker_title));
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_YELLOW));
currentUserLocationMarker = mMap.addMarker(markerOptions);
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomBy(14));
if(googleApiClient != null)
{
LocationServices.FusedLocationApi.removeLocationUpdates(googleApiClient, this);
}
}
private boolean checkLocation() {
if(!isLocationEnabled())
showAlert();
return isLocationEnabled();
}
private void showAlert() {
final AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setTitle(R.string.show_alert_title_enable_location)
.setMessage(getString(R.string.show_alert_location_settings_off_1) +
getString(R.string.show_alert_location_settings_off_2))
.setPositiveButton(R.string.show_alert_positive_button_location_settings, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
Intent myIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(myIntent);
}
})
.setNegativeButton(R.string.explain_negative_button, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
}
});
dialog.show();
}
private boolean isLocationEnabled() {
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) ||
locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
}
}
I expect Google Maps to automatically go to the users location when they first go into the Google Maps Activity, but instead the user has to click the location button at the top right corner to send them there. Thanks for your help and advice in advanced!
I have tried using newLatLngZoom(latLng, zoom) but that didn't work.
Use it like this, it will work:
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
mMap.getUiSettings().setZoomControlsEnabled(true);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(LatLng, zoom));
mMap.getUiSettings().setRotateGesturesEnabled(false);
mMap.getUiSettings().setZoomControlsEnabled(false);
Note:
First, you Enable Zoom Controls.
Then, you do the Zooming thing.
After that, you Disable Zoom Controls.
Hope it helps.
Reference for more info
I am making an app like uber and i have to put driver location with marker on app and
after sign in it shows loading and then crashes?
i have imported all libraries properly but my logcat screen
i have tried going to similar questions on stackOverflow but nothing seems working and this bug just shows again and again and i am not unable to start my app .
Welcome Activity
{
private GoogleMap mMap;
//Play Services
private static final int MY_PERMISSION_REQUEST_CODE=7000;
private static final int PLAY_SERVICE_RES_REQUEST= 7001;
private LocationRequest mLocationRequest;
private GoogleApiClient mGoogleApiClient;
private Location mLastLocation;
private static int UPDATE_INTERVAL = 5000;
private static int FATEST_INTERVAL = 3000;
private static int DISPLACEMENT = 10;
DatabaseReference drivers;
GeoFire geoFire;
Marker mCurrent;
MaterialAnimatedSwitch location_switch;
SupportMapFragment mapFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_welcome);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
//Init View
location_switch = (MaterialAnimatedSwitch)findViewById(R.id.location_switch);
location_switch.setOnCheckedChangeListener(new MaterialAnimatedSwitch.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(boolean isOnline) {
if (isOnline)
{
startLocationUpdates();
displayLocation();
Snackbar.make(mapFragment.getView(),"You are Online",Snackbar.LENGTH_SHORT)
.show();
}
else
{
stopLocationUpdates();
mCurrent.remove();
Snackbar.make(mapFragment.getView(),"You are Offline",Snackbar.LENGTH_SHORT)
.show();
}
}
});
//Geo Fire
drivers = FirebaseDatabase.getInstance().getReference("Drivers");
geoFire = new GeoFire(drivers);
setUpLocation();
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode){
case MY_PERMISSION_REQUEST_CODE:
if (grantResults.length >0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
{
if (checkPlayServices())
{
buildGoogleApiClient();
createLocationRequest();
if(location_switch.isChecked())
displayLocation();
}
}
}
}
private void setUpLocation() {
if(ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED )
{
//Request runtime Permission
ActivityCompat.requestPermissions(this, new String[]{
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION
},MY_PERMISSION_REQUEST_CODE);
}
else
{
if (checkPlayServices())
{
buildGoogleApiClient();
createLocationRequest();
if(location_switch.isChecked())
displayLocation();
}
}
}
private void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(UPDATE_INTERVAL);
mLocationRequest.setFastestInterval(FATEST_INTERVAL);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setSmallestDisplacement(DISPLACEMENT);
}
private void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
}
private boolean checkPlayServices() {
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if(resultCode != ConnectionResult.SUCCESS)
{
if(GooglePlayServicesUtil.isUserRecoverableError(resultCode))
GooglePlayServicesUtil.getErrorDialog(resultCode,this,PLAY_SERVICE_RES_REQUEST).show();
else {
Toast.makeText(this, "This Device is not Supported", Toast.LENGTH_SHORT).show();
finish();
}
return false;
}
return true;
}
private void stopLocationUpdates() {
if(ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED )
{
return;
}
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient,this);
}
private void displayLocation() {
if(ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED )
{
return;
}
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (mLastLocation != null)
{
if (location_switch.isChecked())
{
final double latitude = mLastLocation.getLatitude();
final double longitude = mLastLocation.getLongitude();
//Update to Firebase
geoFire.setLocation(FirebaseAuth.getInstance().getCurrentUser().getUid(), new GeoLocation(latitude, longitude), new GeoFire.CompletionListener() {
#Override
public void onComplete(String key, DatabaseError error) {
//Add Marker
if (mCurrent != null)
mCurrent.remove(); //Remove already Marker
mCurrent = mMap.addMarker(new MarkerOptions()
.icon(BitmapDescriptorFactory.fromResource(R.drawable.lender))
.position(new LatLng(latitude,latitude))
.title("You"));
//Move the camera to this position
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latitude,longitude),15.0f));
//Draw Animation Rotate Marker
rotateMarker(mCurrent,-360,mMap);
}
});
}
}
else
{
Log.d("ERROR","Cannot Get Your Location");
}
}
private void rotateMarker(final Marker mCurrent, final float i, GoogleMap mMap) {
final Handler handler = new Handler();
final long start = SystemClock.uptimeMillis();
final float startRotation = mCurrent.getRotation();
final long duration = 1500;
final Interpolator interpolator = new LinearInterpolator();
handler.post(new Runnable() {
#Override
public void run() {
long elapsed = SystemClock.uptimeMillis() - start ;
float t = interpolator.getInterpolation((float)elapsed/duration);
float rot = t*i+(1-t)*startRotation;
mCurrent.setRotation(-rot > 180?rot/2:rot);
if(t<1.0)
{
handler.postDelayed(this,16);
}
}
});
}
private void startLocationUpdates() {
if(ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED )
{
return;
}
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient,mLocationRequest,this);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
}
#Override
public void onLocationChanged(Location location) {
mLastLocation = location;
displayLocation();
}
#Override
public void onConnected(#Nullable Bundle bundle) {
displayLocation();
startLocationUpdates();
}
#Override
public void onConnectionSuspended(int i) {
mGoogleApiClient.connect();
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
}
I want to show the user's location on a map whenever a toggle button is pressed. I have written the code like below and it works only to show the map but not the user's location and sometimes throws error like:
java.lang.IllegalStateException: GoogleApiClient is not connected yet.
on this line: LocationServices.FusedLocationApi.requestLocationUpdates(apiClient, locationRequest, this);
I am able to get the location in logcat but can't show on map. Here's the fragment code:
public class HomeFragment extends BaseFragment implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, com.google.android.gms.location.LocationListener {
private static final String TAG = HomeFragment.class.getSimpleName();
private Toolbar toolbar;
private TextView driverStatusTV;
public static MaterialAnimatedSwitch statusSwitch;
public static GoogleApiClient apiClient;
public static Location mLastLocation;
public static LocationRequest locationRequest;
public GoogleMap mGmap;
public static Marker currentMarker;
public static double latitude = 0f, longitude = 0f;
public static final int UPDATE_INTERVAL = 15000;
public static final int FASTEST_INTERVAL = 8000;
public static final int DISPLACEMENT = 10;
public static final int PLAY_SERVICES_REQ_CODE = 9009;
public static final int PLAY_SERVICES_RESOLUTION_REQ_CODE = 9090;
private SupportMapFragment mapFragment;
public HomeFragment() {
// Required empty public constructor
}
private void initViews(View view) {
toolbar = view.findViewById(R.id.toolbar);
driverStatusTV = view.findViewById(R.id.driverStatusTV);
statusSwitch = view.findViewById(R.id.statusSwitch);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_home, container, false);
initViews(view);
((AppCompatActivity) getActivity()).setSupportActionBar(toolbar);
mapFragment = (SupportMapFragment) this.getChildFragmentManager().findFragmentById(R.id.mapFragment);
mapFragment.getMapAsync(this);
setUpLocation();
statusSwitch.setOnCheckedChangeListener(new MaterialAnimatedSwitch.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(boolean b) {
if (b){
Snackbar.make(getActivity().findViewById(android.R.id.content), "You are Now Online", Snackbar.LENGTH_LONG).show();
startLocationListener();
displayLocation();
driverStatusTV.setText("ONLINE");
} else {
Snackbar.make(getActivity().findViewById(android.R.id.content), "You are Now Offline", Snackbar.LENGTH_LONG).show();
stopLocationListener();
driverStatusTV.setText("OFFLINE");
//currentMarker.remove();
}
}
});
return view;
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case AppConstants.LOC_PERM_CODE:
for (int gr : grantResults) {
if (gr == PackageManager.PERMISSION_GRANTED) {
if (checkPlayServices()) {
makeLocationRequest();
initAPIClient();
if (statusSwitch.isChecked()) {
displayLocation();
}
} else {
Snackbar.make(getActivity().findViewById(android.R.id.content), "Google Play Services Not Supported on Your Device", Snackbar.LENGTH_LONG).show();
}
} else {
getActivity().finish();
getActivity().moveTaskToBack(true);
}
}
break;
}
}
public void startLocationListener() {
if (ContextCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
|| ContextCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, AppConstants.LOC_PERM_CODE);
} else {
initAPIClient();
apiClient.connect();
LocationServices.FusedLocationApi.requestLocationUpdates(apiClient, locationRequest, this);
}
}
public void setUpLocation() {
if (ContextCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
|| ContextCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
} else {
if (checkPlayServices()) {
if (statusSwitch.isChecked()) {
initAPIClient();
makeLocationRequest();
displayLocation();
}
} else {
Snackbar.make(getActivity().findViewById(android.R.id.content), "Google Play Services Not Supported on Your Device", Snackbar.LENGTH_LONG).show();
}
}
}
private void makeLocationRequest() {
locationRequest = LocationRequest.create();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setInterval(UPDATE_INTERVAL);
locationRequest.setFastestInterval(FASTEST_INTERVAL);
locationRequest.setSmallestDisplacement(DISPLACEMENT);
}
public boolean checkPlayServices() {
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getActivity());
if (resultCode != ConnectionResult.SUCCESS) {
if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
GooglePlayServicesUtil.getErrorDialog(resultCode, getActivity(), AppConstants.PLAY_SERVICES_RESOLUTION_REQUEST).show();
} else {
Snackbar.make(getActivity().findViewById(android.R.id.content), "Play Services NOT Supported on Your Device", Snackbar.LENGTH_LONG).show();
getActivity().finish();
getActivity().moveTaskToBack(true);
}
return false;
}
return true;
}
private void initAPIClient() {
apiClient = new GoogleApiClient.Builder(getActivity())
.enableAutoManage(getActivity(), 0, this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
apiClient.connect();
}
public void stopLocationListener() {
if (ContextCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
|| ContextCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
} else {
LocationServices.FusedLocationApi.removeLocationUpdates(apiClient, this);
}
}
public void displayLocation() {
if (ContextCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
|| ContextCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, AppConstants.LOC_PERM_CODE);
} else {
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(apiClient);
if (mLastLocation != null) {
if (statusSwitch.isChecked()) {
latitude = mLastLocation.getLatitude();
longitude = mLastLocation.getLongitude();
Log.d(TAG, "Locn:\t" + "lat:\t" + latitude + "and long:\t" + longitude);
geoFire.setLocation("saj9oPN15VZODBbB87JXU26Rqa53", new GeoLocation(latitude, longitude), new GeoFire.CompletionListener() {
#Override
public void onComplete(String key, DatabaseError error) {
if (currentMarker != null) {
currentMarker.remove();
currentMarker.setIcon(BitmapDescriptorFactory.fromResource(R.drawable.car));
currentMarker = mGmap.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude)));
LatLng latLng = new LatLng(latitude, longitude);
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(latLng, 17f);
mGmap.animateCamera(cameraUpdate);
//draw rotate marker animation
//rotateMarker(currentMarker, -360, mGmap);
}
}
});
}
}
}
}
private void rotateMarker(final Marker currentMarker, final float i, GoogleMap mGmap) {
final Handler handler = new Handler();
final long start = SystemClock.uptimeMillis();
final float startRotation = currentMarker.getRotation();
final int duration = 1500;
final Interpolator interpolator = new LinearInterpolator();
handler.postDelayed(new Runnable() {
#Override
public void run() {
long elapsed = SystemClock.elapsedRealtime() - start;
float t = interpolator.getInterpolation(elapsed / duration);
float rot = t * i + (1 - t) * startRotation;
currentMarker.setRotation(-rot > 180 ? rot / 2 : rot);
if (t < 1.0) {
handler.postDelayed(this, 16);
}
}
}, duration);
}
#Override
public void onConnected(#Nullable Bundle bundle) {
startLocationListener();
displayLocation();
}
#Override
public void onConnectionSuspended(int i) {
apiClient.connect();
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
if (apiClient != null) {
apiClient = null;
initAPIClient();
}
}
#Override
public void onLocationChanged(Location location) {
mLastLocation = location;
displayLocation();
}
#Override
public void onMapReady(GoogleMap googleMap) {
mGmap = googleMap;
}
}
Can anyone help me understand why it's not working.
I've a pretty large working app, I've implemented myLocation in MapLocation.class which extends Fragment.
Everything was working fine, my whole list of markers were displaying perfectly but after implementation of myLocation, a strange condition occurred.
Condition is on first run/install (after uninstalling the previous one or clearing the data), markers are displayed perfectly but neither myLocation works nor the myLocation icon appears, even it asks for permission.
On second run through studio or launching app again after clearing from recents, location works perfectly with the icon on its place but Markers become invisible. Invisible because camera focuses on Marker's place instead of myLocation as in the code.
Code is as follows:
public class MetroLocation extends Fragment implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {
MapView mMapView;
private GoogleMap googleMap;
ArrayList<Double> arLat = new ArrayList<>();
ArrayList<Double> arLong = new ArrayList<>();
ArrayList<String> arName=new ArrayList<>();
ArrayList<String> arLine = new ArrayList<>();
double lng;
double lat;
LatLng latLng;
Marker mCurrLocation;
Location mLastLocation;
LocationRequest mLocationRequest;
GoogleApiClient mGoogleApiClient;
private Cursor Lat;
private Cursor Long;
private Cursor Stations;
private MyDatabase db;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.activity_metro_location, container, false);
mMapView = v.findViewById(R.id.mapLocation);
mMapView.onCreate(savedInstanceState);
mMapView.onResume();
db = new MyDatabase(getActivity());
Lat = db.getLat();
Long = db.getLong();
Stations = db.getStation();
Cursor line = db.getMetroLine();
for(Lat.moveToFirst(); !Lat.isAfterLast(); Lat.moveToNext()) {
arLat.add(Lat.getDouble(0));
}
for(Long.moveToFirst(); !Long.isAfterLast(); Long.moveToNext()) {
arLong.add(Long.getDouble(0));
}
for(Stations.moveToFirst(); !Stations.isAfterLast(); Stations.moveToNext()) {
arName.add(Stations.getString(0));
}
for(line.moveToFirst(); !line.isAfterLast(); line.moveToNext()) {
arLine.add(line.getString(0));
}
try {
MapsInitializer.initialize(getActivity().getApplicationContext());
} catch (Exception e) {
e.printStackTrace();
}
mMapView.getMapAsync(this);
return v;
}
#Override
public void onResume() {
super.onResume();
mMapView.onResume();
}
#Override
public void onPause() {
super.onPause();
mMapView.onPause();
if (mGoogleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
}
#Override
public void onLowMemory() {
super.onLowMemory();
mMapView.onLowMemory();
}
#Override
public void onDestroy() {
super.onDestroy();
Lat.close();
Long.close();
Stations.close();
db.close();
mMapView.onDestroy();
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
}
#Override
public void onLocationChanged(Location location) {
mLastLocation = location;
if (mCurrLocation != null) {
mCurrLocation.remove();
}
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));
}
#Override
public void onConnected(Bundle bundle) {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(5000);
mLocationRequest.setFastestInterval(3000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
mLocationRequest.setSmallestDisplacement(2F);
Location mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
mGoogleApiClient);
if (mLastLocation != null) {
googleMap.clear();
latLng = new LatLng(mLastLocation.getLatitude(), mLastLocation.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("Current Position");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
mCurrLocation = googleMap.addMarker(markerOptions);
}
if (ContextCompat.checkSelfPermission(getActivity(),
android.Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
}
#Override
public void onConnectionSuspended(int i) {
Toast.makeText(getActivity(),"Connection Suspended",Toast.LENGTH_SHORT).show();
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
Toast.makeText(getActivity(),"Connection Failed",Toast.LENGTH_SHORT).show();
}
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
private void checkLocationPermission() {
if (ContextCompat.checkSelfPermission(getActivity(), android.Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),
android.Manifest.permission.ACCESS_FINE_LOCATION)) {
new AlertDialog.Builder(getActivity())
.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(getActivity(),
new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION );
}
})
.create()
.show();
} else {
ActivityCompat.requestPermissions(getActivity(),
new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION );
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String permissions[], #NonNull int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_LOCATION: {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (ContextCompat.checkSelfPermission(getActivity(),
android.Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
if (mGoogleApiClient == null) {
buildGoogleApiClient();
}
googleMap.setMyLocationEnabled(true);
}
} else {
Toast.makeText(getActivity(), "permission denied", Toast.LENGTH_LONG).show();
}
}
}
}
public void onMapReady(GoogleMap mMap) {
googleMap = mMap;
googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
googleMap.getUiSettings().setZoomControlsEnabled(true);
googleMap.getUiSettings().setAllGesturesEnabled(true);
googleMap.getUiSettings().setCompassEnabled(true);
for(int j= 0;j<arLat.size();j++) {
double lat1 = arLat.get(j);
double long1 = arLong.get(j);
String name = arName.get(j);
String snippet = "Metro Station"+ " Line : " + arLine.get(j);
LatLng latLng = new LatLng(lat1, long1);
googleMap.addMarker(new MarkerOptions().position(latLng).title(name).snippet(snippet).flat(true).icon(
BitmapDescriptorFactory.fromResource(R.drawable.green)));
}
int i = arLat.size() / 2;
lat = arLat.get(i);
lng = arLong.get(i);
LatLng latLng1 = new LatLng(lat, lng);
CameraPosition cameraPosition = new CameraPosition.Builder().target(latLng1).zoom(12).build();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(getActivity(),
android.Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
buildGoogleApiClient();
googleMap.setMyLocationEnabled(true);
} else {
checkLocationPermission();
}
} else {
buildGoogleApiClient();
googleMap.setMyLocationEnabled(true);
}
if (mMapView != null &&
mMapView.findViewById(Integer.parseInt("1")) != null) {
View locationButton = mMapView.findViewWithTag("GoogleMapMyLocationButton");
View locationButton1 = mMapView.findViewWithTag("GoogleMapCompass");
RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) locationButton.getLayoutParams();
layoutParams.addRule(RelativeLayout.ALIGN_PARENT_TOP, 0);
layoutParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE);
layoutParams.setMargins(0, 0, 40, 253);
RelativeLayout.LayoutParams layoutParams1 = (RelativeLayout.LayoutParams) locationButton1.getLayoutParams();
layoutParams1.addRule(RelativeLayout.ALIGN_PARENT_LEFT, 0);
layoutParams1.addRule(RelativeLayout.ALIGN_PARENT_TOP,0);
layoutParams1.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
layoutParams1.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
layoutParams1.bottomMargin = 100;
}
}
}
If there's something my code has wrong, please help.
EDIT - I've experienced that marker appears for a flash and then disappears. Everything else remains same. Also, a restart is required for location and it's button to appear.
I have an arraylist of locations marker. I have this method to sort the list. I then assign the first lat and long in the list to a variable so I can get the nearest store.
Collections.sort(marker, new Comparator<Markers>() {
#Override
public int compare(Markers a, Markers b) {
Location locationA = new Location("point A");
locationA.setLatitude(a.latitude);
locationA.setLongitude(a.longitude);
Location locationB = new Location("point B");
locationB.setLatitude(b.latitude);
locationB.setLongitude(b.longitude);
float distanceOne = currPos.distanceTo(locationA);
float distanceTwo = currPos.distanceTo(locationB);
return Float.compare(distanceOne, distanceTwo);
}
});
nearest = new LatLng(marker.get(0).latitude, marker.get(0).longitude);
However, when I use the nearest variable to put a marker on it, no marker was posted on the map. When I checked the value of nearest it does not contain any coordinates. Am I missing on something? Here is my whole MapsActivity.java:
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {
private GoogleMap mMap;
GoogleApiClient mGoogleApiClient;
Location mLastLocation;
Marker mCurrLocationMarker;
LocationRequest mLocationRequest;
private static LatLng nearest;
private static Location currPos;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
checkLocationPermission();
}
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
fetchData();
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.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();
mMap.setMyLocationEnabled(true);
mMap.addMarker(new MarkerOptions()
.position(new LatLng(nearest.latitude,nearest.longitude))
.title("Nearest Store"));
}
}
else {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
}
public void fetchData() {
new AsyncTask() {
private List<Markers> marker;
private JSONArray jsonArray;
#Override
protected void onPreExecute() {
super.onPreExecute();
marker = new ArrayList();
}
#Override
protected Object doInBackground(Object[] objects) {
return null;
}
#Override
protected void onPostExecute(Object o) {
super.onPostExecute(o);
try {
Intent mapsIntent = getIntent();
String jSonArray = mapsIntent.getStringExtra("jsonArray");
jsonArray = new JSONArray(jSonArray);
for(int i = 0; i < jsonArray.length(); i++) {
Markers branch = new Markers();
branch.latitude = Float.parseFloat(jsonArray.getJSONObject(i).getString("latitude"));
branch.longitude = Float.parseFloat(jsonArray.getJSONObject(i).getString("longitude"));
marker.add(branch);
}
Collections.sort(marker, new Comparator<Markers>() {
#Override
public int compare(Markers a, Markers b) {
Location locationA = new Location("point A");
locationA.setLatitude(a.latitude);
locationA.setLongitude(a.longitude);
Location locationB = new Location("point B");
locationB.setLatitude(b.latitude);
locationB.setLongitude(b.longitude);
float distanceOne = currPos.distanceTo(locationA);
float distanceTwo = currPos.distanceTo(locationB);
return Float.compare(distanceOne, distanceTwo);
}
});
nearest = new LatLng(marker.get(0).latitude, marker.get(0).longitude);
} catch (Exception ex) {
Log.d("Error", ex.toString());
}
}
}.execute();
}
private class Markers {
public float latitude;
public float longitude;
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.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_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) {
mLastLocation = location;
if (mCurrLocationMarker != null) {
mCurrLocationMarker.remove();
}
//Place current location marker
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
currPos = location;
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("Current Location");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
mCurrLocationMarker = mMap.addMarker(markerOptions);
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(11));
if (mGoogleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
}
#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) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_FINE_LOCATION)) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
} else {
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 (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;
}
}
}
}
There's a race condition between your two threads.
mapFragment.getMapAsync(this); // thread 1
fetchData(); // thread 2
Thread 1 needs Thread 2 to finish and assign nearest to work. Otherwise it is null
You could call mapFragment.getMapAsync(MapsActivity.this); at the end of onPostExecute, but...
Your Asynctask is pointless at the moment because no data is being fetched by a background task.