Skip to content
This repository has been archived by the owner on Aug 8, 2023. It is now read-only.

Commit

Permalink
[android] - expose setStyleJson and getStyleJson
Browse files Browse the repository at this point in the history
  • Loading branch information
tobrun committed Aug 7, 2017
1 parent 466728b commit 11c855a
Show file tree
Hide file tree
Showing 8 changed files with 165 additions and 33 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -581,7 +581,7 @@ void onMapChange(int rawChange) {
try {
onMapChangedListener.onMapChanged(rawChange);
} catch (RuntimeException err) {
Timber.e("Exception (%s) in MapView.OnMapChangedListener: %s", err.getClass(), err.getMessage());
Timber.e(err, "Exception in MapView.OnMapChangedListener");
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1134,7 +1134,7 @@ private void setStyleUrl(@NonNull MapboxMapOptions options) {
}

/**
* Returns the map style currently displayed in the map view.
* Returns the map style url currently displayed in the map view.
*
* @return The URL of the map style
*/
Expand All @@ -1144,6 +1144,27 @@ public String getStyleUrl() {
return nativeMapView.getStyleUrl();
}

/**
* Loads a new map style from a json string.
* <p>
* If the style fails to load or an invalid style URL is set, the map view will become blank.
* An error message will be logged in the Android logcat and {@link MapView#DID_FAIL_LOADING_MAP} event will be
* sent.
* </p>
*/
public void setStyleJson(@NonNull String styleJson) {
nativeMapView.setStyleJson(styleJson);
}

/**
* Returns the map style json currently displayed in the map view.
*
* @return The json of the map style
*/
public String getStyleJson() {
return nativeMapView.getStyleJson();
}

//
// Annotations
//
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -687,7 +687,7 @@
android:label="@string/activity_bottom_sheet">
<meta-data
android:name="@string/category"
android:value="@string/category_basic"/>
android:value="@string/category_maplayout"/>
</activity>

<!-- For Instrumentation tests -->
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,10 +41,18 @@ protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.activity_debug_mode);

mapView = (MapView) findViewById(R.id.mapView);
mapView.addOnMapChangedListener(new MapView.OnMapChangedListener() {
@Override
public void onMapChanged(int change) {
if (change == MapView.DID_FINISH_LOADING_STYLE && mapboxMap != null) {
Timber.e("New loaded style = %s", mapboxMap.getStyleJson());
}
}
});

mapView.setTag(true);
mapView.setStyleUrl(STYLES[currentStyleIndex]);
mapView.onCreate(savedInstanceState);

mapView.getMapAsync(new OnMapReadyCallback() {
@Override
public void onMapReady(@NonNull MapboxMap map) {
Expand All @@ -63,13 +71,12 @@ public void onCameraChange(CameraPosition position) {
}
});


FloatingActionButton fabDebug = (FloatingActionButton) findViewById(R.id.fabDebug);
fabDebug.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (mapboxMap != null) {
Timber.d("Debug FAB: isDebug Active? %s" , mapboxMap.isDebugActive());
Timber.d("Debug FAB: isDebug Active? %s", mapboxMap.isDebugActive());
mapboxMap.cycleDebugOptions();
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.mapbox.mapboxsdk.testapp.activity.style;

import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.NonNull;
Expand All @@ -25,11 +26,12 @@
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;
import java.lang.ref.WeakReference;

import timber.log.Timber;

/**
* Test activity showcasing how to use a file:// resource for the style.json
* Test activity showcasing how to use a file:// resource for the style.json and how to use MapboxMap#setStyleJson.
*/
public class StyleFileActivity extends AppCompatActivity {

Expand All @@ -48,58 +50,96 @@ public void onCreate(Bundle savedInstanceState) {
public void onMapReady(@NonNull final MapboxMap map) {
mapboxMap = map;

FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab_file);
fab.setColorFilter(ContextCompat.getColor(StyleFileActivity.this, R.color.primary));
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Timber.i("Loading style file");
new CreateStyleFileTask().execute();
new CreateStyleFileTask(view.getContext(), mapboxMap).execute();
}
});

FloatingActionButton fabStyleJson = (FloatingActionButton) findViewById(R.id.fab_style_json);
fabStyleJson.setColorFilter(ContextCompat.getColor(StyleFileActivity.this, R.color.primary));
fabStyleJson.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
new LoadStyleFileTask(view.getContext(), mapboxMap).execute();
}
});
}
});
}

/**
* Task to read a style file from the raw folder
*/
private static class LoadStyleFileTask extends AsyncTask<Void, Void, String> {
private WeakReference<Context> context;
private WeakReference<MapboxMap> mapboxMap;

LoadStyleFileTask(Context context, MapboxMap mapboxMap) {
this.context = new WeakReference<>(context);
this.mapboxMap = new WeakReference<>(mapboxMap);
}

@Override
protected String doInBackground(Void... voids) {
String styleJson = "";
try {
styleJson = RawResourceReaderWriter.readRawResource(context.get(), R.raw.sat_style);
} catch (Exception exception) {
Timber.e(exception, "Can't load local file style");
}
return styleJson;
}

@Override
protected void onPostExecute(String json) {
super.onPostExecute(json);
Timber.d("Read json, %s", json);
MapboxMap mapboxMap = this.mapboxMap.get();
if (mapboxMap != null) {
mapboxMap.setStyleJson(json);
}
}
}

