在AndroidStudio[Java]中加载地图框地图后绘制标记



这是我在Android Studio中的第一个项目,基本上我正在尝试使用Mapbox开发一个带有多个标记的地图。因此,我的问题是,当在地图上加载标记时,加载大约3-5秒需要花费大量时间,并且应用程序会冻结,直到我从API调用中获得json。这是我给API的回复电话:

private void getNearbyStations() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("***")//my API, not relevant
.addConverterFactory(GsonConverterFactory.create())
.build();
jsonPlaceHolderApi = retrofit.create(JsonPlaceHolderApi.class);
Utilizator utilizator = Utilizator.getUtilizatorInstance();
Call<ResponseNearbyStations> call = jsonPlaceHolderApi.getNearbyStations(utilizator.getAuthentificationKey(), 47.1744354, 27.5746688);//Static Lat and Long for test, in future will use current location
try {
ResponseNearbyStations body = call.execute().body();
JsonObject jsonObject = body.getData();
JsonArray ja_data = jsonObject.getAsJsonArray("stationAround");
Station[] statiiPrimite = gson.fromJson(ja_data, Station[].class);
stationList = new ArrayList<>(Arrays.asList(statiiPrimite));
} catch (IOException e) {
e.printStackTrace();
}
}

我正在将我所有的电台保存在一个名为stationList的ArrayList中。在Station类中,除了其他信息外,我还有纬度和经度坐标。

这是我的addMarkers函数:

private void addMarkers(@NonNull Style loadedMapStyle) {
List<Feature> features = new ArrayList<>();
for(Station statie:stationList){    
features.add(Feature.fromGeometry(Point.fromLngLat(Double.valueOf(statie.getCoordinates().getLongitude()),
Double.valueOf(statie.getCoordinates().getLatitude()))));
}
loadedMapStyle.addSource(new GeoJsonSource(MARKER_SOURCE, FeatureCollection.fromFeatures(features)));
loadedMapStyle.addLayer(new SymbolLayer(MARKER_STYLE_LAYER, MARKER_SOURCE)
.withProperties(
PropertyFactory.iconAllowOverlap(true),
PropertyFactory.iconIgnorePlacement(true),
PropertyFactory.iconImage(MARKER_IMAGE),
PropertyFactory.iconOffset(new Float[]{0f, -52f})
));
}

因此,经过几次搜索,我发现这里的"问题"是我在getNearbyStations((中使用call.execute((,这不是异步的,所以主线程正在等待Stations加载。我试着使用调用.enque,但之后我遇到了另一个问题,在我的函数addMarkers中,我得到了NullPointerException,因为stationList没有足够的时间在中加载

for(Station statie:stationList){    
features.add(Feature.fromGeometry(Point.fromLngLat(Double.valueOf(statie.getCoordinates().getLongitude()),
Double.valueOf(statie.getCoordinates().getLatitude()))));
}

我想我必须使用某种线程来解决这个问题,但我是安卓工作室线程的初学者,我无法解决这个问题。我认为解决方案是:

1.显示地图空

2.加载后添加标记。

通过这种方式,用户不会经历任何冻结。任何解决这个问题的想法都是受欢迎的。

由于问题是希望应用程序不等待同步函数,因此我建议使用异步任务。一旦调用了异步任务的onPostExecute回调,就可以执行addMarkers函数。但请确保只有在onMapReady中设置了样式后才运行addMarkers

请参阅有关如何使用异步任务的文档:https://developer.android.com/reference/android/os/AsyncTask

使用aysnchronous任务的好副作用是,Android将在不同的线程中执行它,从而减轻主线程的负载。

最新更新