在很多APP中都会用到百度地图,以实现各种功能,本片文章介绍在百度地图中添加自定义覆盖物并添加其点击事件
public class NearByFragment extends Fragment {
private MapView mapView;
private BaiduMap Mmap;
private boolean isFirstLoc = true;
private HttpUtils utils;
private BitmapDisplayConfig displayConfig;
private BitmapUtils bmputils;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// 初始化控件,并开启定位功能
View view = initView(inflater, container);
//添加Marker覆盖物的点击事件
Mmap.setOnMarkerClickListener(new OnMarkerClickListener(){
@Override
public boolean onMarkerClick(Marker marker) {
Bundle extraInfo = marker.getExtraInfo();
final Grogshop shop = (Grogshop) extraInfo.getSerializable("Grogshop");
View v2 = LayoutInflater.from(getActivity()).inflate(R.layout.window2, null);
TextView shop_name = (TextView) v2.findViewById(R.id.shop_name);
TextView tv_distance = (TextView) v2.findViewById(R.id.distance);
TextView price_range = (TextView) v2.findViewById(R.id.price_range);
TextView worktime_window = (TextView) v2.findViewById(R.id.worktime_window);
ImageView view_img = (ImageView) v2.findViewById(R.id.view_img);
shop_name.setText(shop.getShopName());
bmputils.display(view_img, shop.getShopPhoto(), displayConfig);
final float distance_float = FunctionUtils.getDistance(shop, getActivity());
tv_distance.setText(distance_float + "km");
price_range.setText(shop.getPriceRange());
worktime_window.setText(shop.getBusinessTime());
v2.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// 加载新数据让他跳转到一个新的界面,展示信息
Intent intent = new Intent(getActivity(), NearByDetail.class);
intent.putExtra("Grogshop", shop);
intent.putExtra("distance_int", distance_float);
startActivity(intent);
getActivity().overridePendingTransition(R.anim.next_in_anim, R.anim.next_out_anim);
Mmap.hideInfoWindow();
}
});
FunctionUtils.PopView(v2);
int infoWindowYOffset = -30;
final InfoWindow info = new InfoWindow(v2, marker.getPosition(), infoWindowYOffset);
Mmap.showInfoWindow(info);
return true;
}
});
//添加地图的点击事件
Mmap.setOnMapClickListener(new OnMapClickListener() {
@Override
public void onMapClick(LatLng arg0) {
Mmap.hideInfoWindow();
}
@Override
public boolean onMapPoiClick(MapPoi arg0) {
// TODO Auto-generated method stub
return false;
}
});
return view;
}
// 为地图添加marker覆盖物
private void getoverlay() {
//为地图添加自定义的覆盖物
final BitmapDescriptor bitmap = BitmapDescriptorFactory.fromResource(R.drawable.icon_green);
utils.send(HttpMethod.POST, String.format(Constants.StringJson_shop, SPUtils.getString(getActivity(), "city", "")), new RequestCallBack() {
// 当请求失败调用此方法
@Override
public void onFailure(HttpException exception, String msg) {
exception.printStackTrace();
Log.i("NearByFragment", msg);
}
// 当请求接口成功调用此方法
@Override
public void onSuccess(ResponseInfo info) {
if (info.statusCode == 200) {
String json = info.result;
Log.e("NearByFragment", json);
// 以下解析json/封装list集合,再遍历list添加覆盖物
try {
JSONObject obj = new JSONObject(json);
String code = obj.getString("code");
String Message = obj.getString("message");
if (code.equals("000000")) {
List list = JsonUtils.JSON1Str(json);
if (adapter == null) {
if (getActivity() == null || getActivity().isDestroyed()) {
return;
} else {
adapter = new ShopAdapter(getActivity());
adapter.addData(list);
shop_list.setAdapter(adapter);
}
} else {
adapter.addData(list);
shop_list.setAdapter(adapter);
}
for (int i = 0; i < list.size(); i++) {
Grogshop shop = list.get(i);
// 利用bundle为覆盖物添加信息
Bundle bundle = new Bundle();
// 是否加盟
// String isJoining = shop.getIsJoining();
// 经纬度
double longitude = shop.getLongitude();
double dimensions = shop.getDimensions();
// 利用bundle逐一put进marker覆盖物
bundle.putSerializable("Grogshop", shop);
LatLng location = new LatLng(dimensions, longitude); op = new MarkerOptions().extraInfo(bundle).position(location).icon(bitmap);
MarkerOptions().extraInfo(bundle).position(location).icon(bitmap2);
// 将覆盖物添加到百度地图上
Mmap.addOverlay(op).setZIndex(i);
}
} else if (code.equals("000011")) {
if (getActivity() == null || getActivity().isDestroyed()) {
return;
} else {
Toast.makeText(getActivity(), Message, 0).show();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
});
}
private View initView(LayoutInflater inflater, ViewGroup container) {
View view = inflater.inflate(R.layout.fragment_nearby, container, false);
utils = new HttpUtils(5000);
bmputils = new BitmapUtils(getActivity(), Constants.cachepath);
displayConfig = new BitmapDisplayConfig();
displayConfig.setBitmapConfig(Config.ARGB_8888);
AlphaAnimation animation = new AlphaAnimation(0.1f, 1.0f);
animation.setDuration(500);
displayConfig.setAnimation(animation);
displayConfig.setLoadingDrawable(getActivity().getResources().getDrawable(R.drawable.loading_not));
displayConfig.setLoadFailedDrawable(getActivity().getResources().getDrawable(R.drawable.loading_not));
// 获取地图控件引用
mapView = (MapView) view.findViewById(R.id.bmapView);
// 隐藏百度地图缩放图标
mapView.showZoomControls(false);
// 获取百度地图控件
Mmap = mapView.getMap();
// 设置百度地图缩放层级
Mmap.setMapStatus(MapStatusUpdateFactory.newMapStatus(new MapStatus.Builder().zoom(15).build()));
//添加一个标志位避免频繁向服务器发请求 设置一个定时器避免请求数据为空
if (isFirstLoc) {
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
getoverlay();
isFirstLoc = false;
}
}, 2500);
}
return view;
}
@Override
public void onResume() {
super.onResume();
// 实现地图生命周期管理
mapView.onResume();
}
@Override
public void onPause() {
super.onPause();
mapView.onPause();
}
@Override
public void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
}
//百度定位监听
/**
*@author xuenan
*百度定位监听实现
*/
public class MyLocationLister implements BDLocationListener{
private Context context;
private BaiduMap Mmap;
private boolean isFirstLoc = true;
public MyLocationLister(BaiduMap mapView,Context context){
this.context = context;
this.Mmap = mapView;
}
@Override
public void onReceiveLocation(BDLocation location) {
final MyLocationData data = new MyLocationData.Builder()
.direction(location.getDirection())
.latitude(location.getLatitude())
.longitude(location.getLongitude())
.accuracy(location.getRadius())
.build();
if(data!=null){
// 设置地图的定位数据
try {
// 设置地图的定位数据
Mmap.setMyLocationData(data);
} catch (NullPointerException e) {
e.printStackTrace();
}
}
//Mmap.setMyLocationEnabled(true);
//城市
String city = location.getCity();
//将经纬度和城市,街道信息,存入SharedPreference中
SPUtils.putString(context,"latitude", String.valueOf(location.getLatitude()));
SPUtils.putString(context,"longitude", String.valueOf(location.getLongitude()));
SPUtils.putString(context,"city", String.valueOf(city));
SPUtils.putString(context, "AddrStr",location.getAddrStr());
// 更新地图状态
if (isFirstLoc) {
isFirstLoc = false;
LatLng pt = new LatLng(location.getLatitude(),
location.getLongitude());
MapStatusUpdate update = MapStatusUpdateFactory.newLatLng(pt);
Mmap.animateMapStatus(update);
}
}
}