简体   繁体   English

使用 flutter package 在 Google 地图上添加和删除制造商

[英]Add and remove makers on Google maps using flutter maps flutter package

I need your help again我再次需要你的帮助

I have a google map using flutter_maps_package package on a web project.我在 web 项目上有一个使用flutter_maps_package package 的谷歌 map。 I receive location updates from node api and using web_socket_channel package.我从节点 api 并使用web_socket_channel package 接收位置更新。 The data comes through fine and I re-draw the polyline from one location to the updated location.数据很好,我将折线从一个位置重新绘制到更新的位置。 However clearing the markers and adding them again to updated locations doesn't work.但是,清除标记并将它们再次添加到更新的位置不起作用。

My approach is simple in addMarkers method we clear all markers and add them again with different latlng values.我的方法在 addMarkers 方法中很简单,我们清除所有标记并使用不同的 latlng 值再次添加它们。

class MapsDisplay extends StatefulWidget {      
  final Client client;
  const MapsDisplay(this.client, {Key? key}) : super(key: key);

  @override
  _MapsDisplayState createState() => _MapsDisplayState();
}

class _MapsDisplayState extends State<MapsDisplay> {
  GoogleMapController? _googleMapController;

  final LatLng _centralJakarta =
      const LatLng(-6.190661334599699, 106.82895257992107);
  final _channel = WebSocketChannel.connect(Uri.parse('ws://localhost:3000/'));
  List<Marker> _markers = [];

  List<PointLatLng>? _polylines;
  double? _distance;
  String? _driverId;

  @override
  void initState() {
    super.initState();
    initiateRequest(widget.client);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Stack(
        alignment: Alignment.center,
        children: [
          GoogleMap(
              myLocationEnabled: false,
              zoomControlsEnabled: false,
              initialCameraPosition:
                  CameraPosition(target: _centralJakarta, zoom: 15),
              markers: Set<Marker>.of(_markers),
              polylines: {
                if (_polylines != null)
                  Polyline(
                      polylineId: const PolylineId('diagonalLine'),
                      color: Colors.red,
                      width: 7,
                      points: _polylines!
                          .map((e) => LatLng(e.latitude, e.longitude))
                          .toList())
              },
              onMapCreated: (controller) => _googleMapController = controller),
          if (_driverId != null)
            Positioned(
                top: 20,
                child: Container(
                    height: 100,
                    width: 200,
                    child: Center(child: Text('km $_distance - $_driverId')),
                    decoration: BoxDecoration(
                        color: Colors.amberAccent,
                        borderRadius: BorderRadius.circular(20.0),
                        boxShadow: const [
                          BoxShadow(
                              color: Colors.black26,
                              offset: Offset(0, 2),
                              blurRadius: 6.0)
                        ]))),
        ],
      ),
    ); 
  }

  void initiateRequest(Client client) async {
    var body = client.toJson();
    _channel.sink.add(jsonEncode(body));

    _channel.stream.listen((data) {
      final Map<String, dynamic> result = jsonDecode(data);

      var userLocation = LatLng(result['userLocation']['latitude'],
          result['userLocation']['longitude']);

      var driverLocation = LatLng(result['nearestDriver']['latitude'],
          result['nearestDriver']['longitude']);

      _addMarkers(userLocation, driverLocation);
      _drawPolyline(userLocation, driverLocation);

      setState(() {
        _distance = result['nearestDriver']['distance'];
        _driverId = result['nearestDriver']['driverId'];
      });

      _googleMapController!.animateCamera(CameraUpdate.newCameraPosition(
          CameraPosition(target: driverLocation, zoom: 15)));
      });
  }

  void _drawPolyline(LatLng userLocation, LatLng driverLocation) {
    setState(() {
      _polylines = [
        PointLatLng(driverLocation.latitude, driverLocation.longitude),
        PointLatLng(userLocation.latitude, userLocation.longitude)
      ];
    });
  }

  void _addMarkers(LatLng userLocation, LatLng driverLocation) {
    setState(() {
      _markers.clear();
      _markers.add(Marker(
          markerId: const MarkerId('user'),
          infoWindow: const InfoWindow(title: 'Your Position'),
          icon:
              BitmapDescriptor.defaultMarkerWithHue(BitmapDescriptor.hueGreen),
          position: userLocation));
      _markers.add(Marker(
          markerId: const MarkerId('driver'),
          infoWindow: const InfoWindow(title: 'Nearest Driver Position'),
          icon:
              BitmapDescriptor.defaultMarkerWithHue(BitmapDescriptor.hueOrange),
          position: driverLocation));
    });
}

  @override
  void dispose() {
    _googleMapController!.dispose();
    super.dispose();
  }
}

Thanks again for all your help.再次感谢你的帮助。 Also if you have any other advice in terms of how I can improve this page pls advise.另外,如果您对如何改进此页面有任何其他建议,请提出建议。

Kind Regards:)亲切的问候:)

that's weird.这很奇怪。 a possible solution is every time you update your markers, pass a new key to the map:) this will force the map to rebuild.一个可能的解决方案是每次更新标记时,将新密钥传递给 map :) 这将强制 map 重建。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM