我正在尝试从我的 WS 获取位置并更新我的 GoogleMap 片段中的标记,所以我正在做的是:
我的 HomeActivity 包含 2 个片段(2 个 GoogleMaps,其中一个具有 TileOverlay)。
在我的 GoogleMap 片段中,我试图从 OnCameraChangeListener 获取我的标记位置,以便在用户继续移动时添加标记。
我正在使用 EventBus 和 Okhttp 进行异步请求!
我的谷歌地图片段:
public class GoogleMapFragment extends FragmentBase {
@Override
public void onResume() {
mapView.onResume();
BusHelper.register(this); // Register the EventBus with my helper
super.onResume();
}
@Override
public void onPause() {
BusHelper.unregister(this); // Unregister the EventBus with my helper
super.onPause();
}
public GoogleMap.OnCameraChangeListener getCameraChangeListener() {
return new GoogleMap.OnCameraChangeListener() {
@Override
public void onCameraChange(CameraPosition cameraPosition) {
//those are corners of visible region
VisibleRegion visibleRegion = mMap.getProjection().getVisibleRegion();
LatLng farLeft = visibleRegion.farLeft;
LatLng farRight = visibleRegion.farRight;
LatLng nearLeft = visibleRegion.nearLeft;
LatLng nearRight = visibleRegion.nearRight;
double minY = nearLeft.latitude;
double minX = nearLeft.longitude;
double maxY = farRight.latitude;
double maxX = farRight.longitude;
//Send the WS Request to a manager who uses okhttp
ApiManager.getPositions(minX, minY, maxX, maxY);
}
};
}
//Receive the eventBus event
public void onEvent(GetPositionsEvent event) {
if (event.positions != null)
setMarkersByVisibleRegion(event.positions);
}
之后它将在 APIManager 中执行 WS 请求。
public class IMSApiManager {
private final static Gson gson = new Gson();
private static Positions mPositions;
/**
* @return Positions
*/
public static void getPositions(double minX, double minY, double maxX, double maxY) {
String TAG = "getPositions";
String wSRequest = AppConstants.REQUEST_POSITIONS
.replace("{vUser}", "CARREPH1")
.replace("{vMinX}", new BigDecimal(minX).toPlainString())
.replace("{vMinY}", new BigDecimal(minY).toPlainString())
.replace("{vMaxX}", new BigDecimal(maxX).toPlainString())
.replace("{vMaxY}", new BigDecimal(maxY).toPlainString());
try {
RestAsyncHttpClient.doGetRequest(wSRequest, new GetPositionsCallback() {
@Override
public void onFailure(Request request, IOException e) {
super.onFailure(request, e);
}
@Override
public void onResponse(Response response) throws IOException {
super.onResponse(response);
mPositions = gson.fromJson(response.body().charStream(), Positions.class);
BusHelper.post(new GetPositionsEvent(mPositions)); //Post the eventBus
}
});
} catch (IOException exp) {
LogHelper.error(TAG, "Error getting positions", exp);
}
}
}
我熟悉 Not on the mainThread 错误,但理论上这是可能的,如果不是我如何在不做片段的新实例的情况下添加标记。