Reputation: 379
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
Upvotes: 9
Views: 17051
Reputation: 21
<!-- 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
Upvotes: 2
Reputation: 2840
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.
Upvotes: 5
Reputation: 458
<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
Upvotes: 1