Android定位获取经纬度并显示位置

来源:互联网 发布:aoi编程手册 编辑:程序博客网 时间:2024/04/29 12:31

今天给了个要获取用户当前位置信息的功能,就结合着网上的资料写了一点。

public void getLocation() {locManger = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);Location loc = locManger.getLastKnownLocation(LocationManager.GPS_PROVIDER);//如果GPS没有打开,则调用网络定位if (loc == null) {loc = locManger.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);}//最小刷新时间为5秒,最小刷新距离为100米locManger.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 5000, 100, locationListener);}

位置监听器

private LocationListener locationListener = new LocationListener() {@Overridepublic void onStatusChanged(String provider, int status, Bundle extras) {}@Overridepublic void onProviderEnabled(String provider) {}@Overridepublic void onProviderDisabled(String provider) {updateWithNewLocation(null);}@Overridepublic void onLocationChanged(Location location) {updateWithNewLocation(location);}};

通过获取到的Location对象的经纬度,来获取位置信息

private void updateWithNewLocation(Location location) {String latLongString;if (location != null) {double lat = location.getLatitude();double lng = location.getLongitude();Geocoder geocoder = new Geocoder(getActivity());List places = null;try {places = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 5);System.out.println(places.size() + "");} catch (Exception e) {e.printStackTrace();}String placename = "";if (places != null && places.size() > 0) {// placename=((Address)places.get(0)).getLocality();// 一下的信息将会具体到某条街// 其中getAddressLine(0)表示国家,getAddressLine(1)表示精确到某个区,getAddressLine(2)表示精确到具体的街,实际使用的时候发现0的精度就已经不错placename = ((Address) places.get(0)).getAddressLine(0);//+ ((Address) places.get(0)).getAddressLine(1) + ", "//+ ((Address) places.get(0)).getAddressLine(2);}latLongString = "纬度:" + lat + "     经度:" + lng;tvPosition.setText("当前位置:" + placename);} else {tvPosition.setText("无法获取地理信息");}}


在销毁的时候,关闭监听器,防止一些bug

@Overridepublic void onDetach() {super.onDetach();locManger.removeUpdates(locationListener);}



0 0