Divyesh
Divyesh

Reputation: 33

Getting longitude and latitude values faster

I am developing an application in android and I want to get the latitude and longitude of the android mobile. My code for getting latitude and longitude is giving values after some time. And sometimes, it doesn't give values at all. Can anyone help me what can be done!

Upvotes: 0

Views: 1343

Answers (3)

Dany Y
Dany Y

Reputation: 7031

One quicker way would be to get the last known location getLastKnownLocation() and check if the time of this location is not far location.getTime(). Or use it until you get the real location.

Another tip is to use both GPS_PROVIDER and NETWORK_PROVIDER so your code will be like this :

    LocationManager locManager; 
    locManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE); 
/*call both providers , the quickest one will call the listener and in the listener you remove the locationUpdates*/
locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,0 ,0 , locationListener); 
    locManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,0 ,0 , locationListener);


    Location location = locManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); 
    /*check both providers even for lastKnownLocation*/
    if (location == null)
    {
     location = locManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); 
    }

    if(location != null) { 

    String lat = String.valueOf(location.getLatitude()); 
    v1.setText(lat); 
    String longi = String.valueOf(location.getLatitude()); 
    v2.setText(longi); 
    }

this is a simple example, a more elaborate solution would compare the newest lastKnownLocation between providers.

Upvotes: 0

Bhavdip Sagar
Bhavdip Sagar

Reputation: 1971

Please used last know location from your location service provider if you not get latest because

  • When your application is not running at that time some other application used location manager to get current location.

  • then once you start your application with location manager,what happen location manager basically take some time to prepare to send current location so at that time you have to get last know location from location provider,for that you have to design service in such way. once the location manager is stable then used those location.

this is best way.

Thank you Bhavdip

Upvotes: 0

user1914905
user1914905

Reputation:

You need to add this code for getting te current location. make sure you give all the permissions

Location Manager location =  locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(location!=null) 
{
 latitude = location.getLatitude();
 longitude = location.getLongitude();
}

Upvotes: 1

Related Questions