Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Batch create, batch delete for symbols #279

Merged
merged 4 commits into from
Jun 9, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 37 additions & 21 deletions android/src/main/java/com/mapbox/mapboxgl/MapboxMapController.java
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@
import com.mapbox.mapboxsdk.plugins.annotation.Line;
import com.mapbox.mapboxsdk.plugins.annotation.LineManager;
import com.mapbox.geojson.Feature;
import com.mapbox.mapboxsdk.plugins.annotation.SymbolOptions;
import com.mapbox.mapboxsdk.style.expressions.Expression;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
Expand Down Expand Up @@ -226,17 +227,6 @@ private CameraPosition getCameraPosition() {
return trackCameraPosition ? mapboxMap.getCameraPosition() : null;
}

private SymbolBuilder newSymbolBuilder() {
return new SymbolBuilder(symbolManager);
}

private void removeSymbol(String symbolId) {
final SymbolController symbolController = symbols.remove(symbolId);
if (symbolController != null) {
symbolController.remove(symbolManager);
}
}

private SymbolController symbol(String symbolId) {
final SymbolController symbol = symbols.get(symbolId);
if (symbol == null) {
Expand Down Expand Up @@ -556,18 +546,44 @@ public void onError(@NonNull String message) {
});
break;
}
case "symbol#add": {
final SymbolBuilder symbolBuilder = newSymbolBuilder();
Convert.interpretSymbolOptions(call.argument("options"), symbolBuilder);
final Symbol symbol = symbolBuilder.build();
final String symbolId = String.valueOf(symbol.getId());
symbols.put(symbolId, new SymbolController(symbol, true, this));
result.success(symbolId);
case "symbols#addAll": {
List<String> newSymbolIds = new ArrayList<String>();
final List<Object> options = call.argument("options");
List<SymbolOptions> symbolOptionsList = new ArrayList<SymbolOptions>();
if (options != null) {
SymbolBuilder symbolBuilder;
for (Object o : options) {
symbolBuilder = new SymbolBuilder();
Convert.interpretSymbolOptions(o, symbolBuilder);
symbolOptionsList.add(symbolBuilder.getSymbolOptions());
}
if (!symbolOptionsList.isEmpty()) {
List<Symbol> newSymbols = symbolManager.create(symbolOptionsList);
String symbolId;
for (Symbol symbol : newSymbols) {
symbolId = String.valueOf(symbol.getId());
newSymbolIds.add(symbolId);
symbols.put(symbolId, new SymbolController(symbol, true, this));
}
}
}
result.success(newSymbolIds);
break;
}
case "symbol#remove": {
final String symbolId = call.argument("symbol");
removeSymbol(symbolId);
case "symbols#removeAll": {
final ArrayList<String> symbolIds = call.argument("symbols");
SymbolController symbolController;

List<Symbol> symbolList = new ArrayList<Symbol>();
for(String symbolId : symbolIds){
symbolController = symbols.remove(symbolId);
if (symbolController != null) {
symbolList.add(symbolController.getSymbol());
}
}
if(!symbolList.isEmpty()) {
symbolManager.delete(symbolList);
}
result.success(null);
break;
}
Expand Down
8 changes: 3 additions & 5 deletions android/src/main/java/com/mapbox/mapboxgl/SymbolBuilder.java
Original file line number Diff line number Diff line change
Expand Up @@ -13,17 +13,15 @@
import com.mapbox.mapboxsdk.plugins.annotation.SymbolOptions;

class SymbolBuilder implements SymbolOptionsSink {
private final SymbolManager symbolManager;
private final SymbolOptions symbolOptions;
private static boolean customImage;

SymbolBuilder(SymbolManager symbolManager) {
this.symbolManager = symbolManager;
SymbolBuilder() {
this.symbolOptions = new SymbolOptions();
}

Symbol build() {
return symbolManager.create(symbolOptions);
public SymbolOptions getSymbolOptions(){
return this.symbolOptions;
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,10 @@ boolean onTap() {
return consumeTapEvents;
}

public Symbol getSymbol(){
return this.symbol;
}

void remove(SymbolManager symbolManager) {
symbolManager.delete(symbol);
}
Expand Down
69 changes: 59 additions & 10 deletions example/lib/place_symbol.dart
Original file line number Diff line number Diff line change
Expand Up @@ -89,18 +89,50 @@ class PlaceSymbolBodyState extends State<PlaceSymbolBody> {
}

void _add(String iconImage) {
controller.addSymbol(
SymbolOptions(
geometry: LatLng(
center.latitude + sin(_symbolCount * pi / 6.0) / 20.0,
center.longitude + cos(_symbolCount * pi / 6.0) / 20.0,
),
iconImage: iconImage,
List<int> availableNumbers = Iterable<int>.generate(12).toList();
controller.symbols.forEach(
(s) => availableNumbers.removeWhere((i) => i == s.data['count'])
);
if (availableNumbers.isNotEmpty) {
controller.addSymbol(
_getSymbolOptions(iconImage, availableNumbers.first),
{'count': availableNumbers.first}
);
setState(() {
_symbolCount += 1;
});
}
}

SymbolOptions _getSymbolOptions(String iconImage, int symbolCount){
return SymbolOptions(
geometry: LatLng(
center.latitude + sin(symbolCount * pi / 6.0) / 20.0,
center.longitude + cos(symbolCount * pi / 6.0) / 20.0,
),
iconImage: iconImage,
);
setState(() {
_symbolCount += 1;
});
}

Future<void> _addAll(String iconImage) async {
List<int> symbolsToAddNumbers = Iterable<int>.generate(12).toList();
controller.symbols.forEach(
(s) => symbolsToAddNumbers.removeWhere((i) => i == s.data['count'])
);

if (symbolsToAddNumbers.isNotEmpty) {
final List<SymbolOptions> symbolOptionsList = symbolsToAddNumbers.map(
(i) => _getSymbolOptions(iconImage, i)
).toList();
controller.addSymbols(
symbolOptionsList,
symbolsToAddNumbers.map((i) => {'count': i}).toList()
);

setState(() {
_symbolCount += symbolOptionsList.length;
});
}
}

void _remove() {
Expand All @@ -111,6 +143,14 @@ class PlaceSymbolBodyState extends State<PlaceSymbolBody> {
});
}

void _removeAll() {
controller.removeSymbols(controller.symbols);
setState(() {
_selectedSymbol = null;
_symbolCount = 0;
});
}

void _changePosition() {
final LatLng current = _selectedSymbol.options.geometry;
final Offset offset = Offset(
Expand Down Expand Up @@ -257,6 +297,11 @@ class PlaceSymbolBodyState extends State<PlaceSymbolBody> {
onPressed: () =>
(_symbolCount == 12) ? null : _add("airport-15"),
),
FlatButton(
child: const Text('add all'),
onPressed: () =>
(_symbolCount == 12) ? null : _addAll("airport-15"),
),
FlatButton(
child: const Text('add (custom icon)'),
onPressed: () => (_symbolCount == 12)
Expand All @@ -271,6 +316,10 @@ class PlaceSymbolBodyState extends State<PlaceSymbolBody> {
child: Text('${_iconAllowOverlap ? 'disable' : 'enable'} icon overlap'),
onPressed: _changeIconOverlap,
),
FlatButton(
child: const Text('remove all'),
onPressed: (_symbolCount == 0) ? null : _removeAll,
),
FlatButton(
child: const Text('add (asset image)'),
onPressed: () => (_symbolCount == 12)
Expand Down
56 changes: 36 additions & 20 deletions ios/Classes/MapboxMapController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -151,23 +151,22 @@ class MapboxMapController: NSObject, FlutterPlatformView, MGLMapViewDelegate, Ma
mapView.setCamera(camera, animated: true)
}
result(nil)
case "symbol#add":
case "symbols#addAll":
guard let symbolAnnotationController = symbolAnnotationController else { return }
guard let arguments = methodCall.arguments as? [String: Any] else { return }

// Parse geometry
if let options = arguments["options"] as? [String: Any],
let geometry = options["geometry"] as? [Double] {
// Convert geometry to coordinate and create symbol.
let coordinate = CLLocationCoordinate2DMake(geometry[0], geometry[1])
let symbol = MGLSymbolStyleAnnotation(coordinate: coordinate)
Convert.interpretSymbolOptions(options: arguments["options"], delegate: symbol)
// Load icon image from asset if an icon name is supplied.
if let iconImage = options["iconImage"] as? String {
addIconImageToMap(iconImageName: iconImage)

if let options = arguments["options"] as? [[String: Any]] {
var symbols: [MGLSymbolStyleAnnotation] = [];
for o in options {
if let symbol = getSymbolForOptions(options: o) {
symbols.append(symbol)
}
}
symbolAnnotationController.addStyleAnnotation(symbol)
result(symbol.identifier)
if !symbols.isEmpty {
symbolAnnotationController.addStyleAnnotations(symbols)
}

result(symbols.map { $0.identifier })
} else {
result(nil)
}
Expand All @@ -189,17 +188,18 @@ class MapboxMapController: NSObject, FlutterPlatformView, MGLMapViewDelegate, Ma
}
}
result(nil)
case "symbol#remove":
case "symbols#removeAll":
guard let symbolAnnotationController = symbolAnnotationController else { return }
guard let arguments = methodCall.arguments as? [String: Any] else { return }
guard let symbolId = arguments["symbol"] as? String else { return }
guard let symbolIds = arguments["symbols"] as? [String] else { return }
var symbols: [MGLSymbolStyleAnnotation] = [];

for symbol in symbolAnnotationController.styleAnnotations(){
if symbol.identifier == symbolId {
symbolAnnotationController.removeStyleAnnotation(symbol)
break;
if symbolIds.contains(symbol.identifier) {
symbols.append(symbol as! MGLSymbolStyleAnnotation)
}
}
symbolAnnotationController.removeStyleAnnotations(symbols)
result(nil)
case "symbol#getGeometry":
guard let symbolAnnotationController = symbolAnnotationController else { return }
Expand Down Expand Up @@ -327,7 +327,7 @@ class MapboxMapController: NSObject, FlutterPlatformView, MGLMapViewDelegate, Ma
guard let lineAnnotationController = lineAnnotationController else { return }
guard let arguments = methodCall.arguments as? [String: Any] else { return }
guard let lineId = arguments["line"] as? String else { return }

var reply: [Any]? = nil
for line in lineAnnotationController.styleAnnotations() {
if line.identifier == lineId {
Expand Down Expand Up @@ -358,6 +358,22 @@ class MapboxMapController: NSObject, FlutterPlatformView, MGLMapViewDelegate, Ma
}
}

private func getSymbolForOptions(options: [String: Any]) -> MGLSymbolStyleAnnotation? {
// Parse geometry
if let geometry = options["geometry"] as? [Double] {
// Convert geometry to coordinate and create symbol.
let coordinate = CLLocationCoordinate2DMake(geometry[0], geometry[1])
let symbol = MGLSymbolStyleAnnotation(coordinate: coordinate)
Convert.interpretSymbolOptions(options: options, delegate: symbol)
// Load icon image from asset if an icon name is supplied.
if let iconImage = options["iconImage"] as? String {
addIconImageToMap(iconImageName: iconImage)
}
return symbol
}
return nil
}

private func addIconImageToMap(iconImageName: String) {
// Check if the image has already been added to the map.
if self.mapView.style?.image(forName: iconImageName) == nil {
Expand Down
42 changes: 29 additions & 13 deletions lib/src/controller.dart
Original file line number Diff line number Diff line change
Expand Up @@ -321,13 +321,21 @@ class MapboxMapController extends ChangeNotifier {
/// The returned [Future] completes with the added symbol once listeners have
/// been notified.
Future<Symbol> addSymbol(SymbolOptions options, [Map data]) async {
final SymbolOptions effectiveOptions =
SymbolOptions.defaultOptions.copyWith(options);
final symbol =
await MapboxGlPlatform.getInstance(_id).addSymbol(effectiveOptions);
_symbols[symbol.id] = symbol;
List<Symbol> result = await addSymbols([options], [data]);

return result.first;
}


Future<List<Symbol>> addSymbols(List<SymbolOptions> options, [List<Map> data]) async {
final List<SymbolOptions> effectiveOptions = options.map(
(o) => SymbolOptions.defaultOptions.copyWith(o)
).toList();

final symbols = await MapboxGlPlatform.getInstance(_id).addSymbols(effectiveOptions, data);
symbols.forEach((s) => _symbols[s.id] = s);
notifyListeners();
return symbol;
return symbols;
}

/// Updates the specified [symbol] with the given [changes]. The symbol must
Expand Down Expand Up @@ -368,7 +376,17 @@ class MapboxMapController extends ChangeNotifier {
Future<void> removeSymbol(Symbol symbol) async {
assert(symbol != null);
assert(_symbols[symbol.id] == symbol);
await _removeSymbol(symbol.id);
await _removeSymbols([symbol.id]);
notifyListeners();
}

Future<void> removeSymbols(Iterable<Symbol> symbols) async {
assert(symbols.length > 0);
symbols.forEach((s) {
assert(_symbols[s.id] == s);
});

await _removeSymbols(symbols.map((s) => s.id));
notifyListeners();
}

Expand All @@ -381,9 +399,7 @@ class MapboxMapController extends ChangeNotifier {
Future<void> clearSymbols() async {
assert(_symbols != null);
final List<String> symbolIds = List<String>.from(_symbols.keys);
for (String id in symbolIds) {
await _removeSymbol(id);
}
_removeSymbols(symbolIds);
notifyListeners();
}

Expand All @@ -392,9 +408,9 @@ class MapboxMapController extends ChangeNotifier {
///
/// The returned [Future] completes once the symbol has been removed from
/// [_symbols].
Future<void> _removeSymbol(String id) async {
await MapboxGlPlatform.getInstance(_id).removeSymbol(id);
_symbols.remove(id);
Future<void> _removeSymbols(Iterable<String> ids) async {
await MapboxGlPlatform.getInstance(_id).removeSymbols(ids);
_symbols.removeWhere((k, s) => ids.contains(k));
}

/// Adds a line to the map, configured using the specified custom [options].
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -111,16 +111,16 @@ abstract class MapboxGlPlatform {
Future<bool> getTelemetryEnabled() async {
throw UnimplementedError('getTelemetryEnabled() has not been implemented.');
}

Future<Symbol> addSymbol(SymbolOptions options, [Map data]) async {
throw UnimplementedError('addSymbol() has not been implemented.');
Future<List<Symbol>> addSymbols(List<SymbolOptions> options, [List<Map> data]) async {
throw UnimplementedError('addSymbols() has not been implemented.');
}

Future<void> updateSymbol(Symbol symbol, SymbolOptions changes) async {
throw UnimplementedError('updateSymbol() has not been implemented.');
}

Future<void> removeSymbol(String symbolId) async {
Future<void> removeSymbols(Iterable<String> symbolsIds) async {
throw UnimplementedError('removeSymbol() has not been implemented.');
}

Expand Down
Loading