Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,13 @@
- `MapAnimationController.markerDuration`: `MarkerDuration.fixed(duration)` or `MarkerDuration.adaptive(max: duration)`, where each move lasts as long as the time between positions. `markersAnimationDuration` still works and is a shortcut for `fixed`.

- Vehicle tracking: `MapAnimationController.trackVehicle(VehicleTracking(...))`, `updateVehicle(position)` and `stopTrackingVehicle(markerId)`. Positions are put on the route (searching around the last known distance first, so crossing routes and parallel streets do not cause jumps), the route is drawn as travelled and remaining (`RouteStyle`), `followRoute` makes the marker follow the route and turn at the corners, and `onOffRoute` reports positions beyond `snapToleranceMeters`.
- Animation control: `MapAnimationController.polylineAnimation(id)` returns a `PolylineAnimationHandle` with `pause()`, `resume()`, `seek(progress)`, `isPlaying`, `isCompleted`, `value`, a `progress` stream, `onComplete` and `onCycle`.
- `PolylineCodec.decode` and `PolylineCodec.encode` for the Google Encoded Polyline format, with precision 5 or 6.
- `MapAnimationUtils.boundsOf(points)`.

### Other

- Polyline animations now run on their own simulation, with the same timing as before, so they can be paused and resumed at any point.
- All markers share one ticker and the changes of a frame go to the map together. With 50 markers it is one map call per frame, as before, at about 170 µs per frame in the test harness.

## 1.1.0
Expand Down
38 changes: 38 additions & 0 deletions README.es.md
Original file line number Diff line number Diff line change
Expand Up @@ -224,6 +224,44 @@ mapAnimationController.stopTrackingVehicle(const MarkerId('driver'));
- Con varios vehículos, pasa el `markerId` a `updateVehicle`.
- Combínalo con `markerAnimationMode: MarkerAnimationMode.latestOnly` para seguimiento en vivo.

## Controla una animación en marcha

Pídele al controlador el handle de una polyline para pausarla, llevarla a un punto o seguir su progreso.

```dart
final animacion = mapAnimationController
.polylineAnimation(const PolylineId('front'));

animacion?.pause();
animacion?.seek(0.5); // salta a la mitad del ciclo
animacion?.resume();

animacion?.progress.listen((p) => print(p)); // de 0.0 a 1.0
animacion?.onComplete = () => mostrarLlegada();
animacion?.onCycle = (ciclo) => print('terminó la pasada $ciclo');
```

- `polylineAnimation` devuelve `null` si ese ID no tiene animación.
- El progreso es la posición dentro de un ciclo, en tiempo: incluye `delayStart` y `delayEnd` y se mide antes de la curva.
- `seek` sobre una animación en marcha la mantiene corriendo desde ahí. En una pausada o terminada se queda quieta hasta `resume`.
- `onComplete` no se llama en una animación que se repite para siempre, porque nunca termina. Para esas usa `onCycle`. Con `reverse`, ir y volver cuentan como una pasada cada uno, igual que en `repeatCount`.
- El handle deja de funcionar cuando se quita la polyline, se reemplaza su animator o se hace `dispose` del controlador.

## Utilidades

```dart
// Decodifica la ruta de una respuesta de Directions y ajusta la cámara.
final ruta = PolylineCodec.decode(respuesta.overviewPolyline);
controller.animateCamera(
CameraUpdate.newLatLngBounds(MapAnimationUtils.boundsOf(ruta), 50),
);

// Y de vuelta a texto, con 5 decimales (por defecto) o 6.
final texto = PolylineCodec.encode(ruta, precision: 6);
```

