Add municipality and coordinate search, and a map target selector

Puts the controls that change what the map is looking at over the map itself,
where they act, and gives them something to search.

Search is one field, not two. A string either parses as coordinates or it does
not, and the answer is obvious from the text, so making the user declare up
front which kind of thing they are looking for would be asking them to do the
program's job. Coordinates accept decimal and degrees-minutes-seconds, comma or
space separated, with hemisphere letters — including the Italian O for ovest,
because someone reading an Italian map will type it and silently reading it as
east would put them the wrong side of Greenwich.

The 1180 Piedmont municipalities are bundled rather than geocoded online. The
app is region-scoped, so a list of one region's towns is small enough to ship
(100 KB) and beats a geocoder on every axis that matters: instant, offline, no
API key, no rate limit, and it cannot return a result somewhere the app has no
radar for. Matching folds accents, so "aglie" finds "Agliè", and prefix matches
outrank substring ones — typing "tor" should surface Torino, not the first
alphabetical name that happens to contain those letters.

tool/generate_places.py derives the list from Istat boundary shapefiles
(CC BY 4.0). Two properties of that file cost time and are now written down:
the geometry is UTM 32N rather than degrees, and the DBF is UTF-8 despite one
bilingual Friulian record that makes strict cp1252 fail. A terminal renders
utf-8 and latin-1 output identically, so the encoding cannot be settled by
looking at printed text — it took dumping codepoints. A guard in the generator
and a test against the shipped asset both check for mojibake now, and the guard
caught a real mistake the moment it was written.

The target selector switches between following the device, a saved place, and
the whole region, and the selection doubles as what the app reopens on: "the
place I marked" and "what I see when I open the app" are one idea to the person
using it. Dragging the map while it is following stops the camera chasing them
but leaves that preference alone, because looking somewhere else now is not the
same as changing their mind about next launch.

The position marker and the following are MapLibre's own, driven by
onCameraTrackingDismissed, so there is no second location stream to keep in step
with the map.

A test asserts that all 1180 municipalities fall inside the region bounds, which
is what actually validates the UTM-to-degrees conversion end to end.

