1

How can i get Current location.i have tried below code but getting null for location-

public class LocationsMapView extends Fragment implements LocationListener, android.location.LocationListener{
public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);

  locationManager = (LocationManager)getActivity().getSystemService(Context.LOCATION_SERVICE);
    locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,0,0,LocationsMapView.this);
    // Define the criteria how to select the locatioin provider -> use
    // default
    Criteria criteria = new Criteria();
    provider = locationManager.getBestProvider(criteria, false);
    location = locationManager.getLastKnownLocation(provider);

    // Initialize the location fields
    if (location != null) {
      System.out.println("Provider " + provider + " has been selected.");
      onLocationChanged(location);
    } else {
      System.out.println("Location not available");

    }
}

@Override
    public void onLocationChanged(Location loc) {
        current=new LatLng(loc.getLatitude(),loc.getLongitude());
        lat=loc.getLatitude();longi=loc.getLongitude();
        Toast.makeText(getActivity(), "location-"+loc.getLatitude(), Toast.LENGTH_SHORT).show();
        System.out.println("location.."+lat+"..."+longi+" current .."+current);
    }

    @Override
    public void onProviderDisabled(String arg0) {
        // TODO Auto-generated method stub
    }

    @Override
    public void onProviderEnabled(String arg0) {
        // TODO Auto-generated method stub
    }

    @Override
    public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
        // TODO Auto-generated method stub
    }
@Override
    public void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        location = locationManager.getLastKnownLocation(provider);

            // Initialize the location fields
            if (location != null) {
              System.out.println("Provider " + provider + " has been selected.");
              onLocationChanged(location);
            } else {
              System.out.println("Location not available"); 
            }       
}
}

I have also given permission in manifest-

<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
yuva ツ
  • 3,707
  • 9
  • 50
  • 78

1 Answers1

1

Try on this way:

public static class XYZ extends Fragment
        implements
            GooglePlayServicesClient.ConnectionCallbacks,
            GooglePlayServicesClient.OnConnectionFailedListener,
            LocationListener {
    GoogleMap map;
    LatLng latlng;
    private LocationRequest lr;
    private LocationClient lc;
    MapFragment mapFragment;
    ImageView iv;
    private static View view;

    public XYZ() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        if (view != null) {
            ViewGroup parent = (ViewGroup) view.getParent();
            if (parent != null)
                parent.removeView(view);
        }

        try {
            view = inflater.inflate(R.layout.XYZ, container,
                    false);

            mapFragment = ((MapFragment) this.getActivity()
                    .getFragmentManager().findFragmentById(R.id.map));
            iv = (ImageView) view.findViewById(R.id.iv);

            map = mapFragment.getMap();
            map.getUiSettings().setAllGesturesEnabled(false);
            map.getUiSettings().setMyLocationButtonEnabled(false);
            map.setMyLocationEnabled(true);
            map.getUiSettings().setZoomControlsEnabled(false);

            MapsInitializer.initialize(this.getActivity());
        } catch (GooglePlayServicesNotAvailableException e) {
            Toast.makeText(getActivity(), "Google Play Services missing !",
                    Toast.LENGTH_LONG).show();
        } catch (InflateException e) {
            Toast.makeText(getActivity(), "Problems inflating the view !",
                    Toast.LENGTH_LONG).show();
        } catch (NullPointerException e) {
            Toast.makeText(getActivity(), "Google Play Services missing !",
                    Toast.LENGTH_LONG).show();
        }

        return view;
    }
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        lr = LocationRequest.create();
        lr.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        lc = new LocationClient(this.getActivity().getApplicationContext(),
                this, this);
        lc.connect();
    }

    @Override
    public void onLocationChanged(Location l2) {
        CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(
                new LatLng(l2.getLatitude(), l2.getLongitude()), 15);
        map.animateCamera(cameraUpdate);
    }

    @Override
    public void onConnectionFailed(ConnectionResult arg0) {

    }

    @Override
    public void onConnected(Bundle connectionHint) {
        lc.requestLocationUpdates(lr, this);

    }

    @Override
    public void onDisconnected() {

    }
}

This is perfect working in my case.

M D
  • 47,665
  • 9
  • 93
  • 114
  • what is LocationClient here? – yuva ツ Feb 04 '14 at 07:31
  • @yuva LocationClient is the main entry point for location related APIs, such as location and geofence. and Connect and disconnect to Google Location Services. Request/remove location update callbacks.Request/remove geofences. More info [Go to this](http://developer.android.com/training/location/retrieve-current.html) – M D Feb 04 '14 at 07:33