1.获取当前定位
// 獲取當前位置
baiduMap.setMyLocationEnabled(true);
locationClient = new LocationClient(this);
initLocation();
MyLocationListener myLocationListener = new MyLocationListener();
locationClient.registerLocationListener(myLocationListener);
locationClient.start();
private void initLocation() {
LocationClientOption option = new LocationClientOption();
option.setLocationMode(LocationClientOption.LocationMode.Device_Sensors);
option.setOpenGps(true);
option.setCoorType(CoordType.BD09LL.name());
option.setScanSpan(1000);
option.setIsNeedAddress(true);
option.setIsNeedLocationDescribe(true);
option.setIsNeedLocationPoiList(true);
option.setLocationNotify(true);
option.setIgnoreKillProcess(false);
option.SetIgnoreCacheException(false);
option.setEnableSimulateGps(false);
option.setWifiCacheTimeOut(5 * 60 * 1000);
locationClient.setLocOption(option);
}
/**
* 獲取定位數據
*/
class MyLocationListener extends BDAbstractLocationListener {
@Override
public void onReceiveLocation(BDLocation bdLocation) {
// mapView銷毀后不再處理新接收的位置
if (bdLocation == null || mapView == null) {
return;
}
nowLatLng = new LatLng(bdLocation.getLatitude(), bdLocation.getLongitude());
if (isFirst) {
isFirst = false;
baiduMap.animateMapStatus(MapStatusUpdateFactory.newLatLng(nowLatLng));
lat = bdLocation.getLatitude();
lng = bdLocation.getLongitude();
province = bdLocation.getProvince();
city = bdLocation.getCity();
district = bdLocation.getDistrict();
address = bdLocation.getAddress().town + bdLocation.getStreet() + bdLocation.getAddress().streetNumber;
}
// 在地图上显示当前定位
MyLocationData locData = new MyLocationData.Builder()
.accuracy(bdLocation.getRadius())
.direction(bdLocation.getDirection())
.latitude(bdLocation.getLatitude())
.longitude(bdLocation.getLongitude())
.build();
baiduMap.setMyLocationData(locData);
}
}
- 实现SuggestionSearch
mSuggestionSearch = SuggestionSearch.newInstance();
- 监听EditText的TextChanged事件
mSuggestionSearch.requestSuggestion(new SuggestionSearchOption()
.keyword(s.toString()) // s是onTextChanged里面的字段
.city(city) // 这里的city是获取当前定位的city,若不限制城市搜索可以不设置
.citylimit(false) // 不限制城市
);
- 设置SuggestionSearch获取结果监听事件
mSuggestionSearch.setOnGetSuggestionResultListener(new OnGetSuggestionResultListener());
class OnGetSuggestionResultListener implements com.baidu.mapapi.search.sug.OnGetSuggestionResultListener{
@Override
public void onGetSuggestionResult(SuggestionResult suggestionResult) {
// 这里显示是用RecyclerView显示数据
if (suggestionResult != null && suggestionResult.getAllSuggestions() != null) {
list.clear();
for (SuggestionResult.SuggestionInfo info : suggestionResult.getAllSuggestions()) {
list.add(new LocationBean(info));
}
adapter.notifyDataSetChanged();
}
}
}