`PolylineCodec` lee y escribe el [formato de polyline codificada](https://developers.google.com/maps/documentation/utilities/polylinealgorithm). `boundsOf` no maneja rutas que cruzan el meridiano 180.

## Importante: no repitas IDs en `GoogleMap`

El controlador dibuja directamente sobre el mapa usando el `mapId`. Si el widget `GoogleMap` también recibe una polyline o un marcador con el mismo ID en sus `polylines` o `markers`, el widget sobrescribe lo que dibuja el controlador. Dale al controlador sus propios IDs y no los incluyas en los conjuntos del widget.
Expand Down
38 changes: 38 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -224,6 +224,44 @@ mapAnimationController.stopTrackingVehicle(const MarkerId('driver'));
- With several vehicles, pass the `markerId` to `updateVehicle`.
- Combine it with `markerAnimationMode: MarkerAnimationMode.latestOnly` for live tracking.

## Control a running animation

Ask the controller for the handle of a polyline to pause it, move it to a point or follow its progress.

```dart
final animation = mapAnimationController
.polylineAnimation(const PolylineId('front'));

animation?.pause();
animation?.seek(0.5); // jump to the middle of the cycle
animation?.resume();

animation?.progress.listen((p) => print(p)); // 0.0 to 1.0
animation?.onComplete = () => showArrived();
animation?.onCycle = (cycle) => print('pass $cycle finished');
```

- `polylineAnimation` returns `null` when that ID has no animation.
- Progress is the position inside one cycle, in time: it includes `delayStart` and `delayEnd` and is measured before the curve.
- `seek` on a playing animation keeps it playing from there. On a paused or finished one it stays put until `resume`.
- `onComplete` is not called for an animation that repeats forever, because it never ends. Use `onCycle` for those. With `reverse`, going and coming back are one pass each, the same as `repeatCount`.
- The handle stops working when the polyline is removed, its animator is replaced or the controller is disposed.

## Utilities

```dart
// Decode the route of a Directions response, and fit the camera to it.
final route = PolylineCodec.decode(response.overviewPolyline);
controller.animateCamera(
CameraUpdate.newLatLngBounds(MapAnimationUtils.boundsOf(route), 50),
);

// And back to text, with 5 decimals (the default) or 6.
final text = PolylineCodec.encode(route, precision: 6);
```

`PolylineCodec` reads and writes the [Encoded Polyline Algorithm Format](https://developers.google.com/maps/documentation/utilities/polylinealgorithm). `boundsOf` does not handle routes that cross the 180th meridian.

## Important: do not reuse IDs in `GoogleMap`

The controller draws directly on the map, using the `mapId`. If the `GoogleMap` widget also receives a polyline or marker with the same ID in its `polylines` or `markers`, the widget overwrites what the controller draws. Give the controller its own IDs and leave them out of the widget's sets.
Expand Down
26 changes: 2 additions & 24 deletions example/lib/main.dart
Original file line number Diff line number Diff line change
Expand Up @@ -31,26 +31,6 @@ class MapScreen extends StatefulWidget {
}

class _MapScreenState extends State<MapScreen> with TickerProviderStateMixin {
LatLngBounds _getBounds(List<LatLng> points) {
double? minLat, maxLat, minLng, maxLng;

for (final p in points) {
if (minLat == null) {
minLat = maxLat = p.latitude;
minLng = maxLng = p.longitude;
} else {
if (p.latitude < minLat) minLat = p.latitude;
if (p.latitude > maxLat!) maxLat = p.latitude;
if (p.longitude < minLng!) minLng = p.longitude;
if (p.longitude > maxLng!) maxLng = p.longitude;
}
}

return LatLngBounds(
southwest: LatLng(minLat!, minLng!),
northeast: LatLng(maxLat!, maxLng!),
);
}
GoogleMapController? mapController;
MapAnimationController? mapAnimationController;

Expand Down Expand Up @@ -115,10 +95,8 @@ class _MapScreenState extends State<MapScreen> with TickerProviderStateMixin {
polylines: _polylines,
);
// Move camera to show the whole polyline
final bounds = _getBounds(coordinates1);
controller.animateCamera(
CameraUpdate.newLatLngBounds(bounds, 50),
);
final bounds = MapAnimationUtils.boundsOf(coordinates1);
controller.animateCamera(CameraUpdate.newLatLngBounds(bounds, 50));
},
),
);
Expand Down
2 changes: 2 additions & 0 deletions lib/polyline_animation_plus.dart
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,7 @@ export 'src/animator/snack_animator.dart';
export 'src/controllers/map_animation_controller.dart';
export 'src/model/animated_polyline.dart';
export 'src/model/marker_animation.dart';
export 'src/model/polyline_animation_handle.dart';
export 'src/model/vehicle_tracking.dart';
export 'src/utils/polyline_codec.dart';
export 'src/utils/util.dart';
9 changes: 9 additions & 0 deletions lib/src/controllers/map_animation_controller.dart
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import '../managers/animated_marker_manager.dart';
import '../managers/animated_polyline_manager.dart';
import '../model/animated_polyline.dart';
import '../model/marker_animation.dart';
import '../model/polyline_animation_handle.dart';
import '../model/vehicle_tracking.dart';
import 'marker_controller.dart';
import 'tracked_vehicle.dart';
Expand Down Expand Up @@ -355,6 +356,14 @@ final class MapAnimationController {
_updatePolylinesOnMap(previous, _polylines.values.toSet());
}

/// The handle to pause, resume, seek and follow the animation of a polyline,
/// or `null` if that polyline is not being animated.
///
/// The handle stops working if the animator of the polyline is replaced, the
/// polyline is removed or the controller is disposed.
PolylineAnimationHandle? polylineAnimation(PolylineId polylineId) =>
_animatedPolylineManager.handleFor(polylineId);

/// Update Polyline directly on the map
/// This method is used to update a static polyline that does not have an animator.
/// Useful for update the polyline on marker update using [markerListener].
Expand Down
Loading
Loading