城市定位
1.城市定位的前提是你已经申请百度的Api的key,并已经在AndroidMainfest
里配置好的相关权限,以及百度地图的配置信息,接着我们在代码中介绍
如何城市定位
2. 在你所需要定位的地方,可以是Activity,fragment的onCreat()或者
onCreatView()中加入如下方法,在这次定位中我们首先要先获取当前地址
的经纬度,然后根据经纬度进行反地理编码得到其具体的地址:
public class EventsListFragment extends BaseFragment implements OnRefreshListener2<ListView>,
OnItemClickListener, OnGetGeoCoderResultListener {
private LocationClient mLocClient;
private MyLocationListenner myListener = new MyLocationListenner();
private GeoCoder mSearch = null; // 搜索模块,也可去掉地图模块独立使用
private boolean hasCity;
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
View layout = inflater.inflate(R.layout.fragment_events, container, false);
initLocation();//城市定位方法
return layout;
}
/**
* 初始化定位
*/
private void initLocation() {
// 定位初始化
mLocClient = new LocationClient(getActivity());
mLocClient.registerLocationListener(myListener);
LocationClientOption option = new LocationClientOption();
option.setOpenGps(true);// 打开gps
option.setCoorType("bd09ll"); // 设置坐标类型
option.setAddrType("detail"); // 设置了仍然获取不到详细地址
mLocClient.setLocOption(option);
mLocClient.start();
mLocClient.requestLocation();
// 初始化搜索模块,注册事件监听
mSearch = GeoCoder.newInstance();
mSearch.setOnGetGeoCodeResultListener(this);
}
}
@Override
public void onDestroy() {
super.onDestroy();
if (mLocClient != null) {
// 退出时销毁定位
mLocClient.stop();
}
}
3.定位SDK监听函数
/**
* 定位SDK监听函数
*/
public class MyLocationListenner implements BDLocationListener {
@Override
public void onReceiveLocation(BDLocation location) {
TipTools.dismissShowPrompt();
// map view 销毁后不再处理新接收的位置
if (location == null)
return;
// 获得用户的具体位置 经纬度
double userlongitude = location.getLongitude();
double userlatitude = location.getLatitude();
// 反地理编码
LatLng ptCenter = new LatLng(userlatitude, userlongitude);
// 反Geo搜索
mSearch.reverseGeoCode(new ReverseGeoCodeOption().location(ptCenter));
}
public void onReceivePoi(BDLocation poiLocation) {
}
}
4.重写反地理编码的方法
@Override
public void onGetGeoCodeResult(GeoCodeResult result) {
}
/**
* 反地理编码
*/
@Override
public void onGetReverseGeoCodeResult(ReverseGeoCodeResult result) {
AddressComponent addressDetail = result.getAddressDetail();// 得到详细的地址串
if (addressDetail == null) {
return;
}
String CurrentCity = addressDetail.city;// 得到所定位的城市
List<CityEntity> cityList = ((MyLingsActivity) getActivity()).getCityList();
// 如果城市列表中包含当前定位的城市,则定位到当前城市的活动
for (int i = 0; i < cityList.size(); i++) {
CityEntity city = cityList.get(i);
if (CurrentCity.contains(city.name)) {
mCityId = city.id;
hasCity = true;
((MyLingsActivity) getActivity()).setSpinnerAdapter(i);
TipTools.dismissShowPrompt();
return;
}
}
// 如果定位的城市不在城市列表中,则默认加载全国的活动列表
if (!hasCity) {
mCityId = 0;
((MyLingsActivity) getActivity()).setSpinnerAdapter(0);
TipTools.dismissShowPrompt();
}
}
注意:如果你有下载城市列表,可以在城市定位之前就下载好城市列表,
方便城市定位后去匹配你的城市列表。