【发布时间】:2020-04-30 11:16:29
【问题描述】:
这是我在 Android Studio 中的第一个项目,基本上我正在尝试使用 Mapbox 开发具有多个标记的地图。所以,我的问题是在地图上加载标记时,加载大约需要 3-5 秒,并且应用程序会冻结,直到我从我的 API 调用中获取 json。 这是我对 API 的改造 2 调用:
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() 这不是异步的,所以主线程正在等待站点加载。我尝试使用 call.enqueue 但之后我遇到了另一个问题,在我的函数 addMarkers 中我得到 NullPointerException 因为 stationList 没有足够的时间加载
for(Station statie:stationList){
features.add(Feature.fromGeometry(Point.fromLngLat(Double.valueOf(statie.getCoordinates().getLongitude()),
Double.valueOf(statie.getCoordinates().getLatitude()))));
}
我猜我必须使用某种线程来解决这个问题,但我是在 Android Studio 中使用线程的初学者,我想不通。 我认为解决方案是:
1.显示地图为空
2.加载后添加标记。
通过这种方式,用户不会遇到任何冻结。欢迎任何想法如何解决这个问题。
【问题讨论】:
标签: java android mapbox mapbox-android mapbox-marker