Getting longitude and latitude values faster

非 Y 不嫁゛ 提交于 2019-12-12 01:16:22

问题


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!


回答1:


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();
}



回答2:


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




回答3:


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.



来源:https://stackoverflow.com/questions/14052143/getting-longitude-and-latitude-values-faster

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!