GR75
GR75

Reputation: 11

Flutter google map maker ontap

I'm pretty new in Flutter. It is amazing. I'm working on small app usign google maps. I have 6 points (Markers) and need to recognize which one was selected. I've added ontap event into every marker with i-index (i = 0..5). When I tap/click on marker I always get 6. It should be 0..5 based on marker.

Thanx a lot, Gabriel

i=0;
marker.clear();
for (myPoint mar in globals.historia.items) {
  print(i.toString());
  marker.add(Marker(
    markerId: MarkerId(i.toString()),
    position: mar.pos,
    draggable: false,
    consumeTapEvents: true,
    onTap: () {
      print("Marker_id-${i.toString()}");
    },
  ));
  i++;
}

GoogleMap( onMapCreated: _onMapCreated, initialCameraPosition: CameraPosition( target: myposition, zoom: 17.0, ), polylines: road, markers: Set.of(marker),
)

Upvotes: 0

Views: 1035

Answers (1)

abd3llatif
abd3llatif

Reputation: 330

When onTap() is triggered it calls i with its last value that's == 6, that's why every time you tap on a marker, the print method prints 6. i is a global variable, that has its own address, so the print method will search for the value on that address every time onTap is called.

I propose this solution - replace youtr print method inside onTap with this : print("Marker_id-${globals.historia.items.indexOf(mar)}")

mar is a local variable inside the for in loop, and its value has never changed, so he will point on the same value, onTap will behave as you want.

Upvotes: 0

Related Questions