Verified on the emulator: the dropdown lists follow, region and both saved
places; "aglie" finds Agliè; "44.3841 7.5426" offers the coordinate jump and
lands on Cuneo at town-reading zoom; selecting follow moves the map to the
device position with the blue dot on it and changes the recentre button to
match.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
2026-09-10 21:47:20 +02:00
co-authored by Claude Opus 5
parent 06ab816ebe
commit b4b8d089e6
21 changed files with 2062 additions and 210 deletions
@@ -12,130 +12,21 @@ import '../../data/radar/radar_manifest.dart';
import '../../data/radar/radar_source.dart';
import '../../l10n/app_localizations.dart';
import '../places/location_flow.dart';
import '../places/location_service.dart';
import '../places/map_target.dart';
import '../places/places_screen.dart';
import '../places/saved_place.dart';
import '../places/saved_places.dart';
import '../places/search_screen.dart';
import '../settings/settings_screen.dart';
import '../timeline/data_age_banner.dart';
import '../timeline/radar_timeline.dart';
import '../timeline/timeline_bar.dart';
import 'attribution_bar.dart';
import 'map_overlay_controls.dart';
import 'map_style.dart';
import 'radar_overlay.dart';
/// The live map controller, or null before the map is created.
///
/// Held in a provider because the app bar sits above the map in the widget tree
/// and still needs to move the camera. Cleared on dispose so a stale controller
/// is never used after the map is gone.
class MapControllerHolder extends Notifier<MapLibreMapController?> {
@override
MapLibreMapController? build() => null;
void attach(MapLibreMapController controller) => state = controller;
void detach() => state = null;
}
final mapControllerProvider =
NotifierProvider<MapControllerHolder, MapLibreMapController?>(
MapControllerHolder.new,
);
/// Moves the map onto [point], keeping the current zoom.
Future<void> _centreOn(WidgetRef ref, GeoPoint point) async {
final controller = ref.read(mapControllerProvider);
if (controller == null) return;
await controller.animateCamera(
CameraUpdate.newLatLng(LatLng(point.latitude, point.longitude)),
);
}
/// Centres the map on the device position.
class _LocateAction extends ConsumerWidget {
const _LocateAction();
@override
Widget build(BuildContext context, WidgetRef ref) {
final l10n = AppLocalizations.of(context);
return IconButton(
tooltip: l10n.locateMe,
icon: const Icon(Icons.my_location),
onPressed: () async {
final point = await requestPosition(context, ref);
if (point == null || !context.mounted) return;
// The app only has data for this region. Saying so beats silently
// refusing to move, and beats moving somewhere with an empty map.
final region = await ref.read(regionConfigProvider.future);
if (!context.mounted) return;
if (!region.bounds.contains(point)) {
ScaffoldMessenger.of(
context,
).showSnackBar(SnackBar(content: Text(l10n.locationOutsideRegion)));
return;
}
ref.read(activePlaceProvider.notifier).select(null);
await _centreOn(ref, point);
},
);
}
}
/// Opens the saved places list and centres on whatever comes back.
class _PlacesAction extends ConsumerWidget {
const _PlacesAction();
@override
Widget build(BuildContext context, WidgetRef ref) {
final l10n = AppLocalizations.of(context);
return IconButton(
tooltip: l10n.placesOpen,
icon: const Icon(Icons.place_outlined),
onPressed: () async {
final controller = ref.read(mapControllerProvider);
final region = await ref.read(regionConfigProvider.future);
if (!context.mounted) return;
final target = controller?.cameraPosition?.target;
final centre = target == null
? region.map.center
: GeoPoint(target.longitude, target.latitude);
final chosen = await Navigator.of(context).push<SavedPlace>(
MaterialPageRoute<SavedPlace>(
builder: (_) => PlacesScreen(mapCentre: centre),
),
);
if (chosen == null) return;
ref.read(activePlaceProvider.notifier).select(chosen);
await _centreOn(ref, chosen.point);
},
);
}
}
class _SettingsAction extends StatelessWidget {
const _SettingsAction();
@override
Widget build(BuildContext context) {
final l10n = AppLocalizations.of(context);
return IconButton(
tooltip: l10n.settingsOpen,
icon: const Icon(Icons.settings_outlined),
onPressed: () => Navigator.of(
context,
).push(MaterialPageRoute<void>(builder: (_) => const SettingsScreen())),
);
}
}
/// The radar map: base map, animated precipitation overlay, timeline.
class RadarMapScreen extends ConsumerWidget {
const RadarMapScreen({super.key});
@@ -148,7 +39,17 @@ class RadarMapScreen extends ConsumerWidget {
return Scaffold(
appBar: AppBar(
title: Text(l10n.appTitle),
actions: const [_LocateAction(), _PlacesAction(), _SettingsAction()],
// Only settings here. Everything that changes what the map is looking
// at lives over the map itself, next to the thing it acts on.
actions: [
IconButton(
tooltip: l10n.settingsOpen,
icon: const Icon(Icons.settings_outlined),
onPressed: () => Navigator.of(context).push(
MaterialPageRoute<void>(builder: (_) => const SettingsScreen()),
),
),
],
),
body: switch (region) {
AsyncData(:final value) => _MapWithAttribution(region: value),
@@ -185,19 +86,7 @@ class _MapWithAttribution extends ConsumerWidget {
actions: const [SizedBox.shrink()],
),
Expanded(
child: Stack(
children: [
Positioned.fill(
child: _RegionMap(region: region, style: style),
),
if (manifest != null)
Positioned(
left: 12,
bottom: 12,
child: _RadarLegend(legend: manifest.legend),
),
],
),
child: _RegionMap(region: region, style: style),
),
const DataAgeBanner(),
const TimelineBar(),
@@ -235,50 +124,53 @@ class _RegionMap extends ConsumerStatefulWidget {
}
class _RegionMapState extends ConsumerState<_RegionMap> {
/// Close enough to read a town and its surroundings, wide enough to see
/// weather arriving from the next valley.
static const double placeZoom = 9.5;
MapLibreMapController? _controller;
RadarOverlay? _overlay;
AppLifecycleListener? _lifecycle;
/// Guards against a frame that finished loading after the playhead moved on,
/// which would briefly show the wrong image.
/// Whether the map may draw the blue dot.
///
/// Turning it on without permission makes the native layer complain, so it
/// waits until permission is actually held.
bool _locationEnabled = false;
/// Guards against a frame that finished loading after the playhead moved on.
int _requestId = 0;
@override
void initState() {
super.initState();
// Playback runs a timer and pushes a texture several times a second.
// Behind another app there is no one watching, so it is pure battery.
_lifecycle = AppLifecycleListener(
onPause: () =>
ref.read(radarTimelineProvider.notifier).onAppBackgrounded(),
);
unawaited(_syncLocationAvailability());
}
@override
void dispose() {
_lifecycle?.dispose();
unawaited(_overlay?.detach());
// The controller dies with the platform view; leaving it in the provider
// would let the app bar drive a dead map.
Future<void>.microtask(
() => ref.read(mapControllerProvider.notifier).detach(),
).ignore();
super.dispose();
}
/// Frames the whole region once the map is ready.
///
/// The configured initial zoom is only a starting point: a single zoom number
/// cannot fit the region on both a small phone and a tablet, and on a 411dp
/// screen zoom 7.2 puts the viewport entirely inside the region, so the user
/// sees a flat expanse with no border or outline to orient by. Fitting the
/// bounds works on every screen size.
Future<void> _onMapCreated(MapLibreMapController controller) async {
_controller = controller;
ref.read(mapControllerProvider.notifier).attach(controller);
Future<void> _syncLocationAvailability() async {
final availability = await ref.read(locationServiceProvider).availability();
if (!mounted) return;
setState(
() => _locationEnabled = availability == LocationAvailability.granted,
);
}
// --- camera ---------------------------------------------------------------
Future<void> _frameRegion() async {
final bounds = widget.region.bounds;
await controller.moveCamera(
await _controller?.moveCamera(
CameraUpdate.newLatLngBounds(
LatLngBounds(
southwest: LatLng(bounds.south, bounds.west),
@@ -292,9 +184,136 @@ class _RegionMapState extends ConsumerState<_RegionMap> {
);
}
/// Layers can only be added once the style exists, and the style is reloaded
/// whenever it changes, so the overlay is rebuilt here rather than in
/// [_onMapCreated].
Future<void> _centreOn(GeoPoint point, {double? zoom}) async {
await _controller?.animateCamera(
zoom == null
? CameraUpdate.newLatLng(LatLng(point.latitude, point.longitude))
: CameraUpdate.newLatLngZoom(
LatLng(point.latitude, point.longitude),
zoom,
),
);
}
/// Puts the camera where the current target says it should be.
Future<void> _applyTarget(MapTarget target) async {
switch (target) {
case FollowUser():
// The native tracking mode does the following; nothing to animate.
break;
case PlaceTarget(:final place):
await _centreOn(place.point, zoom: placeZoom);
case FreeTarget():
await _frameRegion();
}
}
// --- actions --------------------------------------------------------------
/// Asks for permission, then starts following.
Future<void> _requestFollow() async {
final point = await requestPosition(context, ref);
if (!mounted) return;
if (point == null) {
// requestPosition has already explained why it could not.
await _syncLocationAvailability();
return;
}
if (!widget.region.bounds.contains(point)) {
// Worth following anyway — someone may be travelling into the region —
// but they should know why the map looks empty.
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(AppLocalizations.of(context).locationOutsideRegion),
),
);
}
setState(() => _locationEnabled = true);
await ref.read(mapTargetProvider.notifier).select(const FollowUser());
if (mounted) await _centreOn(point, zoom: placeZoom);
}
Future<void> _openSearch() async {
final result = await Navigator.of(context).push<SearchResult>(
MaterialPageRoute<SearchResult>(builder: (_) => const SearchScreen()),
);
if (result == null || !mounted) return;
// A searched point is somewhere the user is looking, not somewhere they
// have committed to, so it moves the camera without becoming the target.
// Saving it is one tap away if they want it to stick.
await ref.read(mapTargetProvider.notifier).select(const FreeTarget());
await _centreOn(result.point, zoom: placeZoom);
if (!mounted) return;
final l10n = AppLocalizations.of(context);
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(result.label),
action: SnackBarAction(
label: l10n.mapSaveThisPoint,
onPressed: () => unawaited(_savePoint(result)),
),
),
);
}
Future<void> _savePoint(SearchResult result) async {
try {
final place = await ref
.read(savedPlacesProvider.notifier)
.add(name: result.label, point: result.point);
if (!mounted) return;
await ref.read(mapTargetProvider.notifier).select(PlaceTarget(place));
} on SavedPlaceException catch (error) {
if (!mounted) return;
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(messageFor(AppLocalizations.of(context), error)),
),
);
}
}
Future<void> _openPlaces() async {
final target = _controller?.cameraPosition?.target;
final centre = target == null
? widget.region.map.center
: GeoPoint(target.longitude, target.latitude);
final chosen = await Navigator.of(context).push<SavedPlace>(
MaterialPageRoute<SavedPlace>(
builder: (_) => PlacesScreen(mapCentre: centre),
),
);
if (chosen == null || !mounted) return;
await ref.read(mapTargetProvider.notifier).select(PlaceTarget(chosen));
}
/// Puts the camera back on whatever is being followed.
Future<void> _recentre() async {
final target = ref.read(mapTargetProvider);
if (target is FollowUser) {
// Re-asserting the tracking mode is what pulls the camera back to the
// blue dot after the user has panned away from it.
await _controller?.updateMyLocationTrackingMode(
MyLocationTrackingMode.tracking,
);
return;
}
await _applyTarget(target);
}
// --- map lifecycle --------------------------------------------------------
Future<void> _onMapCreated(MapLibreMapController controller) async {
_controller = controller;
await _applyTarget(ref.read(mapTargetProvider));
}
Future<void> _onStyleLoaded() async {
final controller = _controller;
if (controller == null) return;
@@ -313,13 +332,11 @@ class _RegionMapState extends ConsumerState<_RegionMap> {
final bytes = await ref
.read(radarTimelineProvider.notifier)
.bytesFor(frame);
// Someone scrubbed while this was loading; that newer frame wins.
if (!mounted || request != _requestId) return;
await overlay.show(frame.path, bytes);
} on RadarUnavailableException {
// Hold the previous frame. A gap mid-timeline is normal while the worker
// publishes, and blanking the map would be a worse answer than showing
// the neighbouring minute.
// publishes, and blanking the map is a worse answer.
}
}
@@ -329,41 +346,91 @@ class _RegionMapState extends ConsumerState<_RegionMap> {
radarTimelineProvider.select((state) => state.currentFrame),
(_, frame) => unawaited(_showFrame(frame)),
);
ref.listen<MapTarget>(
mapTargetProvider,
(_, target) => unawaited(_applyTarget(target)),
);
final center = widget.region.map.center;
final target = ref.watch(mapTargetProvider);
final manifest = ref.watch(
radarTimelineProvider.select((state) => state.manifest),
);
final centre = widget.region.map.center;
final zoom = widget.region.map.zoom;
final bounds = widget.region.bounds;
return MapLibreMap(
styleString: widget.style.styleString,
onMapCreated: _onMapCreated,
// Without this the controller's cameraPosition stays null, and "save the
// map centre" silently saves the region default instead of what the user
// is actually looking at.
trackCameraPosition: true,
onStyleLoadedCallback: () => unawaited(_onStyleLoaded()),
initialCameraPosition: CameraPosition(
target: LatLng(center.latitude, center.longitude),
zoom: zoom.initial,
),
minMaxZoomPreference: MinMaxZoomPreference(zoom.min, zoom.max),
// Panning is confined to the region: this app has data for Piedmont and
// nowhere else, so letting the user drift away would only ever show an
// empty map.
cameraTargetBounds: CameraTargetBounds(
LatLngBounds(
southwest: LatLng(bounds.south, bounds.west),
northeast: LatLng(bounds.north, bounds.east),
return Stack(
children: [
Positioned.fill(
child: MapLibreMap(
styleString: widget.style.styleString,
onMapCreated: _onMapCreated,
onStyleLoadedCallback: () => unawaited(_onStyleLoaded()),
// Without this the controller's cameraPosition stays null, and
// "save the map centre" silently saves the region default instead
// of what the user is actually looking at.
trackCameraPosition: true,
initialCameraPosition: CameraPosition(
target: LatLng(centre.latitude, centre.longitude),
zoom: zoom.initial,
),
minMaxZoomPreference: MinMaxZoomPreference(zoom.min, zoom.max),
cameraTargetBounds: CameraTargetBounds(
LatLngBounds(
southwest: LatLng(bounds.south, bounds.west),
northeast: LatLng(bounds.north, bounds.east),
),
),
attributionButtonPosition: AttributionButtonPosition.bottomRight,
compassEnabled: false,
rotateGesturesEnabled: false,
tiltGesturesEnabled: false,
myLocationEnabled: _locationEnabled,
myLocationTrackingMode: target is FollowUser
? MyLocationTrackingMode.tracking
: MyLocationTrackingMode.none,
// Dragging the map while it is chasing the user means "let me look
// over here". The camera stops following, but what the app reopens
// on is left alone: that is a different decision.
onCameraTrackingDismissed: () =>
ref.read(mapTargetProvider.notifier).releaseFollow(),
),
),
),
// Kept enabled on top of our own attribution bar: some tile providers
// require the plugin's own attribution control, and a duplicated credit
// is harmless where a missing one is a licence breach.
attributionButtonPosition: AttributionButtonPosition.bottomRight,
compassEnabled: false,
rotateGesturesEnabled: false,
tiltGesturesEnabled: false,
myLocationEnabled: false,
Positioned(
left: 12,
right: 12,
top: 12,
child: SafeArea(
bottom: false,
child: Align(
alignment: Alignment.topCenter,
child: TargetSelector(
region: widget.region,
onFollowRequested: () => unawaited(_requestFollow()),
onSearch: () => unawaited(_openSearch()),
onManagePlaces: () => unawaited(_openPlaces()),
),
),
),
),
if (manifest != null)
Positioned(
left: 12,
bottom: 12,
child: _RadarLegend(legend: manifest.legend),
),
Positioned(
right: 12,
bottom: 12,
child: MapActionButtons(
onSearch: () => unawaited(_openSearch()),
onRecentre: () => unawaited(_recentre()),
),
),
],
);
}
}