9

I'm trying to get the longitude and latitude for android, here is my code:

    LocationManager locationManager = (LocationManager)
            this_activity.getSystemService(Context.LOCATION_SERVICE);

    LocationListener locationListener = new MyLocationListener();
    locationManager.requestLocationUpdates(
            LocationManager.GPS_PROVIDER, 5000, 10, locationListener);




 public class MyLocationListener implements LocationListener {

    @Override
    public void onLocationChanged(Location loc) {
        longitude = Double.toString(loc.getLongitude());
        latitude = Double.toString(loc.getLatitude());
    }

    @Override
    public void onProviderDisabled(String provider) {}

    @Override
    public void onProviderEnabled(String provider) {}

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {}
}

Manifest Permissions:

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

I'm always getting 0.0s for longitude and latitude

Hassene Benammou
  • 369
  • 2
  • 4
  • 11

3 Answers3

5

except the permissions that @AshishPedhadiya mentioned you are listening only to the GPS provider.

LocationListener locationListener = new MyLocationListener();
locationManager.requestLocationUpdates(
        LocationManager.GPS_PROVIDER, 5000, 10, locationListener);

GPS does not work inside. So when you test your application it will practically always return the (0,0) location. You may want to listen to NETWORK_PROVIDER as well which in absent of the GPS location it estimates the location coming from cell towers and WiFi spots.

locationManager.requestLocationUpdates(
        LocationManager.NETWORK_PROVIDER, 5000, 10, locationListener);

Furthermore to get a quick geographic location check out the Application.getLastKnownLocation() method.

eldjon
  • 2,800
  • 2
  • 20
  • 23
  • it works with NETWORK_PROVIDER but I need internet connection and this doesn't use the GPS, I still have empty values if I don't connect to WIFI –  Sep 20 '14 at 17:47
2
<!-- Needed only if your app targets Android 5.0 (API level 21) or higher. -->
<uses-feature android:name="android.hardware.location.gps" />

You need to add permission request in the manifest file above 5.0 version as mentioned in Android developer portal

Source

Saurav Rastogi
  • 9,575
  • 3
  • 29
  • 41
1
<uses-permission android:name="android.permission.INTERNET" /> 
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
add this permission to your manifest file