我正在尝试为驱动程序模型中的每个驱动程序添加标记,并将其加载到数组列表中。当我举起结果时,我得到了所有的驱动程序,但标记只显示了一个驱动程序。
请帮助我获取模块中每个驱动程序的标记。
//Add markers for all drivers retrieved
private void addMarkers(List<Driver> drivers) {
if (map != null && !drivers.isEmpty()) {
for (int i = 0; i < drivers.size(); i++) {
//Get driver model
Driver driver = drivers.get(i);
Toast.makeText(this, driver.toString(), Toast.LENGTH_LONG).show();
//Add marker
GeoPoint driverLocation = driver.getGeoPoint();
if (driverMarker == null) {
driverMarker = map.addMarker(new MarkerOptions()
.title(driver.getCarNumber())
.position(new LatLng(driverLocation.getLatitude(), driverLocation.getLongitude()))
);
driverMarker.showInfoWindow();
}
else{
driverMarker.remove();
driverMarker = map.addMarker(new MarkerOptions()
.title(driver.getCarNumber())
.position(new LatLng(driverLocation.getLatitude(), driverLocation.getLongitude()))
);
driverMarker.showInfoWindow();
}
}
}
}
答案 0 :(得分:0)
您只获得一个标记,因为您在代码中反复添加和删除相同的标记:
for (int i = 0; i < drivers.size(); i++) {
if (driverMarker == null) {
driverMarker = map.addMarker(...);
} else {
driverMarker.remove();
...
}
}
因此,您需要稍微更改代码以添加每个标记并将其保存到列表中。像这样:
private void addMarkers(List<Driver> drivers) {
List<Marker> markers = new ArrayList<>();
if (map != null && !drivers.isEmpty()) {
for (int i = 0; i < drivers.size(); i++) {
//Get driver model
Driver driver = drivers.get(i);
//Add marker
GeoPoint driverLocation = driver.getGeoPoint();
Marker driverMarker = map.addMarker(new MarkerOptions()
.title(driver.getCarNumber())
.position(new LatLng(driverLocation.getLatitude(), driverLocation.getLongitude())));
driverMarker.showInfoWindow();
// add to the list
markers.add(driverMarker);
}
}
return markers;
}
然后您可以使用该方法获取标记列表:
// assumet drivers is list of Driver
List<Marker> markers = addMarkers(drivers);