Home > Enterprise >  How to update marker position google maps flutter
How to update marker position google maps flutter

Time:03-03

I want to use a custom marker as user position. I am listening to location event and on each move I want to set new lat/lon on this marker. However I don't see any options to update markers position. How can I achieve this? I've tried removing the current marker and adding a new one, but there's ugly flash effect which I do not want.

  final marker = Marker(
        markerId: MarkerId('1'),
        position: LatLng(_latitude, _longitude),
        icon: await customIcon()
    );

    setState(() {
      _markers.add(marker);
    });
    _location.onLocationChanged.listen((event) async {
      //here I want to update the marker lat lng with new event.latitude and event.longitude
    });

CodePudding user response:

Try the following

_location.onLocationChanged.listen((event) async {
      final newMarker = Marker(
        markerId: MarkerId('1'),
        position: LatLng(event.latitude, event.longitude),
        icon: await customIcon()
      );

      final oldMarkerIndex = _markers.indexWhere((marker) => marker.markerId == MarkerId('1'));
      if(oldMarkerIndex > 0) { // If it exists
        setState(() { 
          _markers[oldMarkerIndex] = newMarker;
        });
      }
    });
  • Related