如何使用Polyline Manager移除地图上的折线?
问题分析与解决方案
问题出在PolylineManager和Collection的生命周期管理上:每次onDataChange回调触发时,你都创建了全新的PolylineManager和Collection实例。之前绘制在地图上的折线属于旧的实例,调用新实例的clear()方法根本无法影响到旧实例管理的折线,所以折线会一直保留。
修复步骤
- 将
PolylineManager和Collection声明为类的成员变量,确保整个生命周期内使用同一个实例。 - 在
onDataChange开头先调用clear()清除旧折线,再添加新的折线数据。
修改后的代码示例
// 声明为类成员变量 private PolylineManager mPolylineManager; private PolylineManager.Collection mPolylineCollection; // 在初始化地图的地方(比如onMapReady)初始化实例 @Override public void onMapReady(GoogleMap googleMap) { mGoogleMap = googleMap; mPolylineManager = new PolylineManager(mGoogleMap); mPolylineCollection = mPolylineManager.newCollection(); // 初始化Firebase监听 DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("encoded_polyline"); ref.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { // 先清除旧折线 mPolylineCollection.clear(); for (DataSnapshot ds : dataSnapshot.getChildren()) { String encodedPolyline = ds.child("polyline").getValue().toString(); List<LatLng> decodedPolyline = PolyUtil.decode(encodedPolyline); mPolylineCollection.addPolyline(new PolylineOptions().addAll(decodedPolyline)); } } @Override public void onCancelled(@NonNull DatabaseError error) { // 处理取消事件,比如打印错误信息 Log.e("Firebase", "监听取消: " + error.getMessage()); } }); }
额外注意点
- 确保在地图初始化完成后(比如
onMapReady回调中)创建PolylineManager实例,避免mGoogleMap为空。 - 原代码中
encodedPolyline赋值语句缺少分号,已在修复代码中补上。
内容的提问来源于stack exchange,提问作者Arthur Cross
相关产品推荐
相关产品推荐

