Karel Debedts
Karel Debedts

Reputation: 5768

Flutter google maps: update markers

I'm trying to update the coordinates of a marker (Google Maps flutter)

I'm 'creating' the marker like this.

 Map<MarkerId, Marker> markers = <MarkerId, Marker>{};

Uint8List resizedMarkerImageBytesTemp = await convertUserImage(
        "imgurl");

    MarkerId id = MarkerId(uid);
    Marker _marker = Marker(
      markerId: id,
      onTap: () {
        print("tapped");
      },
      position: LatLng(lat, lng),
      icon: BitmapDescriptor.fromBytes(resizedMarkerImageBytesTemp),
      infoWindow: InfoWindow(title: 'myTitle'),
    );
    setState(() {
      markers[id] = _marker;
    });

What's the best / most efficient way to update the coordinates of a marker?

Thanks!

UPDATE: I tried the following.

MarkerId id = MarkerId(uid); //uid of the marker I want to update

 markers[id].position.longitude = 3.12493;

But then I get the error:

error: 'longitude' can't be used as a setter because it is final.

Upvotes: 1

Views: 19156

Answers (2)

homayoun.azr
homayoun.azr

Reputation: 29

You can easily use this code anywhere you want to change the position:

setState((){markers[id]=markers[id].copyWith(positionParam:LatLng(yournewlat,your new long));});

You can even use it in marker on tap callback.

Upvotes: 1

Itamar Garcia
Itamar Garcia

Reputation: 906

You can create a function and pass the markerId to replace the actual marker:

   updateMarker(id){
 
  final marker = markers.values.toList().firstWhere((item) => item.markerId == id);

  Marker _marker = Marker(
   markerId: marker.markerId,
   onTap: () {
     print("tapped");
   },
   position: LatLng(marker.position.latitude, marker.position.longitude),
   icon: marker.icon,
   infoWindow: InfoWindow(title: 'my new Title'),
  );

 setState(() {
  //the marker is identified by the markerId and not with the index of the list
   markers[id] = _marker;
 });
}

Upvotes: 7

Related Questions