问题:在Android中,每4秒钟,我将从广播接收器接收节点的ArrayList(ArrayList< Node>),我必须根据刚收到的ArrayList单独更新标记的位置(谷歌地图上制作者的头衔是Id)。 Node类定义为:
Class Node{
public String Id;
public LatLng latlng;
public Node(String Id, LatLng latlng){
this.Id = Id;
this.latlng = latlng;
}
}
在0时,接收{A,B,}
4点钟,收到{A,C,}
8点钟,收到{B,C,D}
At 0s , receive {A, B,} : I will add these Nodes onto the Map individually.
At 4s , receive {A, C,} : then I have to update or remove them "individually"
A : update the location of marker A
B : remove marker B from the map
C : add marker C to the map
At 8s , receive {B, C, D} : then I have to update or remove them "individually"
A : remove marker A from the map
B : add marker B to the map
C : update the location of marker C
D : add marker C to the map
我通过使用两个HashMap找到了解决方案。是否有好的算法可以单独更新地图上的标记?
答案 0 :(得分:0)
我喜欢这个解决方案:
//MapPoint is your's Node
private Map<Long, MapPoint> mMovingPointsMap;
@Override
public void updateMovingPoints(Collection<? extends MapPoint> movingPoints) {
for(MapPoint mapPoint : movingPoints){
MapPoint pointOnMap = mMovingPointsMap.get(mapPoint.getId());
if(pointOnMap == null){
pointOnMap = mapPoint;
LatLng latLng = new LatLng(pointOnMap.getLatitude(), pointOnMap.getLongitude());
pointOnMap.setMarker(mGoogleMap.addMarker(new MarkerOptions()
.position(latLng)
.title("Isso é um carro")));
mMovingPointsMap.put(pointOnMap.getId(), pointOnMap);
} else{
Marker marker = pointOnMap.getMarker();
LatLng latLng = new LatLng(pointOnMap.getLatitude(), pointOnMap.getLongitude());
LatLngInterpolator latLngInterpolator = new LatLngInterpolator.Linear();
MarkerAnimation.animateMarkerToGB(marker, latLng, latLngInterpolator);
}
}
for(MapPoint mapPoint: mMovingPointsMap.values()) {
if(!movingPoints.contains(mapPoint)) {
mMovingPointsMap.remove(mapPoint)
}
}
}
说明:
您有一个包含所有节点的地图,您的节点的ID与地图的ID相同(您可以使用HashMap)。您应该将地图作为Iterable接收,而不是另一个地图。它将使您的代码更通用和可扩展。您不需要从服务器接收地图......您需要做的就是迭代所有新点并在地图中更新/创建您已有的地图。
来源:https://github.com/leandroBorgesFerreira/UpdatableMap
编辑:
正如Luke Lin所说,如果你正在寻找性能,这个算法会更适合你:
//MapPoint is your's Node
private Map<Long, MapPoint> mMovingPointsMap;
@Override
public void updateMovingPoints(Map<Long, ? extends MapPoint> movingPoints) {
for(MapPoint mapPoint : movingPoints.values()){
MapPoint pointOnMap = mMovingPointsMap.get(mapPoint.getId());
if(pointOnMap == null){
pointOnMap = mapPoint;
LatLng latLng = new LatLng(pointOnMap.getLatitude(), pointOnMap.getLongitude());
pointOnMap.setMarker(mGoogleMap.addMarker(new MarkerOptions()
.position(latLng)
.title("Isso é um carro")));
mMovingPointsMap.put(pointOnMap.getId(), pointOnMap);
} else{
Marker marker = pointOnMap.getMarker();
LatLng latLng = new LatLng(pointOnMap.getLatitude(), pointOnMap.getLongitude());
LatLngInterpolator latLngInterpolator = new LatLngInterpolator.Linear();
MarkerAnimation.animateMarkerToGB(marker, latLng, latLngInterpolator);
}
}
for(MapPoint mapPoint: mMovingPointsMap.values()) {
if(!movingPoints.contains(mapPoint)) {
mMovingPointsMap.remove(mapPoint)
}
}
}
您可以重载方法以使用这两种方法。
我希望我能帮忙!