FlutterMap -粘性标记不随Map移动

kyks70gy  于 2023-05-01  发布在  Flutter
关注(0)|答案(1)|浏览(104)

我需要在Map中心创建一个带有粘性标记的位置选择器。标记位置应始终位于Map中心,标记销应指示任何Map移动/缩放/滚动的当前锁定位置。
有人知道如何使用FlutterMap吗?

tf7tbtn2

tf7tbtn21#

您可以使用MapController来跟踪Map的中心,以获得标记的正确位置。

代码

下面是我在对话框中使用选择器做的一个例子:

class MapPickerDialog extends StatefulWidget {
  const MapPickerDialog({
    super.key,
    required this.initialLocation,
    this.initialZoom = 5,
    this.mapSize = const Size(300, 300),
  });

  /// Initial location of the map widget.
  final LatLng initialLocation;

  /// Initial zoom level of the map widget.
  ///
  /// Defaults to 5.
  final double initialZoom;

  /// Customize the size of the map widget.
  ///
  /// Defaults to 300x300.
  final Size mapSize;

  @override
  State<MapPickerDialog> createState() => _MapPickerDialogState();
}

class _MapPickerDialogState extends State<MapPickerDialog> {
  final mapController = MapController();

  late final pickedLocation = ValueNotifier<LatLng>(widget.initialLocation);

  @override
  void dispose() {
    pickedLocation.dispose();
    mapController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return AlertDialog(
      title: const Text('Pick a location'),
      content: SizedBox.fromSize(
        size: widget.mapSize,
        child: FlutterMap(
          mapController: mapController,
          options: MapOptions(
            center: widget.initialLocation,
            zoom: widget.initialZoom,
            onMapReady: () => pickedLocation.value = mapController.center,
            onPositionChanged: (_, __) {
              pickedLocation.value = mapController.center;
            },
          ),
          children: [
            TileLayer(
              urlTemplate: 'https://tile.openstreetmap.org/{z}/{x}/{y}.png',
              tileProvider: NetworkTileProvider(),
              userAgentPackageName: 'dev.fleaflet.flutter_map.example',
            ),
            ValueListenableBuilder<LatLng>(
              valueListenable: pickedLocation,
              builder: (context, location, _) {
                return MarkerLayer(
                  markers: [
                    Marker(
                      point: location,
                      builder: (_) => const Icon(Icons.location_on),
                    ),
                  ],
                );
              },
            ),
          ],
        ),
      ),
      actions: [
        TextButton(
          onPressed: () => Navigator.pop(context),
          child: const Text('Cancel'),
        ),
        TextButton(
          onPressed: () => Navigator.pop(context, pickedLocation.value),
          child: const Text('OK'),
        ),
      ],
    );
  }
}

截图

You can try the full example on zapp.run
(Full我是flutter_map repo的维护者之一)

相关问题