那么今天我就来写一下第二种通过Android自带的API来获取经纬度的方法:
<!-- 允许程序访问CellID或WiFi热点来获取粗略的位置 -->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<!-- 用于访问GPS定位 -->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
// 获取位置服务
String serviceName = Context.LOCATION_SERVICE;
// 调用getSystemService()方法来获取LocationManager对象
locationManager = (LocationManager) getSystemService(serviceName);
// 指定LocationManager的定位方法
String provider = LocationManager.GPS_PROVIDER;
// 调用getLastKnownLocation()方法获取当前的位置信息
Location location = locationManager.getLastKnownLocation(provider);
//获取纬度
double lat = location.getLatitude();
//获取经度
double lng = location.getLongitude();
通常情况下到这里我们已经通过Android自带的API获取到了经纬度,但是有的时候会获取不到,或者我们需要获取连续的点位信息,下面我就来写一下如何获取连续的点位信息,同时我们可以通过这种方式来避免获取点位失败的问题。
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 3000, 0, mLocationListener01);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 3000, 0, mLocationListener01);
mLocationListener01 = new LocationListener() {
@Override
public void onProviderDisabled(String provider) {
updateToNewLocation(null);
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onLocationChanged(Location location) {
//调用更新位置
updateToNewLocation(location);
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
};
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获取经纬度就写到这里,以后如果仅仅是获取经纬度的话可以不用集成第三方的东西了,希望对大家有所帮助。