Google Maps saved lists from a scheduled Google Takeout: hourly check of TAKEOUT_DIR (brick's Drive backup, mounted read-only), the zip with Takeout/Saved/*.csv picked by its central directory (photo parts skipped), each list into Google Maps/<list>; positions decoded offline from the place's S2 feature id and refined by Nominatim, unresolved ones flagged approximate in the popup (cleared when moved by hand); points matched by Google id per folder, so a new export updates them (own color/icon/position kept, deleted stay deleted)
CI / check (push) Successful in 8m56s
CI / deploy (push) Successful in 38s

This commit is contained in:
randy committed 2026-11-25 15:10:30 +01:00
1 parent 261b4c053e
commit 0aee739ac3
9 files changed
+306 -1

No files matched your search

+150
View File
@@ -0,0 +1,150 @@
require "csv"
require "json"
require "net/http"
require "uri"
require "zip"
module Maptool
# Google Maps saved lists ("Want to go", "Norway 2026", …) from a Google
# Takeout export: product "Saved", one Takeout/Saved/<list>.csv each with
# Title,Note,URL,Tags,Comment. The URL carries no coordinates, only the
# place's feature id (…/data=!4m2!3m1!1s0x45de3cbf60603ce7:0x82f2b236d153558f),
# whose first half is an S2 cell id around the place: decoded offline it's
# within a few hundred metres to a few km (the low bits look hashed), then
# refined by a Nominatim name search around it. A place Nominatim can't
# find keeps the decoded spot and `approximate: true`.
module GoogleSaved
FEATURE_ID = /!1s(0x\h+):(0x\h+)/
SAVED_ENTRY = %r{\ATakeout/Saved/[^/]+\.csv\z}
NOMINATIM = "https://nominatim.openstreetmap.org/search"
# Search box around the decoded spot, degrees (~10 km).
REFINE_RADIUS = 0.1
# A CSV Google wrote (header Title,…,URL)? Other Takeout CSVs aren't lists.
def self.saved_list?(text)
text.sub(/\A/, "").start_with?("Title,Note,URL")
end
# CSV text → GeoJSON point features, unrefined. `source_id` is Google's
# feature id: Library updates a point with the same one in the same
# folder instead of adding it again.
def self.features(text)
CSV.parse(text.sub(/\A/, ""), headers: true).filter_map do |row|
url = row["URL"].to_s
match = url.match(FEATURE_ID)
coords = url[%r{/maps/search/(-?\d+\.\d+),[+\s]*(-?\d+\.\d+)}] && [Regexp.last_match(2).to_f, Regexp.last_match(1).to_f]
approximate = coords.nil?
coords ||= match && s2_lng_lat(match[1].to_i(16))
next unless coords
name = row["Title"].to_s.strip
name = "Saved place" if name.empty?
# One text the point popup shows and linkifies: the list's note and
# comment, then the way back to the place in Google Maps.
description = [row["Note"], row["Comment"], "Google Maps: #{url}"].map { |t| t.to_s.strip }.reject(&:empty?).join("\n\n")
props = { "name" => name, "description" => description,
"source_id" => (match ? "google:#{match[1]}:#{match[2]}" : "google:#{url}"),
"approximate" => (true if approximate) }.compact
{ "type" => "Feature", "geometry" => { "type" => "Point", "coordinates" => coords.map { |c| c.round(6) } }, "properties" => props }
end
end
# Moves each approximate feature onto `lookup.(name, lng, lat)` → [lng,
# lat] or nil; one that isn't found stays approximate.
def self.refine!(features, lookup: method(:nominatim))
features.each do |feature|
props = feature["properties"]
next unless props["approximate"]
found = lookup.call(props["name"], *feature["geometry"]["coordinates"])
next unless found
feature["geometry"]["coordinates"] = found.map { |c| c.round(6) }
props.delete("approximate")
end
end
# Nominatim's usage policy: at most 1 request a second, an identifying
# User-Agent.
def self.nominatim(name, lng, lat)
sleep 1
r = REFINE_RADIUS
uri = URI(NOMINATIM)
uri.query = URI.encode_www_form(q: name, format: "jsonv2", limit: 1, bounded: 1,
viewbox: [lng - r, lat + r, lng + r, lat - r].join(","))
response = Net::HTTP.start(uri.host, uri.port, use_ssl: true, open_timeout: 10, read_timeout: 20) do |http|
http.request(Net::HTTP::Get.new(uri, "User-Agent" => "maptool (Google saved lists import)"))
end
hit = response.is_a?(Net::HTTPSuccess) && JSON.parse(response.body).first
hit && [hit["lon"].to_f, hit["lat"].to_f]
rescue JSON::ParserError, Net::OpenTimeout, Net::ReadTimeout, SocketError, SystemCallError, OpenSSL::SSL::SSLError
nil
end
# Each Takeout zip in `dir` holding saved lists, newest first: only the
# zip's central directory is read, so the multi-GB photo parts of the
# same export are cheap to skip.
def self.takeout_zips(dir)
Dir.glob(File.join(dir, "*.zip")).select do |path|
Zip::File.open(path) { |zip| zip.entries.any? { |e| e.name.match?(SAVED_ENTRY) } }
rescue Zip::Error
false
end.sort_by { |path| -File.mtime(path).to_f }
end
# { "<list name>" => csv text } for the zip's saved lists.
def self.lists(zip_path)
Zip::File.open(zip_path) do |zip|
zip.entries.select { |e| e.name.match?(SAVED_ENTRY) }
.to_h { |e| [File.basename(e.name, ".csv"), e.get_input_stream.read.force_encoding("UTF-8")] }
.select { |_, text| saved_list?(text) }
end
end
# Imports the newest Takeout zip in `dir` with saved lists, once (its
# name, size and mtime are remembered in `state_path`), each list into
# "<folder>/<list name>". Returns the number of places, nil if nothing new.
def self.import_takeout(dir, library:, state_path:, folder: "Google Maps", lookup: method(:nominatim))
zip = takeout_zips(dir).first or return nil
stamp = [File.basename(zip), File.size(zip), File.mtime(zip).to_i].join(" ")
return nil if File.exist?(state_path) && File.read(state_path) == stamp
count = lists(zip).sum do |list, text|
places = features(text)
next 0 if places.empty? # Images / Saved for later: no places, no folder
refine!(places, lookup: lookup)
library.import_features(places, folder: "#{folder}/#{list.tr('/', '_')}")
places.size
end
File.write(state_path, stamp)
count
end
# S2 cell id → [lng, lat] of the cell's center (the S2 library's
# face/Hilbert-curve decoding, quadratic projection).
POS_TO_IJ = [[0, 1, 3, 2], [0, 2, 3, 1], [3, 2, 0, 1], [3, 1, 0, 2]].freeze
POS_TO_ORIENTATION = [1, 0, 0, 3].freeze
def self.s2_lng_lat(id)
face = id >> 61
i = j = 0
orientation = face & 1
30.times do |k|
bits = (id >> (59 - 2 * k)) & 3
ij = POS_TO_IJ[orientation][bits]
i = (i << 1) | (ij >> 1)
j = (j << 1) | (ij & 1)
orientation ^= POS_TO_ORIENTATION[bits]
end
uv = lambda do |n|
s = (n + 0.5) / (1 << 30)
s >= 0.5 ? (4 * s * s - 1) / 3.0 : (1 - 4 * (1 - s) * (1 - s)) / 3.0
end
u = uv.call(i)
v = uv.call(j)
x, y, z = [[1, u, v], [-u, 1, v], [-u, -v, 1], [-1, -v, -u], [v, -1, -u], [v, u, -1]][face]
[Math.atan2(y, x) * 180 / Math::PI, Math.atan2(z, Math.hypot(x, y)) * 180 / Math::PI]
end
end
end
+44
View File
@@ -234,6 +234,12 @@ module Maptool
add_features(features, folder, source: relative)
end
# Already-parsed features (GoogleSaved) into `folder`, same rules as an
# upload minus the stored source file.
def import_features(features, folder:)
add_features(features, folder)
end
# FIT (and many TCX/GPX) tracks carry no name of their own: those take
# the file's, so the tree doesn't fill up with "Track".
def default_name(source)
@@ -312,6 +318,9 @@ module Maptool
props = (feature["properties"] || {}).except("id")
write do |db, rev, now|
# Moved by hand: an imported approximate position (GoogleSaved) is checked now.
old = db.get_first_value("SELECT geometry FROM items WHERE id = ?", [id])
props.delete("approximate") if old && round(JSON.parse(old)) != round(feature["geometry"])
db.execute("UPDATE items SET name = ?, geometry = ?, properties = ?, updated_at = ?, rev = ? WHERE id = ? AND deleted_at IS NULL",
[props["name"], JSON.generate(feature["geometry"]), JSON.generate(props), now, rev, id])
raise NotFound if db.changes.zero?
@@ -598,6 +607,11 @@ module Maptool
props = (f["properties"] || {}).compact
props["name"] = default_name(source) if source && props["name"].to_s.empty? && %w[track route].include?(type)
fingerprint = Digest::SHA1.hexdigest(JSON.generate([type, props["name"], round(f["geometry"])]))
if props["source_id"]
id = upsert_by_source_id(db, target, props, f["geometry"], rev, now)
keys << "points:#{target || ROOT}" if id
next
end
existing = db.get_first_value("SELECT id FROM items WHERE folder_id IS ? AND fingerprint = ? AND deleted_at IS NULL", [target, fingerprint])
id = existing
unless existing
@@ -615,6 +629,36 @@ module Maptool
keys.uniq
end
# A feature that names where it came from (`source_id`, e.g. a Google
# saved place's id) is kept once per folder: importing the list again
# refreshes the point's name and Google's fields, keeping what was
# changed here (color, icon, a moved position — only an approximate
# position gives way to an exact one). One deleted here stays deleted.
# Returns the id, nil when skipped.
def upsert_by_source_id(db, folder, props, geometry, rev, now)
row = db.get_first_row("SELECT id, geometry, properties, deleted_at FROM items WHERE folder_id IS ? AND json_extract(properties, '$.source_id') = ?",
[folder, props["source_id"]])
unless row
id = SecureRandom.uuid
db.execute("INSERT INTO items VALUES (?, ?, NULL, 'point', ?, ?, ?, NULL, NULL, ?, ?, NULL, ?)",
[id, folder, props["name"], JSON.generate(geometry), JSON.generate(props.except("id")), now, now, rev])
return id
end
id, old_geometry, old_props, deleted = row
return nil if deleted
old = JSON.parse(old_props)
merged = old.merge(props.except("id", "approximate"))
exact = old["approximate"] && !props["approximate"]
merged.delete("approximate") if exact
new_geometry = exact ? JSON.generate(geometry) : old_geometry
return id if merged == old && new_geometry == old_geometry
db.execute("UPDATE items SET name = ?, geometry = ?, properties = ?, updated_at = ?, rev = ? WHERE id = ?",
[props["name"], new_geometry, JSON.generate(merged), now, rev, id])
id
end
def item_type(feature)
geometry = feature.dig("geometry", "type").to_s
props = feature["properties"] || {}