I am trying to get latitude
and longitude
but sometime network is available
but I am not getting value of latitude
and
See, this is a very common problem. In order to have exact Latitude and Longitude ,You must use GPS also it must me activated on the mobile device but GPS too have some limitations. GPS works most efficiently under open sky. you will not have a clear range inside a building. So try your code under open sky and check the response.
Here Best way to get Longitude Latitude:
/** PROCESS for Get Longitude and Latitude **/
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
// Define a listener that responds to location updates
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
// Called when a new location is found by the network location provider.
longitude = String.valueOf(location.getLongitude());
latitude = String.valueOf(location.getLatitude());
Log.d("msg", "changed Loc : "+longitude + ":"+latitude);
}
public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
};
// getting GPS status
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
// check if GPS enabled
if(isGPSEnabled){
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(location != null)
{
longitude = String.valueOf(location.getLongitude());
latitude = String.valueOf(location.getLatitude());
Log.d("msg", "Loc : "+longitude + ":"+latitude);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
}else
{
/*
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setCostAllowed(true);
String provider = locationManager.getBestProvider(criteria, true);
*/
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if(location != null)
{
longitude = String.valueOf(location.getLongitude());
latitude = String.valueOf(location.getLatitude());
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
}else
{
longitude = "0.00";
latitude = "0.00";
}
}
}
if device is not able to get currentLocation using GPS
then it'll be take fron NetworkProvider
or else it'll take 0,0 as my requirement but you can modify as per your requirement
May it'll helpful to you.
Happy Coding :D