/**
* Task to write a style file to local disk and load it in the map view
*/
private class CreateStyleFileTask extends AsyncTask<Void, Integer, Long> {
private static class CreateStyleFileTask extends AsyncTask<Void, Integer, Long> {
private File cacheStyleFile;
private WeakReference<Context> context;
private WeakReference<MapboxMap> mapboxMap;

CreateStyleFileTask(Context context, MapboxMap mapboxMap) {
this.context = new WeakReference<>(context);
this.mapboxMap = new WeakReference<>(mapboxMap);
}

@Override
protected Long doInBackground(Void... params) {
try {
cacheStyleFile = File.createTempFile("my-", ".style.json");
cacheStyleFile.createNewFile();
Timber.i("Writing style file to: %s", cacheStyleFile.getAbsolutePath());
writeToFile(cacheStyleFile, readRawResource(R.raw.local_style));
Context context = this.context.get();
if (context != null) {
writeToFile(cacheStyleFile, RawResourceReaderWriter.readRawResource(context, R.raw.local_style));
}
} catch (Exception exception) {
Toast.makeText(StyleFileActivity.this, "Could not create style file in cache dir", Toast.LENGTH_SHORT).show();
Toast.makeText(context.get(), "Could not create style file in cache dir", Toast.LENGTH_SHORT).show();
}
return 1L;
}

protected void onPostExecute(Long result) {
// Actual file:// usage
mapboxMap.setStyleUrl("file://" + cacheStyleFile.getAbsolutePath());
}

private String readRawResource(@RawRes int rawResource) throws IOException {
InputStream is = getResources().openRawResource(rawResource);
Writer writer = new StringWriter();
char[] buffer = new char[1024];
try {
Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
int numRead;
while ((numRead = reader.read(buffer)) != -1) {
writer.write(buffer, 0, numRead);
}
} finally {
is.close();
MapboxMap mapboxMap = this.mapboxMap.get();
if (mapboxMap != null) {
mapboxMap.setStyleUrl("file://" + cacheStyleFile.getAbsolutePath());
}

return writer.toString();
}

private void writeToFile(File file, String contents) throws IOException {
Expand All @@ -115,6 +155,28 @@ private void writeToFile(File file, String contents) throws IOException {
}
}

static class RawResourceReaderWriter {
static String readRawResource(Context context, @RawRes int rawResource) throws IOException {
String json = "";
if (context != null) {
InputStream is = context.getResources().openRawResource(rawResource);
Writer writer = new StringWriter();
char[] buffer = new char[1024];
try {
Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
int numRead;
while ((numRead = reader.read(buffer)) != -1) {
writer.write(buffer, 0, numRead);
}
} finally {
is.close();
}
json = writer.toString();
}
return json;
}
}

@Override
protected void onStart() {
super.onStart();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,18 @@
app:mapbox_styleUrl="@string/mapbox_style_mapbox_streets"/>

<android.support.design.widget.FloatingActionButton
android:id="@id/fab"
android:id="@+id/fab_style_json"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_above="@+id/fab_file"
android:layout_margin="@dimen/fab_margin"
android:src="@drawable/ic_add"
app:backgroundTint="@android:color/white"/>

<android.support.design.widget.FloatingActionButton
android:id="@id/fab_file"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
{
"version": 8,
"name": "Satellite",
"metadata": {
"mapbox:autocomposite": true
},
"sources": {
"mapbox": {
"type": "raster",
"url": "mapbox://mapbox.satellite",
"tileSize": 256
}
},
"sprite": "mapbox://sprites/mapbox/satellite-v8",
"glyphs": "mapbox://fonts/mapbox/{fontstack}/{range}.pbf",
"layers": [
{
"id": "background",
"type": "background",
"paint": {
"background-color": "rgb(4,7,14)"
}
},
{
"id": "satellite",
"type": "raster",
"source": "mapbox",
"source-layer": "mapbox_satellite_full"
}
]
}
Original file line number Diff line number Diff line change
Expand Up @@ -187,8 +187,8 @@
<string name="dynamic_marker_chelsea_snippet">Stamford Bridge</string>
<string name="dynamic_marker_arsenal_title">Arsenal</string>
<string name="dynamic_marker_arsenal_snippet">Emirates Stadium</string>
<string name="debug_zoom">Zoom: %d</string>
<string name="viewcache_size">"ViewCache size %d"</string>
<string name="debug_zoom">Zoom: %.2f</string>
<string name="viewcache_size">ViewCache size %.2f</string>
<string name="latitude">Latitude</string>
<string name="min_value">-180</string>
<string name="longitude">Longitude</string>
Expand Down

0 comments on commit 11c855a

Please sign in to comment.