From 07076711f14cd7509d0480e0fe90e3d49d5cd0cc Mon Sep 17 00:00:00 2001 From: Zhao Gang Date: Fri, 22 Feb 2019 15:52:24 +0800 Subject: [PATCH] Use wikimedia tiles and support localization on nearby map (#2335) Wikimedia tiles support adding a "?lang=xx" suffix to tiles url to set preferred language. Use this feature to set the preferred language to user's default Locale. --- .../nrw/commons/nearby/NearbyMapFragment.java | 35 +++++++++++++++++-- 1 file changed, 33 insertions(+), 2 deletions(-) diff --git a/app/src/main/java/fr/free/nrw/commons/nearby/NearbyMapFragment.java b/app/src/main/java/fr/free/nrw/commons/nearby/NearbyMapFragment.java index 48228eab0f..35112d1e00 100644 --- a/app/src/main/java/fr/free/nrw/commons/nearby/NearbyMapFragment.java +++ b/app/src/main/java/fr/free/nrw/commons/nearby/NearbyMapFragment.java @@ -45,9 +45,13 @@ import com.mapbox.mapboxsdk.maps.MapboxMap; import com.mapbox.mapboxsdk.maps.MapboxMapOptions; +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.List; +import java.util.Locale; import javax.inject.Inject; import javax.inject.Named; @@ -505,16 +509,44 @@ public void onSlide(@NonNull View bottomSheet, float slideOffset) { }); } + private String getLocaleMapStyleJson() { + String styleFileName = "mapstyle.json"; + String suffix = "png\""; + StringBuilder styleJson = new StringBuilder(4096); + String language = Locale.getDefault().getLanguage(); + + try { + BufferedReader reader = new BufferedReader(new InputStreamReader(getActivity().getAssets().open(styleFileName))); + String line = reader.readLine(); + while (line != null) { + if (line.endsWith(suffix)) { + String newSuffix = suffix.replace("\"", String.format("?lang=%s\"", language)); + styleJson.append(line.replace(suffix, newSuffix)); + Timber.d("Localized tiles url: %s", line.replace(suffix, newSuffix)); + } else { + styleJson.append(line); + } + + line = reader.readLine(); + } + } catch (IOException e){ + Timber.e(e, "failed to read file: %s", styleFileName); + } + + return styleJson.toString(); + } + /** * Sets up map view of first time it created, it passes MapBoxMap options and style assets. * @param savedInstanceState bundle coming from Nearby Fragment */ private void setupMapView(Bundle savedInstanceState) { Timber.d("setupMapView called"); + String styleJson = getLocaleMapStyleJson(); MapboxMapOptions options = new MapboxMapOptions() .compassGravity(Gravity.BOTTOM | Gravity.LEFT) .compassMargins(new int[]{12, 0, 0, 24}) - .styleUrl(Style.OUTDOORS) + .styleJson(styleJson) .logoEnabled(false) .attributionEnabled(false) .camera(new CameraPosition.Builder() @@ -531,7 +563,6 @@ private void setupMapView(Bundle savedInstanceState) { addMapMovementListeners(); updateMapSignificantlyForCurrentLocation(); }); - mapView.setStyleUrl("asset://mapstyle.json"); } }