Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Center scroll wheel zoom on mouse pointer #1191

Merged
merged 6 commits into from
Mar 20, 2022
Merged
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 19 additions & 13 deletions lib/src/gestures/gestures.dart
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import 'dart:async';
import 'dart:math' as math;
import 'dart:math';

import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
Expand All @@ -27,18 +26,25 @@ abstract class MapGestureMixin extends State<FlutterMap>
void onPointerSignal(PointerSignalEvent pointerSignal) {
// Handle mouse scroll events if the enableScrollWheel parameter is enabled
if (pointerSignal is PointerScrollEvent &&
mapState.options.enableScrollWheel) {
if (pointerSignal.scrollDelta.dy != 0) {
// Check whether the mouse is scrolled down and calculate new zoom level
final delta = pointerSignal.scrollDelta.dy * (-0.01);
final zoom = delta > 0
? min(mapState.options.maxZoom ?? double.infinity,
mapState.zoom + delta)
: max(mapState.options.minZoom ?? 0, mapState.zoom + delta);
final newZoom = mapState.fitZoomToBounds(zoom);
// Move the map to the new zoom level
mapState.move(mapState.center, newZoom, source: MapEventSource.custom);
}
mapState.options.enableScrollWheel &&
pointerSignal.scrollDelta.dy != 0) {
// Calculate new zoom level
final minZoom = mapState.options.minZoom ?? 0.0;
final maxZoom = mapState.options.maxZoom ?? double.infinity;
final newZoom = (mapState.zoom + pointerSignal.scrollDelta.dy * -0.005)
.clamp(minZoom, maxZoom);
// Calculate offset of mouse cursor from viewport center
final cursorPos = CustomPoint(
pointerSignal.localPosition.dx, pointerSignal.localPosition.dy);
final viewCenter = mapState.originalSize! / 2;
final offset = (cursorPos - viewCenter).rotate(mapState.rotationRad);
// Match new center coordinate to mouse cursor position
final scale = mapState.getZoomScale(newZoom, mapState.zoom);
final newOffset = offset * (1.0 - 1.0 / scale);
final mapCenter = mapState.project(mapState.center);
final newCenter = mapState.unproject(mapCenter + newOffset);
// Move to new center and zoom level
mapState.move(newCenter, newZoom, source: MapEventSource.custom);
}
}

Expand Down