-2

i am working on a google map activity. i am trying to get the current location.it works perfectly on emulator but not getting the current location on my phone. here is the code which i am using in my application...

locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    Criteria criteria = new Criteria();
    criteria.setAccuracy(Criteria.ACCURACY_FINE);
    provider = locationManager.getBestProvider(criteria, false);
    Location location = locationManager.getLastKnownLocation(provider);

    if (location != null) {
        double lat = (double) (location.getLatitude());
        double lng = (double) (location.getLongitude());

        Constants.lat = String.valueOf(lat);
        Constants.lng = String.valueOf(lng);
     }

Constants is the class where i have decalred the latitude and longitude static variables declared. This code is written in a function and it is call from onCreate method.I am getting null location everytime.I have declare below code also in manifestfile.

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

Can anybody please help me ? Thanks .

huk
  • 220
  • 3
  • 11

1 Answers1

1

Try out this code from the documentation.

    private void setUpMapIfNeeded() {
    // Do a null check to confirm that we have not already instantiated the map.
    if (mMap == null) {
        // Try to obtain the map from the SupportMapFragment.
        mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
                .getMap();
        mMap.setMyLocationEnabled(true);
        // Check if we were successful in obtaining the map.
        if (mMap != null) {


         mMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {

       @Override
       public void onMyLocationChange(Location arg0) {
        // TODO Auto-generated method stub

         mMap.addMarker(new MarkerOptions().position(new    LatLng(arg0.getLatitude(), arg0.getLongitude())).title("It's Me!"));
       }
      });

        }
    }
}

Call this function in your onCreate.Hope it helps.

Kristo
  • 1,339
  • 12
  • 22