Compare commits

...
6 Commits
22 changed files with 1505 additions and 22 deletions

No files matched your search

+4 -3
View File
@@ -75,7 +75,7 @@ independence from connectivity.
* [x] Installable PWA with a share target — `public/manifest.webmanifest`, `public/sw.js` parks files shared from Android's share sheet (OsmAnd, Locus, mapy.com — the last has no API at all), `public/js/share_import.js` offers to import them into a Tracks & Points folder (login required, files wait until then)
* [x] Item-based library replacing the file-based `GpxStore`, phase 1 — `lib/maptool/library.rb`, design in `docs/library-design.adoc`; old files migrated as layers in subfolders
* [x] Library phase 2 — rename/recolor tracks, routes and layers, rename and move (drag) folders, split a migrated layer into items (its notes become items, keeping their ids)
* [ ] Change feed + GPX export flavors for OsmAnd/Locus
* [x] Change feed + GPX export flavors for OsmAnd/Locus — `/api/library/changes`, folder menu → Export for Locus (GPX) / OsmAnd (zip)
* [ ] Android sync client (MapTool → apps first; apps → MapTool only if their APIs can list data)
== Nice to have (later)
@@ -86,8 +86,9 @@ Deprioritized for now — revisit after the sections above land.
* [ ] Offline routing with vehicle parameters (height, weight, width) — Valhalla in its own container, design in `docs/routing-design.adoc`
** [x] Phase 1: `valhalla` compose service (`bin/routing-service.sh`), builds from the offline map's extracts, "Offline routing" row in the Offline data panel
** [ ] Phase 2: `/api/route`, vehicle profile, route panel, save a route to the library
** [ ] Phase 3: elevation profile from terrain.pmtiles, isochrones
** [x] Phase 2: `/api/route`, vehicle profile, route panel, save a route to the library
** [x] Route points from search / GPS / a library point, reordering, re-editing a saved route
** [x] Phase 3: elevation profile from terrain.pmtiles, isochrones
* [ ] Solar calculator — sun path for location/date, shadows from surroundings, camper orientation
=== HW integration
+80
View File
@@ -447,6 +447,46 @@ module Maptool
json Routing.build_status(DATA_DIR)
end
# A route through the posted points ({"locations": [[lon, lat], ...]})
# for the stored vehicle. Open to anyone, like viewing the map; only
# saving it to the library needs a login.
post "/api/route" do
locations = JSON.parse(request.body.read)["locations"]
halt 400, json(error: "locations must be a list of [lon, lat]") unless locations.is_a?(Array) && locations.all?(Array)
json Routing.route(VALHALLA_URL, locations, Routing.vehicle(DATA_DIR))
rescue JSON::ParserError
halt 400, json(error: "invalid JSON")
rescue Routing::RouteError => e
halt 422, json(error: e.message)
rescue Routing::Unavailable => e
halt 503, json(error: e.message)
end
# Where the stored vehicle gets in each of `minutes` from `center`
# ({"center": [lon, lat], "minutes": [30, 60]}). Open like /api/route.
post "/api/isochrone" do
body = JSON.parse(request.body.read)
json Routing.isochrone(VALHALLA_URL, body["center"], body["minutes"], Routing.vehicle(DATA_DIR))
rescue JSON::ParserError
halt 400, json(error: "invalid JSON")
rescue Routing::RouteError => e
halt 422, json(error: e.message)
rescue Routing::Unavailable => e
halt 503, json(error: e.message)
end
get "/api/vehicle" do
json Routing.vehicle(DATA_DIR)
end
put "/api/vehicle" do
require_login!
json Routing.save_vehicle(DATA_DIR, params)
rescue ArgumentError, KeyError => e
halt 400, json(error: e.message)
end
# Same reasoning as DELETE /api/offline-tiles above.
delete "/api/terrain-tiles" do
require_login!
@@ -622,6 +662,46 @@ module Maptool
halt 404
end
# The sync feed (Library#changes): everything after ?since=<rev>.
# Login-only, like the other exports.
get "/api/library/changes" do
require_login!
json LIBRARY.changes(params[:since])
rescue Library::InvalidValue
halt 400, json(error: "since must be a number")
end
# A folder (?folder=a/b, "" = top level) for an app: ?flavor=locus is
# one GPX, ?flavor=osmand a zip of favourites.gpx + tracks/.
get "/api/library/export" do
require_login!
folder = params[:folder].to_s
name = folder.split("/").last || "MapTool"
case params[:flavor]
when "locus"
content_type "application/gpx+xml" # before attachment, which doesn't know .gpx
attachment "#{name}.gpx"
LIBRARY.export_gpx(folder)
when "osmand"
files = LIBRARY.export_osmand(folder)
halt 404, json(error: "nothing to export") if files.empty?
content_type "application/zip"
attachment "#{name}-osmand.zip"
Zip::OutputStream.write_buffer do |zip|
files.each do |path, gpx|
zip.put_next_entry(path)
zip.write(gpx)
end
end.string
else
halt 400, json(error: "flavor must be locus or osmand")
end
rescue Library::InvalidPath
halt 400, json(error: "invalid folder")
rescue Library::NotFound
halt 404
end
post "/api/library/move" do
require_login!
key = LIBRARY.move_node(params[:key].to_s, params[:to_folder].to_s)
+23 -1
View File
@@ -2,7 +2,7 @@
:toc:
:toclevels: 2
Status: *phases 1–2 implemented* (`lib/maptool/library.rb`, see Decisions); phases 3–4 proposed. Replaces the file-based store behind
Status: *phases 1–3 implemented* (`lib/maptool/library.rb`, see Decisions); phase 4 (the Android client) proposed. Replaces the file-based store behind
Tracks & Points (`GpxStore`) with an item-based library that OsmAnd, Locus
Map and the MapTool web app can all be synced against.
@@ -341,6 +341,28 @@ removed once nothing uses them.
* `GpxStore` stays, since unsplit layers are still drawn from it. It goes
away once nothing is a layer any more.
== Decisions (phase 3)
* `GET /api/library/changes?since=<rev>`: folders and items with
`rev > since`, tombstones as `"deleted": true`, plus the current `rev`,
read in one transaction. A layer comes without geometry; it's a legacy
file until split. Login-only for now. The Android client will need a
token instead of the browser session (phase 4).
* `GET /api/library/export?folder=<path>&flavor=locus|osmand`, from the
folder's own menu (and the panel header for the top level). It covers
the folder's own items, not its subfolders.
** Locus: one GPX with points, tracks and routes together.
** OsmAnd: a zip. `favourites.gpx` holds the loose points, with the
folder path as their `<type>` group ("Van / CZ") and duplicate names
made unique ("Gate (2)"). `tracks/<folder path>/<name>.gpx` holds
one file per track, route or layer, with that item's own points in
it.
* GPX writing (`Gpx.from_features`): colors as `<osmand:color>`, which is
what import reads back, and on lines also gpx_style `<line><color>`,
which Locus reads. Not verified yet against files the apps export
themselves; adjust the tags once a real OsmAnd/Locus export is at
hand.
== Open questions
* Folder depth over 3 — fine to require Locus Premium?
+36 -14
View File
@@ -2,7 +2,7 @@
:toc:
:toclevels: 1
Status: *phase 1 implemented* (the container, builds, status in the Offline data panel); phases 2–3 proposed.
Status: *implemented* (the container and builds; the route panel, vehicle profile and saving a route; elevation profile and reach).
== Goal
@@ -128,25 +128,47 @@ serving swaps the tiles in, and a truck route with dimensions comes back.
three. A routing request made while the offline map is still
downloading extracts waits for it (`Routing.offline_build_finished`).
The row says whether the service answers.
* `POST /api/route` proxies to Valhalla `/route` with `costing: truck`
and the vehicle profile filled in. It's open to everyone, like the
map. Login is required only to save the result.
* Vehicle profile: height, width, length, weight. Stored server-side,
one for now, editable in the route panel.
* Route panel: start, end and via points (map click, search result, GPS
position, a library point), the route drawn with distance, time and
turn list. "Save to library" stores it as a `route` item, so the
route goes to OsmAnd/Locus through the same export as everything
else.
* `POST /api/route` (`{"locations": [[lon, lat], ...]}`) proxies to
Valhalla `/route` and returns the route as a GeoJSON line with
distance, time and turn instructions. It's open to everyone, like the
map; only saving needs a login. The costing depends on the weight:
up to 3.5 t it's `auto` with the vehicle's height and width, because a
camper shouldn't be kept off roads closed to lorries (`hgv=no`). Above
3.5 t it's `truck` with every dimension.
* Vehicle profile: height, width, length, weight in `data/vehicle.json`
(`GET`/`PUT /api/vehicle`), one for now, edited in the route panel.
The default is a camper: 3.0 m, 2.3 m, 7 m, 3.5 t.
* Route panel (`public/js/route.js`): while it's open, a map click adds a
point; markers drag; Reverse, Clear. The route is drawn with distance,
time and directions. "Save to library" stores it as a `route` item in
the "Routes" folder through the notes endpoint, with its points (`via`)
and vehicle in `properties`. That way it goes to OsmAnd/Locus through
the same export as everything else.
* Points also come from "+" on a search result, "Add to route" in a
library point's popup, or "+ My position" (the GNSS fix, else the
browser's position). These go through events in `panels.js`, the same
way the library refresh does. ↑/↓ reorder points.
* "Edit route" in a saved route's menu in the tree loads its points
back. Save then updates that item instead of adding a copy. A route
imported from GPX has no `via`, so it can't be edited this way.
== Phases
. Container + build script + "Build routing" + status. Done when
`curl valhalla:8002/route` answers on the server.
. `/api/route`, the vehicle profile, the route panel, save to library.
. Elevation profile of the route (sampled from `terrain.pmtiles`, which
is already there, instead of Valhalla's own SRTM download), then
isochrones.
. Elevation profile of the route, then isochrones. Done:
* The browser samples the route every ≥50 m (at most 400 points) from
the same terrain tiles the hillshade uses (`dem.js`; from
`terrain.pmtiles` when it's there, else online), instead of
Valhalla's own SRTM download. The summary adds climb, descent and the
steepest grade sustained over 500 m. "Elevation profile" opens the
usual profile panel, and a saved route keeps the profile, so the
library shows it like a track's.
* `POST /api/isochrone` (`{"center": [lon, lat], "minutes": [...]}`,
1–4 times up to 240 min) returns Valhalla's polygons for the stored
vehicle. "Reach in" in the route panel draws them from the start
point, or from the map center when there are no points yet.
== Open questions
+78
View File
@@ -57,6 +57,84 @@ module Maptool
end
private_class_method :waypoint_feature
# The other direction, for exporting to OsmAnd/Locus (Library#export):
# Point features → <wpt>, kind "route" lines → <rte>, every other line
# or polygon ring → <trk>. `group` replaces every waypoint's <type>
# (OsmAnd reads it as the favourites group); without it the point's own
# category is kept. Colors go out as <osmand:color> (what import reads
# back) and, on lines, gpx_style's <line><color>, which Locus reads.
def self.from_features(features, group: nil)
doc = REXML::Document.new
doc << REXML::XMLDecl.new("1.0", "UTF-8")
gpx = doc.add_element("gpx", "version" => "1.1", "creator" => "MapTool", "xmlns" => "http://www.topografix.com/GPX/1/1",
"xmlns:osmand" => OSMAND_NAMESPACE, "xmlns:gpx_style" => GPX_STYLE_NAMESPACE)
points, lines = features.partition { |f| f.dig("geometry", "type") == "Point" }
points.each { |f| write_waypoint(gpx, f, group) }
lines.each { |f| write_line(gpx, f) }
out = +""
doc.write(output: out)
out
end
GPX_STYLE_NAMESPACE = "http://www.topografix.com/GPX/gpx_style/0/2"
private_constant :GPX_STYLE_NAMESPACE
def self.write_waypoint(gpx, feature, group)
props = feature["properties"] || {}
wpt = gpx.add_element("wpt", position_attributes(feature["geometry"]["coordinates"]))
add_text(wpt, "ele", feature["geometry"]["coordinates"][2])
add_text(wpt, "time", props["time"])
add_text(wpt, "name", props["name"])
add_text(wpt, "desc", props["description"])
add_text(wpt, "type", group || props["category"])
return unless props["color"] || props["icon"]
extensions = wpt.add_element("extensions")
add_text(extensions, "osmand:color", props["color"])
add_text(extensions, "osmand:icon", props["icon"])
end
private_class_method :write_waypoint
def self.write_line(gpx, feature)
props = feature["properties"] || {}
geometry = feature["geometry"]
segments = case geometry["type"]
when "LineString" then [geometry["coordinates"]]
when "MultiLineString", "Polygon" then geometry["coordinates"]
when "MultiPolygon" then geometry["coordinates"].flatten(1)
else return
end
route = props["kind"] == "route"
element = gpx.add_element(route ? "rte" : "trk")
add_text(element, "name", props["name"])
add_text(element, "desc", props["description"])
add_text(element, "type", props["activity_type"])
if props["color"]
extensions = element.add_element("extensions")
add_text(extensions, "osmand:color", props["color"])
add_text(extensions.add_element("gpx_style:line"), "gpx_style:color", props["color"].delete("#"))
end
if route
segments.flatten(1).each { |c| add_text(element.add_element("rtept", position_attributes(c)), "ele", c[2]) }
else
segments.each do |segment|
trkseg = element.add_element("trkseg")
segment.each { |c| add_text(trkseg.add_element("trkpt", position_attributes(c)), "ele", c[2]) }
end
end
end
private_class_method :write_line
def self.position_attributes(coordinates)
{ "lat" => coordinates[1].to_s, "lon" => coordinates[0].to_s }
end
private_class_method :position_attributes
def self.add_text(parent, name, value)
parent.add_element(name).text = value.to_s unless value.nil? || value.to_s.empty?
end
private_class_method :add_text
# <link> is plain GPX 1.1 (a wpt/trk/rte can carry any number of them),
# not a vendor extension like waypoint_style's <osmand:*> — a newer
# p4n2gpx export started emitting one per park4night listing photo. A
+91
View File
@@ -353,6 +353,63 @@ module Maptool
[*to_folder.to_s.split("/").map(&:strip).reject(&:empty?), path.split("/").last].join("/")
end
# --- sync / export ------------------------------------------------------
# Everything written after `since` (tombstones included) and the
# current rev: the feed a sync client polls (docs/library-design.adoc).
# A layer has no geometry of its own here (it's a legacy file).
def changes(since)
since = Integer(since || 0)
connect do |db|
db.transaction do
folders = db.execute("SELECT id, parent_id, name, updated_at, deleted_at, rev FROM folders WHERE rev > ? ORDER BY rev", [since])
items = db.execute("SELECT id, folder_id, parent_id, type, name, geometry, properties, updated_at, deleted_at, rev FROM items WHERE rev > ? ORDER BY rev", [since])
{ "rev" => db.get_first_value("SELECT rev FROM meta"),
"folders" => folders.map { |id, parent, name, updated, deleted, rev| { "id" => id, "parent_id" => parent, "name" => name, "updated_at" => updated, "deleted" => !deleted.nil?, "rev" => rev } },
"items" => items.map do |id, folder, parent, type, name, geometry, props, updated, deleted, rev|
{ "id" => id, "folder_id" => folder, "parent_id" => parent, "type" => type, "name" => name,
"geometry" => geometry && JSON.parse(geometry), "properties" => JSON.parse(props),
"updated_at" => updated, "deleted" => !deleted.nil?, "rev" => rev }
end }
end
end
rescue ArgumentError, TypeError
raise InvalidValue
end
# A folder's own items (not its subfolders') as one GPX with points and
# tracks together — what Locus imports into one folder.
def export_gpx(path)
Gpx.from_features(export_entries(path).map { |e| e[:feature] })
end
# The same folder the way OsmAnd keeps things: { filename => GPX }.
# Loose points → favourites.gpx in a group named after the folder path
# (names made unique, OsmAnd needs that per group); each track, route
# or layer → its own tracks/<name>.gpx with its own points.
def export_osmand(path)
group = path.to_s.split("/").reject(&:empty?).join(" / ")
group = "MapTool" if group.empty?
files = export_entries(path).group_by { |e| e[:file] }
favourites = (files.delete(nil) || []).map { |e| e[:feature] }
seen = Hash.new(0)
favourites = favourites.map do |f|
name = f["properties"]["name"].to_s.empty? ? "Point" : f["properties"]["name"]
seen[name] += 1
f.merge("properties" => f["properties"].merge("name" => seen[name] > 1 ? "#{name} (#{seen[name]})" : name))
end
out = {}
out["favourites.gpx"] = Gpx.from_features(favourites, group: group) if favourites.any?
dir = ["tracks", *group.split(" / ").map { |part| safe_name(part) }].join("/")
names = Hash.new(0)
files.each_value do |entries|
base = safe_name(File.basename(entries.first[:file_name].to_s, ".*"))
names[base] += 1
out["#{dir}/#{names[base] > 1 ? "#{base} (#{names[base]})" : base}.gpx"] = Gpx.from_features(entries.map { |e| e[:feature] })
end
out
end
# "a/b" → folder id (nil for the top level), created along the way if
# `create`; nil when it doesn't exist and isn't created.
def folder_id(path, create:)
@@ -385,6 +442,35 @@ module Maptool
id == ROOT ? nil : id
end
# Each feature in a folder (layers expanded) with the OsmAnd file it
# goes into: nil = favourites, else the id of the track/route/layer it
# belongs with (a polygon or a measured line gets a file of its own).
def export_entries(path)
id = path.to_s.empty? ? nil : (folder_id(path, create: false) or raise NotFound)
rows = connect do |db|
db.execute("SELECT id, parent_id, type, name, geometry, properties, source_path FROM items WHERE folder_id IS ? AND deleted_at IS NULL ORDER BY name COLLATE NOCASE", [id])
end
rows.flat_map do |iid, parent, type, name, geometry, props, source|
if type == "layer"
features = begin
JSON.parse(layer_geojson(source, JSON.parse(props)["color"]))["features"]
rescue Gpx::ParseError, Fit::ParseError, Errno::ENOENT
[] # an unreadable legacy file doesn't sink the whole folder
end
lines = features.any? { |f| f.dig("geometry", "type") != "Point" }
features.map { |f| { feature: f, file: lines ? iid : nil, file_name: name } }
else
f = feature(iid, name, geometry, props)
file = parent || (type == "point" ? nil : iid)
[{ feature: f, file: file, file_name: file && (file == iid ? name : nil) }]
end
end.then do |entries|
# A track's points name their file after the track.
names = entries.filter_map { |e| [e[:file], e[:file_name]] if e[:file_name] }.to_h
entries.each { |e| e[:file_name] ||= names[e[:file]] }
end
end
def sibling?(db, parent, name, except)
db.get_first_value("SELECT 1 FROM folders WHERE parent_id IS ? AND name = ? AND id != ? AND deleted_at IS NULL", [parent, name, except])
end
@@ -482,6 +568,11 @@ module Maptool
db.execute("UPDATE items SET deleted_at = ?, updated_at = ?, rev = ? WHERE (#{where}) AND deleted_at IS NULL", [now, now, rev, *params])
end
def safe_name(name)
name = name.to_s.gsub(%r{[/\\:*?"<>|]}, "_").strip
name.empty? || %w[. ..].include?(name) ? "track" : name
end
def safe_filename(filename)
base = File.basename(filename.to_s)
base = "upload.gpx" if base.empty? || base == "." || base == ".."
+13 -1
View File
@@ -543,11 +543,23 @@ module Maptool
last_modified = nil
redirect_to = nil
Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == "https") do |http|
# Net::HTTP's default (true) quietly accepts a body cut short of
# its Content-Length; a dropped connection must fail the download.
http.ignore_eof = false
http.request_get(uri) do |response|
case response
when Net::HTTPSuccess
last_modified = response["last-modified"]
File.open(dest, "wb") { |file| response.read_body { |chunk| file.write(chunk) } }
# Into a .part file renamed at the end: an interrupted download
# never leaves a truncated extract behind its old stamp, and a
# routing build that hard-linked the old file keeps reading
# that complete old file (see docs/routing-design.adoc).
begin
File.open("#{dest}.part", "wb") { |file| response.read_body { |chunk| file.write(chunk) } }
File.rename("#{dest}.part", dest)
ensure
FileUtils.rm_f("#{dest}.part")
end
when Net::HTTPRedirection
redirect_to = URI.join(url, response["location"]).to_s
else
+106
View File
@@ -114,6 +114,112 @@ module Maptool
end
private_class_method :write_json
class RouteError < StandardError; end
class Unavailable < StandardError; end
# A camper by default; one profile for now (docs/routing-design.adoc).
DEFAULT_VEHICLE = { height: 3.0, width: 2.3, length: 7.0, weight: 3.5 }.freeze
VEHICLE_LIMITS = { height: 1..6, width: 1..4, length: 2..25, weight: 0.5..60 }.freeze
# Up to this weight Valhalla's "auto" costing (with height/width) fits
# better than "truck": a camper isn't kept off roads closed to lorries.
CAR_MAX_WEIGHT = 3.5
def self.vehicle(data_dir)
DEFAULT_VEHICLE.merge(read_json(File.join(data_dir, "vehicle.json")) || {})
end
def self.save_vehicle(data_dir, values)
vehicle = VEHICLE_LIMITS.to_h do |key, range|
value = Float(values.fetch(key.to_s), exception: false)
raise ArgumentError, "#{key} must be between #{range.min} and #{range.max}" unless value && range.cover?(value)
[key, value]
end
write_json(File.join(data_dir, "vehicle.json"), vehicle)
vehicle
end
# [[lon, lat], ...] → a GeoJSON Feature (the route line) with distance
# (km), time (s) and the turn-by-turn instructions.
def self.route(valhalla_url, locations, vehicle)
raise RouteError, "at least two points are needed" if locations.size < 2
costing, options = costing(vehicle)
data = valhalla(valhalla_url, "/route",
locations: locations.map { |lon, lat| { lon: Float(lon), lat: Float(lat) } },
costing: costing, costing_options: { costing => options }, units: "kilometers")
legs = data["trip"]["legs"]
{ type: "Feature",
geometry: { type: "LineString", coordinates: legs.flat_map { |leg| decode_polyline(leg["shape"]) } },
properties: { kind: "route", costing: costing, distance_km: data["trip"]["summary"]["length"],
time_s: data["trip"]["summary"]["time"],
maneuvers: legs.flat_map { |leg| leg["maneuvers"].map { |m| { text: m["instruction"], km: m["length"] } } } } }
rescue ArgumentError, TypeError
raise RouteError, "invalid coordinates"
end
ISOCHRONE_MAX_MINUTES = 240 # Valhalla's own default limit
# How far the vehicle gets from [lon, lat] in each of `minutes`: a
# GeoJSON FeatureCollection of polygons, largest first.
def self.isochrone(valhalla_url, center, minutes, vehicle)
lon, lat = center
minutes = Array(minutes).map { |m| Integer(m) }.uniq.sort
raise RouteError, "1 to 4 times between 1 and #{ISOCHRONE_MAX_MINUTES} minutes" unless (1..4).cover?(minutes.size) && minutes.all? { |m| (1..ISOCHRONE_MAX_MINUTES).cover?(m) }
costing, options = costing(vehicle)
valhalla(valhalla_url, "/isochrone",
locations: [{ lon: Float(lon), lat: Float(lat) }], costing: costing, costing_options: { costing => options },
contours: minutes.map { |m| { time: m } }, polygons: true)
rescue ArgumentError, TypeError
raise RouteError, "invalid center or times"
end
# Up to CAR_MAX_WEIGHT "auto" with height/width, above it "truck".
def self.costing(vehicle)
vehicle[:weight].to_f <= CAR_MAX_WEIGHT ? ["auto", vehicle.slice(:height, :width)] : ["truck", vehicle]
end
private_class_method :costing
def self.valhalla(valhalla_url, path, body)
raise Unavailable, "routing is not set up" if valhalla_url.to_s.empty?
uri = URI("#{valhalla_url}#{path}")
response = begin
Net::HTTP.start(uri.host, uri.port, open_timeout: 2, read_timeout: 60) do |http|
http.post(uri.path, JSON.generate(body), "Content-Type" => "application/json")
end
rescue SystemCallError, Net::OpenTimeout, SocketError
raise Unavailable, "the routing service is not running"
end
data = JSON.parse(response.body)
raise RouteError, data["error"] || "no result" unless response.is_a?(Net::HTTPSuccess)
data
end
private_class_method :valhalla
# Valhalla's encoded polyline (precision 6) → [[lon, lat], ...].
def self.decode_polyline(encoded)
values = []
value = shift = 0
encoded.each_byte do |byte|
byte -= 63
value |= (byte & 0x1f) << shift
shift += 5
next if byte >= 0x20
values << ((value & 1).zero? ? value >> 1 : ~(value >> 1))
value = shift = 0
end
lat = lon = 0
values.each_slice(2).map do |dlat, dlon|
lat += dlat
lon += dlon
[lon / 1e6, lat / 1e6]
end
end
def self.reset!
MUTEX.synchronize { @pending = false }
end
+185
View File
@@ -2256,3 +2256,188 @@ html, body {
white-space: normal;
max-width: 200px;
}
/* Route panel (public/js/route.js) */
.route-panel__body {
padding: 10px 12px;
overflow-y: auto;
}
.route-panel__hint,
.route-panel__summary {
margin: 0 0 8px;
color: #666;
}
.route-panel__summary {
color: #222;
font-weight: 600;
}
.route-panel__points {
margin: 0 0 8px;
padding: 0;
list-style: none;
}
.route-panel__points li {
display: flex;
justify-content: space-between;
align-items: center;
padding: 3px 0;
}
.route-panel__remove {
border: none;
background: none;
color: #999;
font-size: 14px;
cursor: pointer;
}
.route-panel__remove:hover {
color: #e63946;
}
.route-panel__buttons {
display: flex;
gap: 6px;
margin-bottom: 8px;
}
.route-panel__buttons button {
border: 1px solid #ccc;
border-radius: 4px;
background: #fff;
padding: 4px 8px;
font: inherit;
font-size: 12px;
cursor: pointer;
}
.route-panel__buttons button[hidden] {
display: none;
}
.route-panel__directions {
margin-bottom: 8px;
}
.route-panel__directions ol {
margin: 6px 0 0;
padding-left: 20px;
}
.route-panel__vehicle {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 6px;
border: 1px solid #eee;
border-radius: 4px;
}
.route-panel__vehicle input {
width: 4.5em;
}
.route-marker {
width: 22px;
height: 22px;
border-radius: 50%;
background: #1d6fdc;
border: 2px solid #fff;
box-shadow: 0 1px 4px rgba(0, 0, 0, 0.3);
color: #fff;
font: 600 11px/22px sans-serif;
text-align: center;
cursor: grab;
}
.route-panel__remove:disabled {
visibility: hidden;
}
.route-panel__point {
flex: 1;
}
.route-panel__editing {
margin: 0 0 8px;
color: #1d6fdc;
}
.route-panel__editing[hidden] {
display: none;
}
.search-panel__route,
.gpx-popup__route {
border: 1px solid #ccc;
border-radius: 4px;
background: #fff;
font: inherit;
font-size: 12px;
cursor: pointer;
}
.search-panel__route {
float: right;
margin-left: 6px;
padding: 0 6px;
}
.gpx-popup__route {
display: block;
margin-top: 6px;
padding: 3px 8px;
}
/* Places that preview on hover / press-and-hold (public/js/preview.js):
no text selection or callout menu getting in the way of the hold. */
.search-panel__result,
.route-panel__point {
-webkit-touch-callout: none;
user-select: none;
}
.route-panel__point {
cursor: pointer;
}
.preview-highlight {
pointer-events: none;
}
.route-panel__profile,
.route-panel__reach button,
.route-panel__reach select {
border: 1px solid #ccc;
border-radius: 4px;
background: #fff;
padding: 3px 6px;
font: inherit;
font-size: 12px;
cursor: pointer;
}
.route-panel__profile {
margin-bottom: 8px;
}
.route-panel__profile[hidden],
.route-panel__reach button[hidden],
.route-panel__reach-status[hidden] {
display: none;
}
.route-panel__reach {
display: flex;
align-items: center;
gap: 6px;
margin-bottom: 8px;
}
.route-panel__reach-status {
margin: 0 0 8px;
color: #666;
}
+44 -2
View File
@@ -11,7 +11,7 @@ import {
POI_ICONS,
PARK4NIGHT_TAGS,
} from "/js/icons.js";
import { notifySidePanelOpen, onlyOneSidePanelOpen, onGpxStoreChanged, notifyGpxStoreChanged } from "/js/panels.js";
import { notifySidePanelOpen, onlyOneSidePanelOpen, onGpxStoreChanged, notifyGpxStoreChanged, addRoutePoint, editRoute } from "/js/panels.js";
import { formatActivityType } from "/js/track_profile.js";
import { isLoggedIn } from "/js/auth.js";
@@ -130,6 +130,10 @@ export class GpxPanelControl {
if (!isLoggedIn()) {
this._panel.querySelector('[data-action="new-folder"]').hidden = true;
this._panel.querySelector('[data-action="upload"]').hidden = true;
} else {
// The top level's own items have no folder row with a menu of its own.
const close = this._panel.querySelector(".gpx-panel__close");
close.before(this._menuButton(DOWNLOAD_ICON, "Export the top level", this._exportEntries("", "MapTool")));
}
this._panel
.querySelector(".gpx-panel__close")
@@ -280,7 +284,12 @@ export class GpxPanelControl {
name.textContent = folder.name;
row.appendChild(name);
if (isLoggedIn()) {
row.appendChild(this._menuButton("⋯", "Edit", [{ label: "Rename…", run: () => this._renameFolder(folder) }]));
row.appendChild(
this._menuButton("⋯", "Edit", [
{ label: "Rename…", run: () => this._renameFolder(folder) },
...this._exportEntries(folder.path, folder.name),
]),
);
row.appendChild(this._deleteButton(() => this._deleteFolder(folder.path)));
// Dragged onto another folder (or the tree's blank space) moves it.
summary.draggable = true;
@@ -366,6 +375,7 @@ export class GpxPanelControl {
{ label: "Color…", run: () => this._pickColor(file) },
file.color && { label: "Default color", run: () => this._patchNode(file.path, { color: "" }) },
file.layer && { label: "Split into items", run: () => this._splitLayer(file) },
(file.kinds || []).includes("route") && { label: "Edit route", run: () => this._editRoute(file) },
]);
}
@@ -757,6 +767,17 @@ export class GpxPanelControl {
.setHTML(popupHtml(feature.properties, { editable }))
.addTo(this._map);
if (editable) this._wireNoteActions(popup, path, feature);
if (feature.geometry.type === "Point") {
const button = document.createElement("button");
button.type = "button";
button.className = "gpx-popup__route";
button.textContent = "Add to route";
button.addEventListener("click", () => {
addRoutePoint(feature.geometry.coordinates, feature.properties.name);
popup.remove();
});
popup.getElement().querySelector(".maplibregl-popup-content").appendChild(button);
}
}
// Edit swaps the popup's content for a plain textarea + Save/Cancel (the
@@ -1071,6 +1092,15 @@ export class GpxPanelControl {
this._renderTree(tree);
}
// A folder (or "" for the top level) as files for the phone apps.
_exportEntries(path, name) {
const url = (flavor) => `/api/library/export?${new URLSearchParams({ folder: path, flavor })}`;
return [
{ label: "Export for Locus (GPX)", run: () => this._download(url("locus"), `${name}.gpx`) },
{ label: "Export for OsmAnd (zip)", run: () => this._download(url("osmand"), `${name}-osmand.zip`) },
];
}
async _renameFolder(folder) {
const name = window.prompt("Rename folder:", folder.name);
if (name && name.trim() && name.trim() !== folder.name) await this._patchFolder(folder.path, { name: name.trim() });
@@ -1123,6 +1153,18 @@ export class GpxPanelControl {
}
}
// A route saved from the route panel keeps its points (properties.via);
// one without them (an imported GPX route) can't be re-routed.
async _editRoute(file) {
const { features } = await (await fetch(gpxFileUrl(file.path))).json();
const route = features.find((f) => f.geometry.type === "LineString" && Array.isArray(f.properties.via));
if (!route) {
window.alert("This route has no saved route points, so it can't be edited.");
return;
}
editRoute(file.path, route);
}
async _splitLayer(file) {
if (!window.confirm(`Split "${file.name}" into separate points and tracks? This can't be undone.`)) return;
+2
View File
@@ -16,6 +16,7 @@ import { PluginsControl } from "/js/plugins.js";
import { LocateControl } from "/js/locate.js";
import { SearchControl } from "/js/search.js";
import { OfflineDataControl } from "/js/offline_data.js";
import { RoutePanelControl } from "/js/route.js";
import { LAYERS_ICON, WAYPOINT_ICON, SUNRISE_ICON, SUNSET_ICON, PENDING_ICON } from "/js/icons.js";
import { formatCoords, formatSunInfo, sunChartHtml } from "/js/sun.js";
import { notifySidePanelOpen, onlyOneSidePanelOpen } from "/js/panels.js";
@@ -584,6 +585,7 @@ if (isLoggedIn()) new PluginsControl(map).mount(sidebar);
sidebar.insertAdjacentHTML("beforeend", `<div class="sidebar-group-label" title="Offline hub"></div>`);
layerToggle.mount(sidebar);
layerToggle.setActive("online");
new RoutePanelControl(map, gnssControl, profilePanel).mount(sidebar);
new OfflineDataControl().mount(sidebar);
sidebar.insertAdjacentHTML("beforeend", `<div class="sidebar-group-label" title="Navigation"></div>`);
+7 -1
View File
@@ -397,7 +397,13 @@ export class OfflineDataControl {
formatMeta: formatRoutingMeta,
}),
];
this._regionPicker = new RegionPicker(() => this._rows.forEach((row) => row.triggerBuild()));
// One after another (each returns once its build has started, not
// finished): the routing request must reach the server after the
// offline build has, so it waits for the extracts that build downloads
// (Routing.request_build) instead of building from half-written ones.
this._regionPicker = new RegionPicker(async () => {
for (const row of this._rows) await row.triggerBuild();
});
}
mount(sidebar) {
+22
View File
@@ -31,3 +31,25 @@ export function notifyGpxStoreChanged(path) {
export function onGpxStoreChanged(callback) {
document.addEventListener(STORE_CHANGED_EVENT, (event) => callback(event.detail));
}
// Anything with a location (a search result, a library point) hands it to
// the route panel (route.js) the same decoupled way.
const ROUTE_POINT_EVENT = "route-point";
const ROUTE_EDIT_EVENT = "route-edit";
export function addRoutePoint(lngLat, name) {
document.dispatchEvent(new CustomEvent(ROUTE_POINT_EVENT, { detail: { lngLat, name } }));
}
export function onRoutePoint(callback) {
document.addEventListener(ROUTE_POINT_EVENT, (event) => callback(event.detail));
}
// A saved route (its library node key and feature) back into the panel.
export function editRoute(key, feature) {
document.dispatchEvent(new CustomEvent(ROUTE_EDIT_EVENT, { detail: { key, feature } }));
}
export function onRouteEdit(callback) {
document.addEventListener(ROUTE_EDIT_EVENT, (event) => callback(event.detail));
}
+97
View File
@@ -0,0 +1,97 @@
import { Marker } from "/vendor/maplibre-gl/maplibre-gl.mjs";
// Hovering a list item with a place (mouse), or pressing and holding it
// (touch), shows that place on the map for a moment; leaving or letting go
// puts the map back where it was. A click or tap commits: the item's own
// click handler moves the map for good, and nothing is restored.
const HOLD_MS = 400;
const RESTORE_DELAY_MS = 150; // moving straight to the next item doesn't bounce back in between
const DURATION_MS = 300;
let saved = null; // the camera before the first preview
let restoreTimer = null;
let marker = null;
const wiredMaps = new WeakSet();
// target() → { lngLat: [lon, lat] } or { bbox: [w, s, e, n] }.
export function wirePreview(map, element, target) {
// Panning the map yourself during a preview keeps where you are now.
if (!wiredMaps.has(map)) {
wiredMaps.add(map);
map.on("dragstart", commit);
}
let holdTimer = null;
let held = false;
element.addEventListener("pointerenter", (event) => {
if (event.pointerType === "mouse") show(map, target());
});
element.addEventListener("pointerleave", (event) => {
if (event.pointerType === "mouse") restoreSoon(map);
});
element.addEventListener("pointerdown", (event) => {
if (event.pointerType === "mouse") return;
held = false;
holdTimer = setTimeout(() => {
held = true;
show(map, target());
}, HOLD_MS);
});
const release = () => {
clearTimeout(holdTimer);
if (held) restoreSoon(map);
};
element.addEventListener("pointerup", release);
element.addEventListener("pointercancel", release); // the list scrolled instead
element.addEventListener("contextmenu", (event) => event.preventDefault()); // the long press is ours
// Capture, so this runs before the item's own click handler.
element.addEventListener(
"click",
(event) => {
if (held) {
// The end of a hold, not a tap.
held = false;
event.preventDefault();
event.stopImmediatePropagation();
return;
}
commit();
},
true,
);
}
function show(map, { lngLat, bbox }) {
clearTimeout(restoreTimer);
saved ||= { center: map.getCenter(), zoom: map.getZoom(), bearing: map.getBearing(), pitch: map.getPitch() };
const point = bbox && (bbox[0] !== bbox[2] || bbox[1] !== bbox[3]) ? null : lngLat || bbox.slice(0, 2);
if (point) {
map.easeTo({ center: point, zoom: Math.max(saved.zoom, 14), duration: DURATION_MS });
if (!marker) {
const element = document.createElement("div");
element.className = "search-highlight preview-highlight";
marker = new Marker({ element });
}
marker.setLngLat(point).addTo(map);
} else {
map.fitBounds(bbox, { padding: 40, maxZoom: 15, duration: DURATION_MS });
marker?.remove();
}
}
function restoreSoon(map) {
clearTimeout(restoreTimer);
restoreTimer = setTimeout(() => {
if (saved) map.easeTo({ ...saved, duration: DURATION_MS });
saved = null;
marker?.remove();
}, RESTORE_DELAY_MS);
}
function commit() {
clearTimeout(restoreTimer);
saved = null;
marker?.remove();
}
+473
View File
@@ -0,0 +1,473 @@
import { Marker } from "/vendor/maplibre-gl/maplibre-gl.mjs";
import { ROUTE_ICON } from "/js/icons.js";
import { notifySidePanelOpen, onlyOneSidePanelOpen, notifyGpxStoreChanged, onRoutePoint, onRouteEdit } from "/js/panels.js";
import { isLoggedIn } from "/js/auth.js";
import { wirePreview } from "/js/preview.js";
import { elevationAt } from "/js/dem.js";
const ROUTE_URL = "/api/route";
const ISOCHRONE_URL = "/api/isochrone";
const REACH_SOURCE = "route-reach";
const PROFILE_SAMPLES = 400; // elevation lookups per route, at least 50 m apart
const GRADE_WINDOW_M = 500; // "max grade" is sustained over this distance, not one noisy pixel
const VEHICLE_URL = "/api/vehicle";
const NOTES_URL = "/api/library/notes";
const SOURCE = "route";
const COLOR = "#1d6fdc";
const SAVE_FOLDER = "Routes";
// Offline routing (docs/routing-design.adoc): while the panel is open, a
// map click adds a point, markers drag to move, and the route through
// them comes from POST /api/route (Valhalla, for the stored vehicle). The
// route stays drawn after the panel closes, until Clear.
export class RoutePanelControl {
constructor(map, gnssControl, profilePanel) {
this._map = map;
this._gnss = gnssControl;
this._profilePanel = profilePanel;
this._reach = null; // the last /api/isochrone FeatureCollection
// Elevations from the offline terrain when it's there, as the hillshade does.
this._offlineTerrain = fetch("/api/terrain-tiles")
.then((r) => r.json())
.then((d) => d.available)
.catch(() => false);
this._points = []; // [{ lngLat: [lon, lat], name, marker }]
this._route = null; // the last /api/route Feature
this._request = 0; // so a slow older response can't overwrite a newer one
this._editing = null; // { key, id, name } of a saved route being edited
onRoutePoint(({ lngLat, name }) => {
this._setOpen(true);
this._addPoint(lngLat, name);
});
onRouteEdit(({ key, feature }) => this._edit(key, feature));
map.on("click", (event) => {
if (this._panel.hidden || event.originalEvent.altKey) return;
this._addPoint([event.lngLat.lng, event.lngLat.lat]);
});
// setStyle() (base map switch) drops custom sources.
map.on("style.load", () => this._draw());
}
mount(sidebar) {
this._container = document.createElement("div");
this._container.className = "sidebar-item";
this._container.innerHTML = `<button type="button" class="sidebar-icon" title="Route" aria-label="Route">${ROUTE_ICON}</button>`;
this._icon = this._container.querySelector(".sidebar-icon");
this._icon.addEventListener("click", () => this._togglePanel());
this._panel = document.getElementById("route-panel");
this._panel.querySelector(".basemap-panel__close").addEventListener("click", () => this._togglePanel(false));
this._list = this._panel.querySelector(".route-panel__points");
this._summary = this._panel.querySelector(".route-panel__summary");
this._directions = this._panel.querySelector(".route-panel__directions");
this._saveButton = this._panel.querySelector('[data-action="save"]');
this._panel.querySelector('[data-action="reverse"]').addEventListener("click", () => {
this._points.reverse();
this._changed();
});
this._panel.querySelector('[data-action="clear"]').addEventListener("click", () => this._clear());
this._panel.querySelector('[data-action="position"]').addEventListener("click", () => this._addPosition());
this._editingNote = this._panel.querySelector(".route-panel__editing");
this._saveButton.addEventListener("click", () => this._save());
this._profileButton = this._panel.querySelector(".route-panel__profile");
this._profileButton.addEventListener("click", () => this._profilePanel.show(this._profileProperties()));
this._reachStatus = this._panel.querySelector(".route-panel__reach-status");
this._reachClear = this._panel.querySelector('[data-action="reach-clear"]');
this._panel.querySelector('[data-action="reach"]').addEventListener("click", () => this._showReach());
this._reachClear.addEventListener("click", () => {
this._reach = null;
this._reachClear.hidden = true;
this._reachStatus.hidden = true;
this._draw();
});
this._setupVehicle();
onlyOneSidePanelOpen(this._panel, () => this._setOpen(false));
sidebar.appendChild(this._container);
}
_togglePanel(force) {
this._setOpen(force === undefined ? this._panel.hidden : force);
}
_setOpen(open) {
this._panel.hidden = !open;
this._icon.classList.toggle("active", open);
this._map.getCanvas().style.cursor = open ? "crosshair" : "";
if (open) notifySidePanelOpen(this._panel);
}
// --- points ---------------------------------------------------------------
_addPoint(lngLat, name, { quiet = false } = {}) {
const element = document.createElement("div");
element.className = "route-marker";
const marker = new Marker({ element, draggable: true }).setLngLat(lngLat).addTo(this._map);
const point = { lngLat, name, marker };
marker.on("dragend", () => {
const { lng, lat } = marker.getLngLat();
point.lngLat = [lng, lat];
point.name = null; // no longer that place
this._changed();
});
this._points.push(point);
if (!quiet) this._changed();
}
// The GNSS fix when there is one, else the browser's own position.
_addPosition() {
const fix = this._gnss?.getPosition();
if (fix) {
this._addPoint([fix.lng, fix.lat], "My position");
return;
}
navigator.geolocation.getCurrentPosition(
(position) => this._addPoint([position.coords.longitude, position.coords.latitude], "My position"),
() => window.alert("Could not determine your location."),
{ enableHighAccuracy: true },
);
}
_move(point, step) {
const index = this._points.indexOf(point);
const other = index + step;
if (other < 0 || other >= this._points.length) return;
[this._points[index], this._points[other]] = [this._points[other], this._points[index]];
this._changed();
}
// A saved route's points back in the panel; Save then updates that item.
_edit(key, feature) {
this._clear();
feature.properties.via.forEach((lngLat) => this._addPoint(lngLat, null, { quiet: true }));
this._editing = { key, id: feature.properties.id, name: feature.properties.name };
this._setOpen(true);
this._changed();
}
_removePoint(point) {
point.marker.remove();
this._points = this._points.filter((p) => p !== point);
this._changed();
}
_clear() {
this._points.forEach((p) => p.marker.remove());
this._points = [];
this._editing = null;
this._changed();
}
_changed() {
this._renderPoints();
this._fetchRoute();
}
_renderPoints() {
this._list.innerHTML = "";
this._points.forEach((point, index) => {
const label = index === 0 ? "Start" : index === this._points.length - 1 ? "End" : `Via ${index}`;
point.marker.getElement().textContent = index === 0 ? "S" : index === this._points.length - 1 ? "E" : String(index);
const li = document.createElement("li");
const text = document.createElement("span");
text.className = "route-panel__point";
text.textContent = `${label} · ${point.name || `${point.lngLat[1].toFixed(5)}, ${point.lngLat[0].toFixed(5)}`}`;
li.append(
text,
this._pointButton("↑", "Move up", index > 0, () => this._move(point, -1)),
this._pointButton("↓", "Move down", index < this._points.length - 1, () => this._move(point, 1)),
this._pointButton("×", "Remove", true, () => this._removePoint(point)),
);
// Hover/hold previews the point; a click on its name commits.
wirePreview(this._map, text, () => ({ lngLat: point.lngLat }));
text.addEventListener("click", () => this._map.easeTo({ center: point.lngLat, zoom: Math.max(this._map.getZoom(), 14) }));
this._list.appendChild(li);
});
this._editingNote.hidden = !this._editing;
if (this._editing) this._editingNote.textContent = `Editing "${this._editing.name}"`;
this._saveButton.textContent = this._editing ? "Save changes" : "Save to library";
}
_pointButton(text, title, enabled, onClick) {
const button = document.createElement("button");
button.type = "button";
button.className = "route-panel__remove";
button.title = title;
button.setAttribute("aria-label", title);
button.textContent = text;
button.disabled = !enabled;
button.addEventListener("click", onClick);
return button;
}
// --- route ----------------------------------------------------------------
async _fetchRoute() {
const request = ++this._request;
this._route = null;
if (this._points.length < 2) {
this._showResult(null, "");
return;
}
this._showResult(null, "Routing…");
let data;
let error;
try {
const response = await fetch(ROUTE_URL, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ locations: this._points.map((p) => p.lngLat) }),
});
data = await response.json().catch(() => ({}));
if (!response.ok) error = data.error || `routing failed (${response.status})`;
} catch (err) {
error = err.message;
}
if (request !== this._request) return;
this._route = error ? null : data;
this._showResult(this._route, error ? `No route: ${error}` : "");
}
_showResult(route, message) {
this._draw();
this._saveButton.hidden = !route || !isLoggedIn();
this._directions.hidden = !route;
this._profileButton.hidden = true;
if (!route) {
this._summary.textContent = message;
return;
}
const { distance_km: km, time_s: seconds, maneuvers } = route.properties;
this._summary.textContent = `${km.toFixed(1)} km · ${formatDuration(seconds)}`;
const list = this._directions.querySelector("ol");
list.innerHTML = "";
maneuvers.forEach(({ text, km: length }) => {
const li = document.createElement("li");
li.textContent = length > 0 ? `${text} (${length.toFixed(1)} km)` : text;
list.appendChild(li);
});
this._addElevation(route);
}
// Sampled from the terrain tiles once the route is there; adds climb,
// descent and the steepest sustained grade to the summary.
async _addElevation(route) {
const profile = await elevationProfile(route.geometry.coordinates, await this._offlineTerrain);
if (this._route !== route || !profile) return;
route.elevation = profile;
this._summary.textContent += ` · ↑ ${Math.round(profile.gain)} m ↓ ${Math.round(profile.loss)} m · max ${profile.maxGrade.toFixed(0)} %`;
this._profileButton.hidden = false;
}
// What TrackProfilePanel (and a library track) reads.
_profileProperties() {
const { distance_km: km, time_s: seconds } = this._route.properties;
const elevation = this._route.elevation;
return {
name: this._editing?.name || "Route",
distance_meters: km * 1000,
duration_secs: seconds,
...(elevation && { elevation_gain_meters: elevation.gain, profile: elevation.profile }),
};
}
// From the start point (or the map center with no points yet).
async _showReach() {
const center = this._points[0]?.lngLat || this._map.getCenter().toArray();
const minutes = this._panel.querySelector(".route-panel__reach select").value.split(",").map(Number);
this._reachStatus.hidden = false;
this._reachStatus.textContent = "Computing reach…";
try {
const response = await fetch(ISOCHRONE_URL, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ center, minutes }),
});
const data = await response.json().catch(() => ({}));
if (!response.ok) throw new Error(data.error || `failed (${response.status})`);
this._reach = data;
} catch (err) {
this._reachStatus.textContent = `No reach: ${err.message}`;
return;
}
this._reachStatus.textContent = `Reach from ${this._points[0] ? "the start" : "the map center"}: ${minutes.map((m) => formatDuration(m * 60)).join(", ")}`;
this._reachClear.hidden = false;
this._draw();
}
_draw() {
if (!this._map.isStyleLoaded() && !this._map.getSource(SOURCE)) return; // style.load draws it
const reach = this._reach || { type: "FeatureCollection", features: [] };
if (this._map.getSource(REACH_SOURCE)) {
this._map.getSource(REACH_SOURCE).setData(reach);
} else {
// Valhalla colors each contour (properties.color); drawn under the route.
this._map.addSource(REACH_SOURCE, { type: "geojson", data: reach });
this._map.addLayer({
id: `${REACH_SOURCE}-fill`,
type: "fill",
source: REACH_SOURCE,
paint: { "fill-color": ["get", "color"], "fill-opacity": 0.15 },
});
this._map.addLayer({
id: `${REACH_SOURCE}-outline`,
type: "line",
source: REACH_SOURCE,
paint: { "line-color": ["get", "color"], "line-width": 2 },
});
}
const data = { type: "FeatureCollection", features: this._route ? [this._route] : [] };
const source = this._map.getSource(SOURCE);
if (source) {
source.setData(data);
return;
}
this._map.addSource(SOURCE, { type: "geojson", data });
this._map.addLayer({
id: `${SOURCE}-casing`,
type: "line",
source: SOURCE,
layout: { "line-cap": "round", "line-join": "round" },
paint: { "line-color": "#fff", "line-width": 8 },
});
this._map.addLayer({
id: `${SOURCE}-line`,
type: "line",
source: SOURCE,
layout: { "line-cap": "round", "line-join": "round" },
paint: { "line-color": COLOR, "line-width": 5 },
});
}
// A route item in the library ("Routes" folder), keeping its points and
// vehicle so it can be routed again later; an edited one is updated in
// place.
async _save() {
const name = window.prompt("Route name:", this._editing?.name || `Route ${new Date().toLocaleDateString()}`);
if (!name || !name.trim()) return;
const { maneuvers, ...properties } = this._route.properties;
const feature = {
type: "Feature",
geometry: this._route.geometry,
// The elevation profile too, so the library shows it like a track's.
properties: { ...properties, ...this._profileProperties(), name: name.trim(), via: this._points.map((p) => p.lngLat), vehicle: this._vehicle },
};
const editing = this._editing;
const response = await fetch(NOTES_URL, {
method: editing ? "PUT" : "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: new URLSearchParams(
editing
? { feature: JSON.stringify(feature), path: editing.key, id: editing.id }
: { feature: JSON.stringify(feature), folder: SAVE_FOLDER },
),
});
if (response.status === 401) {
window.location.href = "/login";
return;
}
if (!response.ok) {
window.alert("Could not save the route.");
return;
}
const path = editing ? editing.key : (await response.json()).path;
notifyGpxStoreChanged(path);
this._editing = { key: path, id: editing?.id ?? (await this._savedId(path)), name: name.trim() };
this._renderPoints();
this._summary.textContent += " · saved";
}
// The id of the route just saved, so a second Save updates it instead of
// adding another copy.
async _savedId(key) {
const { features } = await (await fetch(`/api/library/node/${encodeURIComponent(key)}`)).json();
return features.find((f) => f.geometry.type === "LineString")?.properties.id;
}
// --- vehicle --------------------------------------------------------------
// Readable by anyone, saved only when logged in; a change re-routes.
async _setupVehicle() {
const inputs = [...this._panel.querySelectorAll(".route-panel__vehicle input")];
try {
this._vehicle = await (await fetch(VEHICLE_URL)).json();
} catch {
return;
}
inputs.forEach((input) => {
input.value = this._vehicle[input.name];
input.disabled = !isLoggedIn();
input.addEventListener("change", async () => {
const body = new URLSearchParams(inputs.map((i) => [i.name, i.value]));
const response = await fetch(VEHICLE_URL, { method: "PUT", body });
const data = await response.json().catch(() => ({}));
if (!response.ok) {
window.alert(data.error || "Could not save the vehicle.");
input.value = this._vehicle[input.name];
return;
}
this._vehicle = data;
this._fetchRoute();
});
});
}
}
// The route's coordinates resampled every ≥50 m (at most PROFILE_SAMPLES
// points), each with its terrain elevation, as TrackProfilePanel's
// `profile`; plus total climb/descent and the steepest grade sustained
// over GRADE_WINDOW_M. null when no elevation could be read.
async function elevationProfile(coordinates, offline) {
const along = [0];
for (let i = 1; i < coordinates.length; i++) along.push(along[i - 1] + distanceM(coordinates[i - 1], coordinates[i]));
const total = along.at(-1);
const step = Math.max(50, total / PROFILE_SAMPLES);
const samples = [];
let segment = 1;
for (let d = 0; d < total; d += step) {
while (along[segment] < d) segment++;
const [a, b] = [coordinates[segment - 1], coordinates[segment]];
const t = (d - along[segment - 1]) / (along[segment] - along[segment - 1] || 1);
samples.push({ distance_meters: d, lon: a[0] + (b[0] - a[0]) * t, lat: a[1] + (b[1] - a[1]) * t });
}
samples.push({ distance_meters: total, lon: coordinates.at(-1)[0], lat: coordinates.at(-1)[1] });
const elevations = await Promise.all(samples.map((s) => elevationAt(s.lon, s.lat, offline)));
const profile = samples.map((s, i) => ({ ...s, elevation_meters: elevations[i] })).filter((p) => p.elevation_meters != null);
if (profile.length < 2) return null;
let gain = 0;
let loss = 0;
let maxGrade = 0;
let j = 0;
profile.forEach((p, i) => {
if (i > 0) {
const climb = p.elevation_meters - profile[i - 1].elevation_meters;
if (climb > 0) gain += climb;
else loss -= climb;
}
while (j < profile.length - 1 && profile[j].distance_meters - p.distance_meters < GRADE_WINDOW_M) j++;
const run = profile[j].distance_meters - p.distance_meters;
if (run >= GRADE_WINDOW_M) maxGrade = Math.max(maxGrade, (Math.abs(profile[j].elevation_meters - p.elevation_meters) / run) * 100);
});
return { profile, gain, loss, maxGrade };
}
function distanceM([lon1, lat1], [lon2, lat2]) {
const rad = Math.PI / 180;
const a = Math.sin(((lat2 - lat1) * rad) / 2) ** 2 + Math.cos(lat1 * rad) * Math.cos(lat2 * rad) * Math.sin(((lon2 - lon1) * rad) / 2) ** 2;
return 12742000 * Math.asin(Math.sqrt(a));
}
function formatDuration(seconds) {
const minutes = Math.round(seconds / 60);
return minutes < 60 ? `${minutes} min` : `${Math.floor(minutes / 60)} h ${minutes % 60} min`;
}
+14
View File
@@ -1,6 +1,8 @@
import { Marker } from "/vendor/maplibre-gl/maplibre-gl.mjs";
import { SEARCH_ICON } from "/js/icons.js";
import { escapeHtml } from "/js/gpx.js";
import { addRoutePoint } from "/js/panels.js";
import { wirePreview } from "/js/preview.js";
const NOMINATIM_API = "https://nominatim.openstreetmap.org/search";
// "lat, lng" / "lat lng" decimal degrees — the same plain-text shape the
@@ -208,6 +210,7 @@ export class SearchControl {
result.status
? `<li class="search-panel__status">${escapeHtml(result.status)}</li>`
: `<li class="search-panel__result" data-index="${i}">
${result.lat != null || result.bbox ? `<button type="button" class="search-panel__route" title="Add to route" aria-label="Add to route">+</button>` : ""}
${escapeHtml(result.name)}
<span class="search-panel__where">${escapeHtml(
[result.where, result.distanceKm != null && formatKm(result.distanceKm)].filter(Boolean).join(" · "),
@@ -215,7 +218,18 @@ export class SearchControl {
</li>`,
)
.join("") + tail;
this._resultsEl.querySelectorAll(".search-panel__route").forEach((button) => {
button.addEventListener("click", (event) => {
event.stopPropagation();
const { lat, lng, bbox, name } = this._results[Number(button.closest("li").dataset.index)];
addRoutePoint(lat != null ? [lng, lat] : [(bbox[0] + bbox[2]) / 2, (bbox[1] + bbox[3]) / 2], name);
});
});
this._resultsEl.querySelectorAll(".search-panel__result").forEach((el) => {
const result = this._results[Number(el.dataset.index)];
if (result.bbox || result.lat != null) {
wirePreview(this._map, el, () => (result.lat != null ? { lngLat: [result.lng, result.lat] } : { bbox: result.bbox }));
}
el.addEventListener("click", () => {
const result = this._results[Number(el.dataset.index)];
result.open?.();
+34
View File
@@ -230,6 +230,40 @@ class AppTest < Minitest::Test
assert_equal 409, request.patch("/api/library/folder/Van", params: { name: "Bus" }, **logged_in_env).status
end
def test_routing_without_a_valhalla_service_says_so
assert_equal 503, request.post("/api/route", input: JSON.generate(locations: [[17.1, 48.1], [17.2, 48.2]]), "CONTENT_TYPE" => "application/json").status
assert_equal 400, request.post("/api/route", input: JSON.generate(locations: "x"), "CONTENT_TYPE" => "application/json").status
assert_equal 503, request.post("/api/isochrone", input: JSON.generate(center: [17.1, 48.1], minutes: [60]), "CONTENT_TYPE" => "application/json").status
assert_equal 422, request.post("/api/isochrone", input: JSON.generate(center: [17.1, 48.1], minutes: [999]), "CONTENT_TYPE" => "application/json").status
end
def test_the_vehicle_is_readable_by_anyone_but_saved_only_when_logged_in
assert_equal 3.0, json_body(request.get("/api/vehicle"))["height"]
vehicle = { height: 3.3, width: 2.3, length: 7, weight: 3.5 }
assert_equal 401, request.put("/api/vehicle", params: vehicle).status
assert_equal 3.3, json_body(request.put("/api/vehicle", params: vehicle, **logged_in_env))["height"]
assert_equal 400, request.put("/api/vehicle", params: vehicle.merge(weight: 0), **logged_in_env).status
ensure
FileUtils.rm_f(File.join(Maptool::App::DATA_DIR, "vehicle.json"))
end
def test_changes_and_exports_need_login
upload("ride.gpx", File.read(fixture_path("sample.gpx")), folder: "trips")
assert_equal 401, request.get("/api/library/changes").status
assert_equal 401, request.get("/api/library/export?folder=trips&flavor=locus").status
changes = json_body(request.get("/api/library/changes?since=0", **logged_in_env))
assert_equal ["Morning Loop", "Start"], changes["items"].map { |i| i["name"] }.sort
locus = request.get("/api/library/export?folder=trips&flavor=locus", **logged_in_env)
assert_includes locus.body, "<name>Morning Loop</name>"
osmand = request.get("/api/library/export?folder=trips&flavor=osmand", **logged_in_env)
entries = nil
Zip::File.open_buffer(StringIO.new(osmand.body)) { |zip| entries = zip.map(&:name) }
assert_equal ["tracks/trips/Morning Loop.gpx"], entries
assert_equal 400, request.get("/api/library/export?folder=trips&flavor=x", **logged_in_env).status
end
def test_invalid_folder_path_is_rejected
assert_equal 400, request.post("/api/library/folder?path=..%2F..%2Fescape", **logged_in_env).status
end
+51
View File
@@ -130,8 +130,59 @@ class LibraryTest < Minitest::Test
assert_raises(Maptool::Library::InvalidValue) { library.move_folder("c/x", "a") }
end
def test_a_saved_route_is_a_route_node_and_editing_replaces_it
route = { "type" => "Feature", "geometry" => { "type" => "LineString", "coordinates" => [[17.1, 48.1], [17.2, 48.2]] },
"properties" => { "name" => "To the lake", "kind" => "route", "via" => [[17.1, 48.1], [17.2, 48.2]] } }
library = open_library
key = library.add_note(route, "Routes")
node = library.tree["children"].first["children"].first
assert_equal [key, ["route"]], node.values_at("path", "kinds")
id = JSON.parse(library.geojson(key))["features"].first["properties"]["id"]
edited = route.merge("properties" => route["properties"].merge("name" => "Lake, scenic", "via" => [[17.1, 48.1], [17.15, 48.3], [17.2, 48.2]]))
library.update_feature(key, id, edited)
features = JSON.parse(library.geojson(key))["features"]
assert_equal [["Lake, scenic", 3]], features.map { |f| [f["properties"]["name"], f["properties"]["via"].size] }
end
def test_changes_lists_everything_after_a_rev_tombstones_included
library = open_library
start = library.rev
key = library.add_note(note("Gate"), "Van")
id = JSON.parse(library.geojson(key))["features"].first["properties"]["id"]
library.delete_feature(key, id)
changes = library.changes(start)
assert_equal library.rev, changes["rev"]
assert_equal ["Van"], changes["folders"].map { |f| f["name"] }
assert_equal [[id, true, "Point"]], changes["items"].map { |i| [i["id"], i["deleted"], i["geometry"]["type"]] }
assert_empty library.changes(library.rev)["items"]
assert_raises(Maptool::Library::InvalidValue) { library.changes("x") }
end
def test_export_for_locus_and_osmand
library = open_library
library.import(folder: "Van/CZ", filename: "ride.gpx", io: File.open(fixture_path("sample.gpx")))
library.add_note(note("Gate"), "Van/CZ")
library.add_note(note("Gate", nil).tap { |f| f["geometry"]["coordinates"] = [17.3, 48.3] }, "Van/CZ")
locus = Maptool::Gpx.to_geojson(write_tmp(library.export_gpx("Van/CZ")))["features"]
assert_equal 2, locus.count { |f| f["properties"]["name"] == "Gate" }
assert(locus.any? { |f| f["properties"]["kind"] == "track" })
files = library.export_osmand("Van/CZ")
assert_equal ["favourites.gpx", "tracks/Van/CZ/Morning Loop.gpx"], files.keys.sort
favourites = Maptool::Gpx.to_geojson(write_tmp(files["favourites.gpx"]))["features"]
assert_equal [["Gate", "Van / CZ"], ["Gate (2)", "Van / CZ"]], favourites.map { |f| f["properties"].values_at("name", "category") }.sort
assert_raises(Maptool::Library::NotFound) { library.export_gpx("nope") }
end
private
def write_tmp(content)
File.join(@dir, "export-#{SecureRandom.hex(4)}.gpx").tap { |path| File.write(path, content) }
end
def open_library
Maptool::Library.new(File.join(@dir, "library.sqlite"), gpx_store: @store, sources_dir: File.join(@dir, "sources"))
end
+38
View File
@@ -1,4 +1,5 @@
require_relative "test_helper"
require "socket"
require "maptool/pmtiles_builder"
require "tmpdir"
require "fileutils"
@@ -689,4 +690,41 @@ class PmtilesBuilderTest < Minitest::Test
gate.push(fake_manifest)
thread&.join
end
# A download replaces the extract by rename, so a hard link to the old one
# (a routing build reading it) keeps the complete old file, and a broken
# download leaves the old extract alone.
def test_download_extract_replaces_the_file_atomically
dest = File.join(@data_dir, "SK.osm.pbf")
File.write(dest, "old")
linked = File.join(@data_dir, "linked.pbf")
File.link(dest, linked)
serve_once("HTTP/1.1 200 OK\r\nContent-Length: 3\r\nLast-Modified: today\r\n\r\nnew") do |url|
assert_equal "today", Maptool::PmtilesBuilder.download_extract(url, dest)
end
assert_equal ["new", "old"], [File.read(dest), File.read(linked)]
serve_once("HTTP/1.1 200 OK\r\nContent-Length: 100\r\n\r\ncut") do |url|
assert_raises(StandardError) { Maptool::PmtilesBuilder.download_extract(url, dest) }
end
assert_equal "new", File.read(dest)
refute File.exist?("#{dest}.part")
end
private
def serve_once(response)
server = TCPServer.new("127.0.0.1", 0)
thread = Thread.new do
client = server.accept
client.readpartial(4096)
client.write(response)
client.close
end
yield "http://127.0.0.1:#{server.addr[1]}/x.osm.pbf"
ensure
thread&.join
server&.close
end
end
+61
View File
@@ -1,5 +1,6 @@
require_relative "test_helper"
require "maptool/routing"
require "socket"
class RoutingTest < Minitest::Test
def setup
@@ -58,4 +59,64 @@ class RoutingTest < Minitest::Test
File.write(File.join(@routing, "status.json"), JSON.generate(state: "running", step: "packing tiles"))
assert_equal "packing tiles", Maptool::Routing.build_status(@data)[:step]
end
def test_the_vehicle_is_validated_and_stored
assert_equal Maptool::Routing::DEFAULT_VEHICLE, Maptool::Routing.vehicle(@data)
Maptool::Routing.save_vehicle(@data, "height" => "3.4", "width" => "2.4", "length" => "8", "weight" => "4.2")
assert_equal 4.2, Maptool::Routing.vehicle(@data)[:weight]
assert_raises(ArgumentError) { Maptool::Routing.save_vehicle(@data, "height" => "30", "width" => "2", "length" => "8", "weight" => "3") }
end
def test_decode_polyline_reads_valhallas_precision_6
# Two points, encoded with Valhalla's (Google-style, 1e6) polyline.
assert_equal [[9.521006, 47.140956], [9.521034, 47.140974]], Maptool::Routing.decode_polyline("wdg|xA{ubdQc@w@")
end
def test_route_picks_the_costing_by_weight_and_returns_a_line
shape = "wdg|xA{ubdQc@w@"
reply = JSON.generate(trip: { summary: { length: 1.5, time: 90 },
legs: [{ shape: shape, maneuvers: [{ instruction: "Drive north.", length: 1.5 }] }] })
request = serve_once("HTTP/1.1 200 OK\r\nContent-Length: #{reply.bytesize}\r\n\r\n#{reply}") do |url|
route = Maptool::Routing.route(url, [[9.52, 47.14], [9.53, 47.15]], Maptool::Routing::DEFAULT_VEHICLE)
assert_equal [2, "auto", "Drive north."], [route[:geometry][:coordinates].size, route[:properties][:costing], route[:properties][:maneuvers][0][:text]]
end
assert_includes request, %("costing_options":{"auto":{"height":3.0,"width":2.3}})
request = serve_once("HTTP/1.1 400 Bad Request\r\nContent-Length: 20\r\n\r\n{\"error\":\"no route\"}") do |url|
error = assert_raises(Maptool::Routing::RouteError) { Maptool::Routing.route(url, [[1, 2], [3, 4]], Maptool::Routing::DEFAULT_VEHICLE.merge(weight: 7.5)) }
assert_equal "no route", error.message
end
assert_includes request, %("costing":"truck")
assert_raises(Maptool::Routing::Unavailable) { Maptool::Routing.route("", [[1, 2], [3, 4]], {}) }
end
def test_isochrone_asks_valhalla_for_each_time_and_checks_them
reply = JSON.generate(type: "FeatureCollection", features: [])
request = serve_once("HTTP/1.1 200 OK\r\nContent-Length: #{reply.bytesize}\r\n\r\n#{reply}") do |url|
assert_equal "FeatureCollection", Maptool::Routing.isochrone(url, [17.1, 48.1], [60, 30, 60], Maptool::Routing::DEFAULT_VEHICLE)["type"]
end
assert_includes request, %("contours":[{"time":30},{"time":60}])
assert_raises(Maptool::Routing::RouteError) { Maptool::Routing.isochrone("http://x", [17.1, 48.1], [600], {}) }
assert_raises(Maptool::Routing::RouteError) { Maptool::Routing.isochrone("http://x", nil, [30], {}) }
end
private
# Answers one HTTP request with `response`; returns what was received.
def serve_once(response)
server = TCPServer.new("127.0.0.1", 0)
received = +""
thread = Thread.new do
client = server.accept
received << client.readpartial(65_536)
received << client.readpartial(65_536) unless received.include?("{")
client.write(response)
client.close
end
yield "http://127.0.0.1:#{server.addr[1]}"
thread.join
received
ensure
server&.close
end
end
+44
View File
@@ -104,6 +104,50 @@
<div class="debug-panel__body"></div>
</div>
<div id="route-panel" class="basemap-panel" hidden>
<div class="basemap-panel__header">
<strong>Route</strong>
<button type="button" class="basemap-panel__close" aria-label="Close">&times;</button>
</div>
<!-- Filled by RoutePanelControl (public/js/route.js). -->
<div class="route-panel__body">
<p class="route-panel__hint">Click the map to add points (or "Add to route" on a search result or a library point); drag a marker to move it.</p>
<p class="route-panel__editing" hidden></p>
<ol class="route-panel__points"></ol>
<div class="route-panel__buttons">
<button type="button" data-action="position">+ My position</button>
<button type="button" data-action="reverse">Reverse</button>
<button type="button" data-action="clear">Clear</button>
<button type="button" data-action="save" hidden>Save to library</button>
</div>
<p class="route-panel__summary"></p>
<button type="button" class="route-panel__profile" hidden>Elevation profile</button>
<details class="route-panel__directions" hidden>
<summary>Directions</summary>
<ol></ol>
</details>
<div class="route-panel__reach">
<span>Reach in</span>
<select>
<option value="30">30 min</option>
<option value="60" selected>1 h</option>
<option value="120">2 h</option>
<option value="30,60,120">30 min · 1 h · 2 h</option>
</select>
<button type="button" data-action="reach">Show</button>
<button type="button" data-action="reach-clear" hidden>Hide</button>
</div>
<p class="route-panel__reach-status" hidden></p>
<fieldset class="route-panel__vehicle">
<legend>Vehicle</legend>
<label>Height <input type="number" name="height" step="0.1" min="1" max="6"> m</label>
<label>Width <input type="number" name="width" step="0.1" min="1" max="4"> m</label>
<label>Length <input type="number" name="length" step="0.5" min="2" max="25"> m</label>
<label>Weight <input type="number" name="weight" step="0.1" min="0.5" max="60"> t</label>
</fieldset>
</div>
</div>
<div id="offline-data-panel" class="basemap-panel" hidden>
<div class="basemap-panel__header">
<strong>Offline data</strong>
+2
View File
@@ -52,7 +52,9 @@
"/js/overlays.js": "/js/overlays.js?v=<%= ASSET_VERSION %>",
"/js/panels.js": "/js/panels.js?v=<%= ASSET_VERSION %>",
"/js/plugins.js": "/js/plugins.js?v=<%= ASSET_VERSION %>",
"/js/preview.js": "/js/preview.js?v=<%= ASSET_VERSION %>",
"/js/radar.js": "/js/radar.js?v=<%= ASSET_VERSION %>",
"/js/route.js": "/js/route.js?v=<%= ASSET_VERSION %>",
"/js/share_import.js": "/js/share_import.js?v=<%= ASSET_VERSION %>",
"/js/search.js": "/js/search.js?v=<%= ASSET_VERSION %>",
"/js/shadow.js": "/js/shadow.js?v=<%= ASSET_VERSION %>",