Reputation: 1419
I am using flutter_map to add a map to my project. I am able to work with it and use its options. But I want something that I did not find in flutter_map.
I want to listen to a position change and get the last position when the user stops touching the screen. Like the onTapUp or onLongPressUp in the GestureDetector widget.
There is onPositionChanged option in flutter_map but it gets called every time the position is changing, which is a lot. As soon as the user touched the screen, the onPositionChanged gets called until the user stops touching the screen. I can get the last position from this, but I want to call an API when the position changes to get the list of nearby cars. Calling API every time the onPositionChanged gets called is not good.
So I want to be able to call the API when the user finishes changing location (when he/she stops touching the screen).
Here is my flutter_map code:
FlutterMap(
key: Key('map'),
mapController: main.mapController,
options: MapOptions(
center: LatLng(main.lat, main.long),
zoom: 14,
maxZoom: 18,
minZoom: 10,
onPositionChanged: (mapPosition, boolValue){
_lastposition = mapPosition.center;
}),
layers: [
TileLayerOptions(
errorImage: AssetImage('images/login_icon.png'),
urlTemplate:
"https://maps.wikimedia.org/osm-intl/{z}/{x}/{y}.png",
// subdomains: ['a', 'b', 'c'],
// subdomains: ['', '1', '2', '3', '4']
),
MarkerLayerOptions(
markers: main.markersStart +
main.markersDestination +
main.driverMarkers,
),
],
),
Any help would be appreciated, thanks :).
Upvotes: 3
Views: 5536
Reputation: 5262
The easiest way I guess is to define a Timer
like so:
Timer? timer;
....
And then inside onPositionChanged
event, first reset it (actually reseting the old timer), then set it again. Using this, print
is called only once and 1 second after changing position ends
FlutterMap(
...
options: MapOptions(
onPositionChanged: (MapPosition position, bool hasGesture) {
timer?.cancel();
timer = Timer(Duration(milliseconds: 1000), () {
print(position);
});
}
),
...
)
Upvotes: 2
Reputation: 101
The best solution I found was to add a listener on MapEventStream
(check events here: map_events.dart)
MapController mapController;
StreamSubscription subscription;
@override
void initState() {
mapController = MapController();
mapController.onReady.then((_) {
subscription = mapController.mapEventStream.listen((MapEvent mapEvent) {
if (mapEvent is MapEventMoveStart) {
print(DateTime.now().toString() + ' [MapEventMoveStart] START');
// do something
}
if (mapEvent is MapEventMoveEnd) {
print(DateTime.now().toString() + ' [MapEventMoveStart] END');
// do something
}
});
});
super.initState();
}
@override
void dispose() {
subscription.cancel();
super.dispose();
}
Many thanks to this post that helps me
Upvotes: 9
Reputation: 298
You can use a timer, which executes only after a one second delay.
onPositionChanged: (mapPosition, boolValue) {
Timer(Duration(seconds: 1), () {}}
Upvotes: -1