Home get updated and lastknownlocation in a fragment
Reply: 1

get updated and lastknownlocation in a fragment

BaRud Published in 2018-02-14 09:41:51Z

Being very new to java, I am very confused about getting lastknownlocation and updated location.

Over last few days, I have managed to get the mark on a predefined location, but I am struggling very much on getting my current location using fusedlocationproviderclient.

I will be grateful if somebody kindly help me on getting this. I am using :

compile 'com.google.android.gms:play-services-maps:11.8.0'
compile 'com.google.android.gms:play-services-location:11.8.0'

Though not for the updated location, below is the code for marker at a fixed position

public class SecondFragment extends Fragment implements OnMapReadyCallback {

    private GoogleMap mMap;

    public GoogleMap getMap() {
    return mMap;
    public static SecondFragment newInstance() {
        SecondFragment fragment = new SecondFragment();
        return fragment;

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.activity_maps, null, false);

        SupportMapFragment mapFragment = (SupportMapFragment) this.getChildFragmentManager()

        return view;

    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;

        // Add a marker in Sydney and move the camera
        LatLng sydney = new LatLng(-34, 151);
        mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
Soham Reply to 2018-02-14 12:30:38Z

I am using this to get my location:

 LocationManager locationManager = (LocationManager)getActivity().getSystemService(getContext().LOCATION_SERVICE);
                Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);

and listener for this:

 LocationListener locationListener = new LocationListener() {
                    public void onLocationChanged(Location location) {
                        Log.e("osm", "onLocationChanged: "+location.getLongitude() );

                    public void onStatusChanged(String s, int i, Bundle bundle) {


                    public void onProviderEnabled(String s) {


                    public void onProviderDisabled(String s) {


Do not forget write to manifest this:

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> 

and runtime permission for new version of android(6 and up) :

String[] permission = new String[]{Manifest.permission.CALL_PHONE,Manifest.permission.ACCESS_FINE_LOCATION};
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.311302 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO