Search code examples
fluttergeojsonsyncfusion

Shape Sublayer on zoom | Syncfusion Map Flutter


I have problem with Syncfusion Map plugin in Flutter.

I have code look like this:

SfMaps(
  layers: [
    MapShapeLayer(
      source: mapSource,
      zoomPanBehavior: _zoomPanBehavior,
      sublayers: [
        MapShapeSublayer(
          source: sublayerSource,
          strokeColor: Colors.white,
        ),
      ],
      strokeColor: Colors.white,
    ),
  ],
);

This works fine, but I'd like to show MapShapeSublayer after ZoomLevel is greater than 2.0, for example.

Is it possible?


Solution

  • You can show MapShapeSublayer after the zoom level is greater than 2.0 using the OnWillZoom callback. The OnWillZoom has the zoom details. So, you can add sub layer when the zoom level is greater than 2.0. Attached are sample and code snippets for your reference.

    late MapShapeSource _shapeSource;
    late MapShapeSource _sublayerSource;
    late MapZoomPanBehavior _zoomPanBehavior;
    late List<MapSublayer> _sublayers;
    
    @override
    void initState() {
      _shapeSource = const MapShapeSource.asset(
        "assets/world_map.json",
        shapeDataField: "continent",
      );
    
      _sublayerSource = const MapShapeSource.asset(
        'assets/uk.json',
        shapeDataField: 'name',
      );
    
      _zoomPanBehavior = MapZoomPanBehavior();
      _sublayers = [];
      super.initState();
    }
    
    @override
    void dispose() {
      _sublayers.clear();
      super.dispose();
    }
    
    @override
    Widget build(BuildContext context) {
      return Scaffold(
        appBar: AppBar(
          title: Text(widget.title),
        ),
        body: SfMaps(
          layers: [
            MapShapeLayer(
              source: _shapeSource,
              zoomPanBehavior: _zoomPanBehavior,
              onWillZoom: _handleOnWillZoom,
              sublayers: _sublayers,
              strokeColor: Colors.white,
            ),
          ],
        ),
      );
    }
    
    bool _handleOnWillZoom(MapZoomDetails details) {
      setState(() {
        if (_sublayers.isEmpty && details.newZoomLevel! >= 2) {
          _sublayers.add(MapShapeSublayer(
            source: _sublayerSource,
            color: Colors.blue[100],
            strokeWidth: 1,
            strokeColor: Colors.blue[800],
          ));
        } else if (details.newZoomLevel! < 2) {
          _sublayers.clear();
        }
      });
           return true;
    }