Skip to content

Commit

Permalink
Support styleString as "Documents directory/Temporary directory" abso…
Browse files Browse the repository at this point in the history
…lute path (#520)

* iOS: Allow absolute path at styleString

* Android: Allow absolute path at styleString

Additional: change deprecated deprecated "fromUrl" method to "fromUri" (https://docs.mapbox.com/archive/android/maps/api/9.3.0/com/mapbox/mapboxsdk/maps/Style.Builder.html#fromUrl-java.lang.String-)

* Add local style example

* Add "style as absolute path" instruction into README

Co-authored-by: Tobrun <tobrun.van.nuland@gmail.com>
  • Loading branch information
bahung1221 and tobrun authored Feb 12, 2021
1 parent 27de579 commit d083d12
Show file tree
Hide file tree
Showing 7 changed files with 101 additions and 12 deletions.
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,8 @@ Map styles can be supplied by setting the `styleString` in the `MapOptions`. The

1. Passing the URL of the map style. This can be one of the built-in map styles, also see `MapboxStyles` or a custom map style served remotely using a URL that start with 'http(s)://' or 'mapbox://'
2. Passing the style as a local asset. Create a JSON file in the `assets` and add a reference in `pubspec.yml`. Set the style string to the relative path for this asset in order to load it into the map.
3. Passing the raw JSON of the map style. This is only supported on Android.
3. Passing the style as a local file. create an JSON file in app directory (e.g. ApplicationDocumentsDirectory). Set the style string to the absolute path of this JSON file.
4. Passing the raw JSON of the map style. This is only supported on Android.

## Offline Sideloading

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -269,20 +269,23 @@ public void onMapReady(MapboxMap mapboxMap) {

@Override
public void setStyleString(String styleString) {
//check if json, url or plain string:
// Check if json, url, absolute path or asset path:
if (styleString == null || styleString.isEmpty()) {
Log.e(TAG, "setStyleString - string empty or null");
} else if (styleString.startsWith("{") || styleString.startsWith("[")) {
mapboxMap.setStyle(new Style.Builder().fromJson(styleString), onStyleLoadedCallback);
} else if (styleString.startsWith("/")) {
// Absolute path
mapboxMap.setStyle(new Style.Builder().fromUri("file://" + styleString), onStyleLoadedCallback);
} else if (
!styleString.startsWith("http://") &&
!styleString.startsWith("https://")&&
!styleString.startsWith("http://") &&
!styleString.startsWith("https://")&&
!styleString.startsWith("mapbox://")) {
// We are assuming that the style will be loaded from an asset here.
String key = MapboxMapsPlugin.flutterAssets.getAssetFilePathByName(styleString);
mapboxMap.setStyle(new Style.Builder().fromUri("asset://" + key), onStyleLoadedCallback);
} else {
mapboxMap.setStyle(new Style.Builder().fromUrl(styleString), onStyleLoadedCallback);
mapboxMap.setStyle(new Style.Builder().fromUri(styleString), onStyleLoadedCallback);
}
}

Expand Down
77 changes: 77 additions & 0 deletions example/lib/local_style.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:mapbox_gl/mapbox_gl.dart';
import 'package:path_provider/path_provider.dart';

import 'main.dart';
import 'page.dart';

class LocalStylePage extends ExamplePage {
LocalStylePage()
: super(const Icon(Icons.map), 'Local style');

@override
Widget build(BuildContext context) {
return const LocalStyle();
}
}

class LocalStyle extends StatefulWidget {
const LocalStyle();

@override
State createState() => LocalStyleState();
}

class LocalStyleState extends State<LocalStyle> {
MapboxMapController mapController;
String styleAbsoluteFilePath;

@override
initState() {
super.initState();

getApplicationDocumentsDirectory().then((dir) async {
String documentDir = dir.path;
String stylesDir = '$documentDir/styles';
String styleJSON = '{"version":8,"name":"Basic","constants":{},"sources":{"mapillary":{"type":"vector","tiles":["https://d25uarhxywzl1j.cloudfront.net/v0.1/{z}/{x}/{y}.mvt"],"attribution":"<a href=\\"https://www.mapillary.com\\" target=\\"_blank\\">© Mapillary, CC BY</a>","maxzoom":14}},"sprite":"","glyphs":"","layers":[{"id":"background","type":"background","paint":{"background-color":"rgba(135, 149, 154, 1)"}},{"id":"water","type":"fill","source":"mapbox","source-layer":"water","paint":{"fill-color":"rgba(108, 148, 120, 1)"}}]}';

await new Directory(stylesDir).create(recursive: true);

File styleFile = new File('$stylesDir/style.json');

await styleFile.writeAsString(styleJSON);

setState(() {
styleAbsoluteFilePath = styleFile.path;
});
});
}


void _onMapCreated(MapboxMapController controller) {
mapController = controller;
}

@override
Widget build(BuildContext context) {
if (styleAbsoluteFilePath == null) {
return Scaffold(
body: Center(child: Text('Creating local style file...')),
);
}

return new Scaffold(
body: MapboxMap(
accessToken: MapsDemo.ACCESS_TOKEN,
styleString: styleAbsoluteFilePath,
onMapCreated: _onMapCreated,
initialCameraPosition: const CameraPosition(target: LatLng(0.0, 0.0)),
onStyleLoadedCallback: onStyleLoadedCallback,
)
);
}

void onStyleLoadedCallback() {}
}
2 changes: 2 additions & 0 deletions example/lib/main.dart
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import 'animate_camera.dart';
import 'annotation_order_maps.dart';
import 'full_map.dart';
import 'line.dart';
import 'local_style.dart';
import 'map_ui.dart';
import 'move_camera.dart';
import 'page.dart';
Expand All @@ -29,6 +30,7 @@ final List<ExamplePage> _allPages = <ExamplePage>[
PlaceSymbolPage(),
PlaceSourcePage(),
LinePage(),
LocalStylePage(),
PlaceCirclePage(),
PlaceFillPage(),
ScrollingMapPage(),
Expand Down
1 change: 1 addition & 0 deletions example/pubspec.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ dependencies:
# Use with the CupertinoIcons class for iOS style icons.
cupertino_icons: ^0.1.2
location: ^2.5.3
path_provider: ^1.6.27
http:

dependency_overrides:
Expand Down
7 changes: 6 additions & 1 deletion ios/Classes/MapboxMapController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -827,19 +827,24 @@ class MapboxMapController: NSObject, FlutterPlatformView, MGLMapViewDelegate, Ma
mapView.maximumZoomLevel = max
}
func setStyleString(styleString: String) {
// Check if json, url or plain string:
// Check if json, url, absolute path or asset path:
if styleString.isEmpty {
NSLog("setStyleString - string empty")
} else if (styleString.hasPrefix("{") || styleString.hasPrefix("[")) {
// Currently the iOS Mapbox SDK does not have a builder for json.
NSLog("setStyleString - JSON style currently not supported")
} else if (styleString.hasPrefix("/")) {
// Absolute path
mapView.styleURL = URL(fileURLWithPath: styleString, isDirectory: false)
} else if (
!styleString.hasPrefix("http://") &&
!styleString.hasPrefix("https://") &&
!styleString.hasPrefix("mapbox://")) {
// We are assuming that the style will be loaded from an asset here.
let assetPath = registrar.lookupKey(forAsset: styleString)
mapView.styleURL = URL(string: assetPath, relativeTo: Bundle.main.resourceURL)


} else {
mapView.styleURL = URL(string: styleString)
}
Expand Down
12 changes: 6 additions & 6 deletions pubspec.lock
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ packages:
name: characters
url: "https://pub.dartlang.org"
source: hosted
version: "1.0.0"
version: "1.1.0-nullsafety.3"
charcode:
dependency: transitive
description:
Expand All @@ -35,7 +35,7 @@ packages:
name: collection
url: "https://pub.dartlang.org"
source: hosted
version: "1.14.13"
version: "1.15.0-nullsafety.3"
convert:
dependency: transitive
description:
Expand Down Expand Up @@ -105,7 +105,7 @@ packages:
name: meta
url: "https://pub.dartlang.org"
source: hosted
version: "1.1.8"
version: "1.3.0-nullsafety.3"
path:
dependency: transitive
description:
Expand All @@ -131,14 +131,14 @@ packages:
name: typed_data
url: "https://pub.dartlang.org"
source: hosted
version: "1.2.0"
version: "1.3.0-nullsafety.3"
vector_math:
dependency: transitive
description:
name: vector_math
url: "https://pub.dartlang.org"
source: hosted
version: "2.0.8"
version: "2.1.0-nullsafety.3"
xml:
dependency: transitive
description:
Expand All @@ -147,5 +147,5 @@ packages:
source: hosted
version: "4.5.1"
sdks:
dart: ">=2.9.0-14.0.dev <3.0.0"
dart: ">=2.10.0-110 <2.11.0"
flutter: ">=1.12.13+hotfix.4 <2.0.0"

0 comments on commit d083d12

Please sign in to comment.