收拾及中常用的获取位置信息的方法

整理及中常用的获取位置信息的方法
(1)

一般来讲,通过gps获取到经纬度坐标以后,要继续深入的获取该经纬度坐标的城市、街道与精度(误差)等信息。



private String getAddressbyGeoPoint() {

// 自经纬度取得地址

StringBuilder sb = new StringBuilder();

Geocoder gc = new Geocoder(getBaseContext(), Locale.getDefault());

List<Address> lstAddr = null;

try {

lstAddr = gc.getFromLocation(location.getLatitude(), location.getLongitude(), 1);

} catch (IOException e) {

Log.e("HangzhouBike", e.getMessage());

}

if (lstAddr != null && lstAddr.size() > 0) {

Address addr = lstAddr.get(0);

if (addr.getAddressLine(1) != null) {

sb.append(addr.getAddressLine(1)).append(" ");

}

if (addr.getAddressLine(2) != null){

sb.append(addr.getAddressLine(2)).append(" ");

sb.append(" ±" + location.getAccuracy() + "米");

}、

}

return sb.toString();

}

(2)

Android中LocationManager的提供了一系列方法来地理位置相关的问题,包括查询上一个已知位置;注册/注销来自某个 LocationProvider的周期性的位置更新;以及注册/注销接近某个坐标时对一个已定义Intent的触发等。今天我们就来看看Android 中LocatinManager的简单使用,以获取当前所在的位置为例。

首先,我们需要获取LocationManager的一个实例,这里需要注意的是他的实例只能通过下面这种方式来获取,直接实例化LocationManager是不被允许的。

Java代码
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);  
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

得到了LocationManager的实例locatonManager以后,我们通过下面的语句来注册一个周期性的位置更新。

Java代码
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,   
1000, 0, locationListener);  
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
1000, 0, locationListener);

这句代码告诉系统,我们需要从GPS获取位置信息,并且是每隔1000ms更新一次,并且不考虑位置的变化。最后一个参数是LocationListener的一个引用,我们必须要实现这个类。

Java代码
private final LocationListener locationListener = new LocationListener() {   
    public void onLocationChanged(Location location) { //当坐标改变时触发此函数,如果Provider传进相同的坐标,它就不会被触发   
        // log it when the location changes   
        if (location != null) {   
            Log.i("SuperMap", "Location changed : Lat: "  
              + location.getLatitude() + " Lng: "  
              + location.getLongitude());   
        }   
    }   
  
    public void onProviderDisabled(String provider) {   
    // Provider被disable时触发此函数,比如GPS被关闭   
    }   
  
    public void onProviderEnabled(String provider) {   
    //  Provider被enable时触发此函数,比如GPS被打开   
    }   
  
    public void onStatusChanged(String provider, int status, Bundle extras) {   
    // Provider的转态在可用、暂时不可用和无服务三个状态直接切换时触发此函数   
    }   
};  
private final LocationListener locationListener = new LocationListener() {
    public void onLocationChanged(Location location) { //当坐标改变时触发此函数,如果Provider传进相同的坐标,它就不会被触发
        // log it when the location changes
        if (location != null) {
            Log.i("SuperMap", "Location changed : Lat: "
              + location.getLatitude() + " Lng: "
              + location.getLongitude());
        }
    }

    public void onProviderDisabled(String provider) {
    // Provider被disable时触发此函数,比如GPS被关闭
    }

    public void onProviderEnabled(String provider) {
    //  Provider被enable时触发此函数,比如GPS被打开
    }

    public void onStatusChanged(String provider, int status, Bundle extras) {
    // Provider的转态在可用、暂时不可用和无服务三个状态直接切换时触发此函数
    }
};

以上的这些步骤一般应当在Activity的onCreate()阶段完成。

在成功注册了一个周期性坐标更新以后,我们就随时可以通过下面的方法来取得当前的坐标了。

Java代码
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);   
double latitude = location.getLatitude();     //经度   
double longitude = location.getLongitude(); //纬度   
double altitude =  location.getAltitude();     //海拔  
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
double latitude = location.getLatitude();     //经度
double longitude = location.getLongitude(); //纬度
double altitude =  location.getAltitude();     //海拔

不过这时候,如果你尝试去运行这个LocationSample的话程序启动时多半就会报错,因为我们没有设置GPS相关的权限,解决方法也相当简单,在AndroidManifest.xml中的block里添加下面这句即可解决权限的问题。详细的权限设置,请参考官方文档docs/reference/android/Manifest.permission.html

Java代码
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> 
(3)

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

criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_LOW);

provider = locationManager.getBestProvider(criteria,true);
if (provider != null) {
location = locationManager.getLastKnownLocation(provider);
/* TODO - adjust update times to minimize battery use. Can be changed as needed.
*
*/
locationManager.requestLocationUpdates(provider,
60000, // 1min
100, // 100m
locationListener);
}

Obviously you don't need to request location updates, but if you do then below is some code I use....


private final LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location newloc) {
// something to do here when location changes
// TODO get other datq (accuracy, velocity, altitude, etc...)
// write data to database
// add markers
location = newloc;

}
public void onProviderDisabled(String provider) {}
public void onProviderEnabled(String provider) {}
public void onStatusChanged(String provider, int status, Bundle extras) {}
};

and you need to remember to turn off/on the updating at onStart and onStop

@Override
public void onStop() {
super.onStop();
if (provider != null) {
locationManager.removeUpdates(locationListener);
}


@Override
public void onStart() {
super.onStart();

/* recheck which provider to use */
provider = locationManager.getBestProvider(criteria,true);
if (provider != null) {
location = locationManager.getLastKnownLocation(provider);
locationManager.requestLocationUpdates(provider,
60000, // 1min
100, // 100m
locationListener);
}

}