Android获取经纬度

/ Android / 没有评论 / 1699浏览

Android获取经纬度

那么今天我就来写一下第二种通过Android自带的API来获取经纬度的方法:

private Location updateToNewLocation(Location location) {
    String latLongString;
    if (location != null) {
        lat = location.getLatitude();
        lng = location.getLongitude();
        if (locationManager != null) {
            locationManager.removeUpdates(mLocationListener01);
            locationManager = null;
        }
        if (mLocationListener01 != null) {
            mLocationListener01 = null;
        }
    } else {
        Toast.makeText(getApplicationContext(), "无法获取地理信息,请确认已开启定位权限并选择定位模式为GPS、WLAN和移动网络", Toast.LENGTH_SHORT).show();
    }
    return location;
}

这样我们就可以获取连续的点位信息了。 不过获取单个点位的时候我也建议使用这种方法,因为他可以避免Location为空的问题。 使用起来也很简单,只要我们获取到点位之后就停止继续获取点位就可以了 停止方法为

if (locationManager != null) {
    locationManager.removeUpdates(mLocationListener01);
    locationManager = null;
}
if (mLocationListener01 != null) {
    mLocationListener01 = null;
}

把这段代码加到我们自己写的更新函数里即可,代码如下

private Location updateToNewLocation(Location location) {
    String latLongString;
    if (location != null) {
        lat = location.getLatitude();
        lng = location.getLongitude();
        if (locationManager != null) {
            locationManager.removeUpdates(mLocationListener01);
            locationManager = null;
        }
        if (mLocationListener01 != null) {
            mLocationListener01 = null;
        }
    } else {
        Toast.makeText(getApplicationContext(), "无法获取地理信息,请确认已开启定位权限并选择定位模式为GPS、WLAN和移动网络", Toast.LENGTH_SHORT).show();
    }
    return location;
}

好了,Android获取经纬度就写到这里,以后如果仅仅是获取经纬度的话可以不用集成第三方的东西了,希望对大家有所帮助。