Get current lat long android

2019-04-16 19:43发布

I want to get the Location object on Button press. I know the LocationListener callbacks, however they execute only after a particular time or distance. I want to get Location instantaneously. Are there any methods to do so.

4条回答
在下西门庆
2楼-- · 2019-04-16 20:04

Try the following: https://github.com/delight-im/Android-SimpleLocation

If your location is enabled, you need just 3 lines of code:

SimpleLocation location = new SimpleLocation(this); //or context instead of this
double latitude = location.getLatitude();
double longitude = location.getLongitude();
查看更多
冷血范
3楼-- · 2019-04-16 20:15
public class GPSHelper {

    private Context context;
    // flag for GPS Status
    private boolean isGPSEnabled = false;
    // flag for network status
    private boolean isNetworkEnabled = false;
    private LocationManager locationManager;
    private Location location;
    private double latitude;
    private double longitude;

    public GPSHelper(Context context) {
        this.context = context;

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

    }   public void getMyLocation() {
        List<String> providers = locationManager.getProviders(true);

        Location l = null;
        for (int i = 0; i < providers.size(); i++) {
            l = locationManager.getLastKnownLocation(providers.get(i));
            if (l != null)
                break;
        }
        if (l != null) {
            latitude = l.getLatitude();
            longitude = l.getLongitude();
        }
    }

    public boolean isGPSenabled() {
        isGPSEnabled = locationManager
                .isProviderEnabled(LocationManager.GPS_PROVIDER);

        // getting network status
        isNetworkEnabled = locationManager
                .isProviderEnabled(LocationManager.NETWORK_PROVIDER);

        return (isGPSEnabled || isNetworkEnabled);
    }

    /**
     * Function to get latitude
     */
    public double getLatitude() {
        return latitude;
    }

    /**
     * Function to get longitude
     */
    public double getLongitude() {
        return longitude;
    }
查看更多
欢心
4楼-- · 2019-04-16 20:23

Use LocationManager class:

locationManager = (LocationManager)this.getSystemService(LOCATION_SERVICE);
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
    latitude=location.getLatitude();
    longitude=location.getLongitude();
    Log.d("old","lat :  "+latitude);
    Log.d("old","long :  "+longitude);
    this.onLocationChanged(location);
}   
查看更多
Bombasti
5楼-- · 2019-04-16 20:26

You are welcome to call getLastKnownLocation() on LocationManager to retrieve the last known location for your requested location provider. However:

  • that location may be old
  • that location may be null

Hence, your code will need to be able to cope with both of those scenarios.

查看更多
登录 后发表回答