![](/img/trans.png)
[英]Drawing line between 2+ markers/wievpoints (not dynamically) in a MapBox on Android
[英]Drawing markers after mapbox map loads in Android Studio [Java]
這是我在 Android Studio 中的第一個項目,基本上我正在嘗試使用 Mapbox 開發具有多個標記的 map。 所以,我的問題是,當在 map 上加載標記時,加載大約需要 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 中。 在車站 class 除了其他信息外,我還有緯度和經度坐標。
這是我的 addMarkers function:
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 加載。 我嘗試使用call.enqueue但之后我遇到了另一個問題,在我的 function 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.顯示map為空
2.加載后添加標記。
以這種方式,用戶不會經歷任何凍結。 歡迎任何想法如何解決這個問題。
由於問題是您希望應用程序不要等待同步 function,因此我建議為此使用異步任務。 然后,您可以在調用異步任務的onPostExecute
回調后執行addMarkers
function。 但請確保僅在您的addMarkers
中設置樣式后運行onMapReady
請參閱此文檔以了解如何使用異步任務: https://developer.android.com/reference/android/os/AsyncTask
使用異步任務獲得的好處是 Android 將在不同的線程中執行它,從而減輕主線程的負載。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.