I have a big problem with fused location provider api , all the methods I ovveride (for example in onConnected I get the last location known) are working except OnLocation change I don't know really what's the problem because I use the same code in other fragment with MapView and it works without any problem.
This is my code :
public class MissionsFragment extends Fragment implements
SwipeRefreshLayout.OnRefreshListener,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener{
LocationRequest mLocationRequest;
GoogleApiClient mGoogleApiClient;
LatLng latLng;
View view;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_jobs, container, false);
ButterKnife.bind(this, view);
return view;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
buildGoogleApiClient();
mGoogleApiClient.connect();
}
#Override
public void onConnected(#Nullable Bundle bundle) {
Location mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (mLastLocation != null) {
latLng = new LatLng(mLastLocation.getLatitude(), mLastLocation.getLongitude());
Toast.makeText(getActivity(), latLng.toString(), Toast.LENGTH_SHORT).show();
}
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(2000);
mLocationRequest.setFastestInterval(1000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
//mLocationRequest.setSmallestDisplacement(0.1F); //1/10 meter
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onLocationChanged(Location location) {
latLng = new LatLng(location.getLatitude(), location.getLongitude());
Toast.makeText(getActivity(), latLng.toString(), Toast.LENGTH_SHORT).show();
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
#Override
public void onPause() {
super.onPause();
if (mGoogleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
}
}
is it necessary to get the location if we use MapView only or I should update soemthing in my current code ?
Related
in the following code does not display the marker.This code I have made with previews android studio editions and there was no problem with tracking but now there is.I want to make a google map with tracking tab and for this reason I think can't use activity but only fragment.Anyone knows how it can be done?
public class Tab2Map extends Fragment implements OnMapReadyCallback {
GoogleMap mGoogleMap;
MapView mMapView;
View mView;
public Tab2Map() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
mView = inflater.inflate(R.layout.fragment_tab2, container, false);
return mView;
}
#Override
public void onViewCreated(View view,Bundle savedInstanceState){
super.onViewCreated(view,savedInstanceState);
mMapView=(MapView) mView.findViewById(R.id.map);
if(mMapView != null){
mMapView.onCreate(null);
mMapView.onResume();
mMapView.getMapAsync(this);
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
MapsInitializer.initialize(getContext());
mGoogleMap = googleMap;
if (ActivityCompat.checkSelfPermission(this.getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this.getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
mGoogleMap.setMyLocationEnabled(true);
LocationManager locationManager = (LocationManager)getActivity().getSystemService(Context.LOCATION_SERVICE);
if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
LatLng latlng = new LatLng(location.getLatitude(), location.getLongitude());
mGoogleMap.addMarker(new MarkerOptions().position(latlng).title("Current Location").snippet(latlng.toString()));
CameraPosition position=CameraPosition.builder().target(latlng).zoom(16).bearing(0).build();
mGoogleMap.moveCamera(CameraUpdateFactory.newCameraPosition(position));
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
};
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5, 15, locationListener);
}
}
fragment_tab2.xml
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/frameLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Tab2Map">
<com.google.android.gms.maps.MapView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/map"/>
</android.support.constraint.ConstraintLayout>
I am just a beginner in java/android. I was trying to pass location latitude and longitude to firebase. So I toast the message to see the value it was showing 0.0. I passed lat and long value from client.getlastlocation to the global value of lat and lon, but it is showing default value 0.0, why is this happening?
public class shopaction extends Fragment implements CompoundButton.OnCheckedChangeListener{
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
Location location;
GoogleApiClient googleApiClient;
FusedLocationProviderClient client;
private String mParam1;
private String mParam2;
String s;
Switch action;
public double lat,lon;
private OnFragmentInteractionListener mListener;
public shopaction() {
}
public static shopaction newInstance(String param1, String param2) {
shopaction fragment = new shopaction();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_shopaction, container, false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
action = (Switch) view.findViewById(R.id.action);
action.setOnCheckedChangeListener(this);
client = LocationServices.getFusedLocationProviderClient(getActivity());
Button button=(Button)view.findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(getActivity(),new String[]{Manifest.permission.ACCESS_FINE_LOCATION},1);
}
client.getLastLocation().addOnSuccessListener(getActivity(), new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
lat=location.getLatitude();
lon=location.getLongitude();
}
});
}
});
client.getLastLocation().addOnSuccessListener(getActivity(), new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
lat=location.getLatitude();
lon=location.getLongitude();
}
});
Toast.makeText(getActivity(),lat+"",Toast.LENGTH_LONG).show();
FirebaseDatabase firebaseDatabase=FirebaseDatabase.getInstance();
DatabaseReference databaseReference=firebaseDatabase.getReference();
databaseReference.child("shop").child("location").setValue(lat);
}
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(action.isChecked())
{
Toast.makeText(getActivity(),"Your shop is open",Toast.LENGTH_LONG).show();
action.setText("open");
s="open";
}
else
{
Toast.makeText(getActivity(),"Your shop is closed",Toast.LENGTH_LONG).show();
action.setText("close");
s="close";
}
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
The problem is that getLastLocation() returns a Task which then operates asynchronously. The location data are not available until the success listener call-back has actually been called. Meanwhile, your code proceeds to display a Toast using the current (default) values of 0 for lat and lon.
One way to fix this is to have your success listener callback display the toast, rather than your main code. So instead of this:
client.getLastLocation().addOnSuccessListener(getActivity(), new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
lat=location.getLatitude();
lon=location.getLongitude();
}
});
Toast.makeText(getActivity(),lat+"",Toast.LENGTH_LONG).show();
// Firebase update code that depends on location data
use this:
client.getLastLocation().addOnSuccessListener(getActivity(), new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
lat=location.getLatitude();
lon=location.getLongitude();
Toast.makeText(getActivity(),lat+"",Toast.LENGTH_LONG).show();
// Firebase update code that depends on location data
}
});
I can't resolve this problem. I trying to create Fragment with a map and I have this done. When I add static Long, Lat value the map show this o a map, But when I trying to make it automatic with getting localization in runnable the application just open the map and don't show specific LongLand values.
How to do this?
For getting long and late I'm using LocalizationManager, of course, I add permissions in manifest and also check runtime
public class LocalizationFragment extends Fragment implements OnMapReadyCallback {
private GoogleMap map;
MapView mapView;
View mview;
private double latitude, longtitude;
private Handler handler;
private Runnable runnable;
public LocalizationFragment() {
// Required empty public constructor
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mview = inflater.inflate(R.layout.fragment_localization, container, false);
handler = new Handler();
getLocation();
if (ContextCompat.checkSelfPermission(getContext(), android.Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 13);
}
if (ContextCompat.checkSelfPermission(getContext(), android.Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 11);
}
return mview;
}
#OnClick(R.id.button)
public void buttonStart() {
getLocation();
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mapView = (MapView) mview.findViewById(R.id.mapView);
if (mapView != null) {
mapView.onCreate(null);
mapView.onResume();
mapView.getMapAsync(this);
}
}
private void getLocation() {
LocationManager locationManager = (LocationManager) getContext().getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener = new LocationListener() {
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
latitude = location.getLatitude();
longtitude = location.getLongitude();
}
};
if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission
(getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
}
#Override
public void onMapReady(final GoogleMap googleMap) {
MapsInitializer.initialize(getContext());
map = googleMap;
googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
runnable = new Runnable() {
#Override
public void run() {
getLocation();
googleMap.addMarker(new MarkerOptions().position(new LatLng(latitude, longtitude)).title("Statue").snippet("Something"));
CameraPosition liberty = CameraPosition.builder().target(new LatLng(latitude, longtitude)).zoom(15).bearing(0).tilt(45).build();
googleMap.moveCamera(CameraUpdateFactory.newCameraPosition(liberty));
handler.postDelayed(this, 5000);
}
};
}
}
You need to add markers form the main thread.add this to your runnable.
runOnUiThread(new Runnable() {
#Override
public void run() {
googleMap.addMarker(new MarkerOptions().position(new LatLng(latitude, longtitude)).title("Statue").snippet("Something"));
}
});
I think this problem come from synchronize data. If you got location after add marker, it is meaningless, you get no location, and you have no marker on map, try to move action add marker into onLocationChanged
A tab within my view pager contains a map view is showing some unexpected behaviour. For some reason whenever I go to a different tab and return to the map view tab, all 4 pins within my map view appear when only 2 of them are supposed to appear. Does anyone know why this has happened? What can be done in order to prevent this from happening?
Stage 1 (flicked the top switch)
Stage 2 (flicked the bottom switch)
Stage 3 (switching to a different tab, then returning back to the map tab)
Java class
public class FragmentCentralPark extends android.support.v4.app.Fragment implements OnMapReadyCallback {
public FragmentCentralPark() {
// Required empty constructor
}
GoogleMap mGoogleMap;
MapView mMapView;
SwitchCompat swt0;
SwitchCompat swt1;
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_centralpark, container, false);
mMapView = (MapView) v.findViewById(R.id.map_centralpark);
mMapView.onCreate(savedInstanceState);
mMapView.getMapAsync(this); //this is important
swt0 = (SwitchCompat) v.findViewById(R.id.switch0_map_centralpark);
swt1 = (SwitchCompat) v.findViewById(R.id.switch1_map_centralpark);
return v;
}
#Override
public void onMapReady(GoogleMap googleMap) {
mGoogleMap = googleMap;
mGoogleMap.getUiSettings().setZoomControlsEnabled(true);
mGoogleMap.setBuildingsEnabled(true);
mGoogleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
swt0.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
initMap0(isChecked);
}
});
swt1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
initMap1(isChecked);
}
});
initMap0(swt0.isChecked());
initMap1(swt1.isChecked());
// Add markers and move the camera
LatLng centralpark_museum1 = new LatLng(40.785407, -73.957145);
mGoogleMap.addMarker(new MarkerOptions()
.position(centralpark_museum1)
);
LatLng centralpark_museum2 = new LatLng(40.782993, -73.958985);
mGoogleMap.addMarker(new MarkerOptions()
.position(centralpark_museum2)
);
// Updates the location and zoom level of the MapView
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(new LatLng(40.780437, -73.981063), 16);
mGoogleMap.animateCamera(cameraUpdate);
}
#Override
public void onResume() {
super.onResume();
mMapView.onResume();
}
#Override
public void onPause() {
super.onPause();
mMapView.onPause();
}
#Override
public void onDestroy() {
super.onDestroy();
mMapView.onDestroy();
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mMapView.onSaveInstanceState(outState);
}
#Override
public void onLowMemory() {
super.onLowMemory();
mMapView.onLowMemory();
}
private void initMap0(boolean isChecked){
if (isChecked) {
mGoogleMap.setMapStyle(new MapStyleOptions(getResources()
.getString(R.string.style_json)));
} else {
mGoogleMap.setMapStyle(null);
}
}
private void initMap1(boolean isChecked){
if (isChecked) {
mGoogleMap.clear();
// Add markers and move the camera
LatLng centralpark__theatre1 = new LatLng(40.780287, -73.968832);
mGoogleMap.addMarker(new MarkerOptions()
.position(centralpark_theatre1)
);
LatLng centralpark__theatre2 = new LatLng(40.780437, -73.981063);
mGoogleMap.addMarker(new MarkerOptions()
.position(centralpark_theatre2)
);
// Updates the location and zoom level of the MapView
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(new LatLng(40.780437, -73.981063), 16);
mGoogleMap.animateCamera(cameraUpdate);
} else {
mGoogleMap.clear();
// Add markers and move the camera
LatLng centralpark_museum1 = new LatLng(40.785407, -73.957145);
mGoogleMap.addMarker(new MarkerOptions()
.position(centralpark_museum1)
);
LatLng centralpark_museum2 = new LatLng(40.782993, -73.958985);
mGoogleMap.addMarker(new MarkerOptions()
.position(centralpark_museum2)
);
// Updates the location and zoom level of the MapView
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(new LatLng(40.780437, -73.981063), 16);
mGoogleMap.animateCamera(cameraUpdate);
}
}
}
MapFragment.java
public class MapFragment extends SupportMapFragment implements OnMapReadyCallback{
private GoogleMap googleMap;
private Context context;
public MapFragment(){
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
super.onCreateView(inflater, container, savedInstanceState);
View root = inflater.inflate(R.layout.item_individual_warehouse, null, false);
onMapReady(googleMap);
return root;
}
private void initializeMap(){
if(googleMap == null) {
SupportMapFragment fm =(SupportMapFragment)getChildFragmentManager().findFragmentById(R.id.map);
fm.getMapAsync(this);
if(googleMap == null){
Toast.makeText(context,"Sorry! We are unable to load maps", Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onMapReady(GoogleMap gm) {
googleMap = gm;
initializeMap();
}
}
In my oncreate method in RetrieveIndividualWarehouseSales.java
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.item_individual_warehouse);
new RetrieveItem().execute();
MapFragment mf = new MapFragment();
mf.onMapReady(googleMap);
}
item_individual_warehouse.xml
<FrameLayout
android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/sales_location"/>
Error is:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.gms.maps.SupportMapFragment.getMapAsync(com.google.android.gms.maps.OnMapReadyCallback)' on a null object reference
I am trying to instantiate the MapFragment object in RetrieveIndividualWarehouseSales.java so that I can display the map in item_individual_warehouse.xml which contains a bunch of textviews and one framelayout which is meant for map.
Use this.
public class MapLocationActivity extends AppCompatActivity
implements OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {
GoogleMap mGoogleMap;
SupportMapFragment mapFrag;
LocationRequest mLocationRequest;
GoogleApiClient mGoogleApiClient;
Location mLastLocation;
Marker mCurrLocationMarker;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
checkLocationPermission();
}
mapFrag = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFrag.getMapAsync(this);
}
#Override
public void onPause() {
super.onPause();
//stop location updates when Activity is no longer active
if (mGoogleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
}
#Override
public void onMapReady(GoogleMap googleMap)
{
mGoogleMap=googleMap;
mGoogleMap.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) {
buildGoogleApiClient();
mGoogleMap.setMyLocationEnabled(true);
}
}
else {
buildGoogleApiClient();
mGoogleMap.setMyLocationEnabled(true);
}
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
}
#Override
public void 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 onConnectionFailed(ConnectionResult connectionResult) {}
#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());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("Current Position");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
mCurrLocationMarker = mGoogleMap.addMarker(markerOptions);
//move map camera
mGoogleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mGoogleMap.animateCamera(CameraUpdateFactory.zoomTo(11));
//stop location updates
if (mGoogleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
}
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)) {
//TODO:
// Show an expanation 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
//(just doing it here for now, note that with this code, no explanation is 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, yay! Do the
// location-related task you need to do.
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
if (mGoogleApiClient == null) {
buildGoogleApiClient();
}
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
}
}
}