diff --git a/docs/public/scripts/getLongLatFromAddress.js b/docs/public/scripts/getLongLatFromAddress.js index 5766672aa..4160272ab 100644 --- a/docs/public/scripts/getLongLatFromAddress.js +++ b/docs/public/scripts/getLongLatFromAddress.js @@ -1,36 +1,46 @@ +// Geocodes an address with OpenStreetMap's free Nominatim API and stores the +// coordinates in the active note's `location` property as `lat,lng`, the +// front matter format that the Map View plugin reads and writes itself. module.exports = async (params) => { - const {createYamlProperty} = params.app.plugins.plugins["metaedit"].api; - const address = await params.quickAddApi.inputPrompt("🏠 Address"); - if (!address) { - new Notice("No address given", 5000); + const {app, obsidian, quickAddApi} = params; + + const activeFile = app.workspace.getActiveFile(); + if (!activeFile) { + new obsidian.Notice("No active file", 5000); return; } - const result = await apiGet(address); - if (!result.length) { - new Notice("No results found", 5000); + const address = await quickAddApi.inputPrompt("🏠 Address"); + if (!address) { + new obsidian.Notice("No address given", 5000); return; } - const {lat, lon} = result[0]; - - const activeFile = params.app.workspace.getActiveFile(); - if (!activeFile) { - new Notice("No active file", 5000); + let results; + try { + results = await geocode(obsidian, address); + } catch (error) { + console.error("getLongLatFromAddress: geocoding failed", error); + new obsidian.Notice(`Could not look up "${address}": ${error?.message ?? error}`, 8000); + return; + } + if (!results.length) { + new obsidian.Notice(`No results found for "${address}"`, 5000); return; } - await createYamlProperty("location", `[${lat}, ${lon}]`, activeFile); -} + const {lat, lon} = results[0]; + await app.fileManager.processFrontMatter(activeFile, (frontmatter) => { + frontmatter.location = `${lat},${lon}`; + }); +}; +async function geocode(obsidian, address) { + const url = new URL("https://nominatim.openstreetmap.org/search"); + // URLSearchParams encodes the address, so characters like `&` and `#` + // stay part of the query instead of cutting it short. + url.search = new URLSearchParams({q: address, format: "json", limit: "1"}).toString(); -async function apiGet(searchQuery) { - let finalURL = new URL(`https://nominatim.openstreetmap.org/search?q=${searchQuery}&format=json`); - - return await fetch(finalURL, { - method: 'GET', cache: 'no-cache', - headers: { - 'Content-Type': 'application/json', - }, - }).then(async (res) => await res.json()); -} \ No newline at end of file + const response = await obsidian.requestUrl({url: url.toString()}); + return response.json; +} diff --git a/docs/src/content/docs/docs/Examples/Macro_AddLocationLongLatFromAddress.md b/docs/src/content/docs/docs/Examples/Macro_AddLocationLongLatFromAddress.md index d83404b8c..7cb373e07 100644 --- a/docs/src/content/docs/docs/Examples/Macro_AddLocationLongLatFromAddress.md +++ b/docs/src/content/docs/docs/Examples/Macro_AddLocationLongLatFromAddress.md @@ -4,11 +4,12 @@ description: Macro and user script that geocode an address into a location latit slug: docs/Examples/Macro_AddLocationLongLatFromAddress --- -This macro asks you for an address, looks up its coordinates, and adds a `location` property with `[lat, long]` as its value to the note you have open. It is especially useful for the [Obsidian Map View plugin](https://github.com/esm7/obsidian-map-view), which reads that property to place notes on a map. +This macro asks you for an address, looks up its coordinates, and sets a `location` property on the note you have open. The value has the form `lat,lng`, for example `location: 48.8582599,2.2945006`. That is the front matter format the [Obsidian Map View plugin](https://github.com/esm7/obsidian-map-view) recommends and writes itself, so Map View places the note on its map. ## Before you start -- The [MetaEdit plugin](https://github.com/chhoumann/MetaEdit) must be installed and enabled. This macro uses MetaEdit's `createYamlProperty` function to write the property. +- The script looks up addresses with [Nominatim](https://nominatim.org/), OpenStreetMap's free geocoding service. It needs an internet connection but no account or API key. Nominatim uses the first match, so a specific address (street, city, country) gives the best result. +- No other plugin is needed to write the property. Install Map View if you want to see your notes on a map. ## Setup @@ -20,14 +21,18 @@ This macro asks you for an address, looks up its coordinates, and adds a `locati ## What you get -Run the macro with the `QuickAdd: Run` command in the command palette and pick your choice. Enter an address, and QuickAdd adds a `location` property to the active note whose value is `[lat, long]` for that address. +Open the note you want to place, run the macro with the `QuickAdd: Run` command in the command palette, and pick your choice. Enter an address, and QuickAdd sets the note's `location` property to that address's coordinates: -![Demo](../Images/longLatDemo.gif) +```yaml +--- +location: 48.8582599,2.2945006 +--- +``` -:::note -If you have MetaEdit's edit mode set to **All Multi**, remove the braces on line 23 of the script so it reads: +If the note already has a `location` property, the script replaces its value. If Nominatim finds no match, you get a notice and the note is left unchanged. -```js -await createYamlProperty("location", `${lat}, ${lon}`, activeFile); -``` +![The Eiffel Tower note's location property, and its pin in Map View](../Images/examples/macro-location-map-view.png) + +:::note +Earlier versions of this script needed MetaEdit to write the property, and this page told MetaEdit users in **All Multi** mode to edit the script. The script now writes the property with Obsidian's own API, so MetaEdit and its edit mode no longer matter. Locations written by the old script keep working in Map View. If you use a different property name for locations in Map View's settings, change `frontmatter.location` in the script to match. ::: diff --git a/docs/src/content/docs/docs/Images/examples/macro-location-map-view.png b/docs/src/content/docs/docs/Images/examples/macro-location-map-view.png new file mode 100644 index 000000000..d96117d3f Binary files /dev/null and b/docs/src/content/docs/docs/Images/examples/macro-location-map-view.png differ diff --git a/docs/src/content/docs/docs/Images/longLatDemo.gif b/docs/src/content/docs/docs/Images/longLatDemo.gif deleted file mode 100644 index efb95ab66..000000000 Binary files a/docs/src/content/docs/docs/Images/longLatDemo.gif and /dev/null differ diff --git a/tests/examples/getLongLatFromAddress.test.ts b/tests/examples/getLongLatFromAddress.test.ts new file mode 100644 index 000000000..62e58635e --- /dev/null +++ b/tests/examples/getLongLatFromAddress.test.ts @@ -0,0 +1,154 @@ +import { readFileSync } from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { describe, expect, it, vi } from "vitest"; + +const scriptPath = path.resolve( + path.dirname(fileURLToPath(import.meta.url)), + "../../docs/public/scripts/getLongLatFromAddress.js", +); + +type Entry = (params: unknown) => Promise; + +function loadScript(): Entry { + const source = readFileSync(scriptPath, "utf8"); + const module = { exports: {} as Entry }; + new Function("module", "exports", source)(module, module.exports); + return module.exports; +} + +function run(options: { + address?: string; + results?: Array<{ lat: string; lon: string }>; + frontmatter?: Record; + activeFile?: boolean; + requestError?: Error; +}) { + const frontmatter = options.frontmatter ?? {}; + const notices: string[] = []; + const requestUrl = vi.fn(async (_request: { url: string }) => { + if (options.requestError) throw options.requestError; + return { json: options.results ?? [] }; + }); + const processFrontMatter = vi.fn( + async (_file: unknown, fn: (fm: Record) => void) => + fn(frontmatter), + ); + const inputPrompt = vi.fn(async () => options.address); + + const params = { + app: { + workspace: { + getActiveFile: () => + options.activeFile === false ? null : { path: "Place.md" }, + }, + fileManager: { processFrontMatter }, + }, + obsidian: { + requestUrl, + Notice: class { + constructor(message: string) { + notices.push(message); + } + }, + }, + quickAddApi: { inputPrompt }, + }; + + return { + done: loadScript()(params), + frontmatter, + notices, + requestUrl, + processFrontMatter, + inputPrompt, + }; +} + +describe("getLongLatFromAddress example script", () => { + it("writes the first result as a Map View `lat,lng` string and keeps other properties", async () => { + const ctx = run({ + address: "Eiffel Tower, Paris", + results: [ + { lat: "48.8582599", lon: "2.2945006" }, + { lat: "1", lon: "2" }, + ], + frontmatter: { tags: ["travel"] }, + }); + await ctx.done; + + expect(ctx.frontmatter).toEqual({ + tags: ["travel"], + location: "48.8582599,2.2945006", + }); + expect(ctx.notices).toEqual([]); + }); + + it("replaces an existing location", async () => { + const ctx = run({ + address: "Colosseum, Rome", + results: [{ lat: "41.8909421", lon: "12.4919030" }], + frontmatter: { location: "[47.5939700, 14.1245600]" }, + }); + await ctx.done; + + expect(ctx.frontmatter.location).toBe("41.8909421,12.4919030"); + }); + + it("sends the whole address to Nominatim, including `&` and `#`", async () => { + const address = "AT&T Stadium #1, Arlington, Texas"; + const ctx = run({ + address, + results: [{ lat: "32.7478503", lon: "-97.0928337" }], + }); + await ctx.done; + + const url = new URL(ctx.requestUrl.mock.calls[0][0].url); + expect(url.origin + url.pathname).toBe( + "https://nominatim.openstreetmap.org/search", + ); + expect(url.searchParams.get("q")).toBe(address); + expect(url.searchParams.get("format")).toBe("json"); + expect(url.hash).toBe(""); + }); + + it("leaves the note unchanged and shows a notice when nothing is found", async () => { + const ctx = run({ address: "nowhere", results: [] }); + await ctx.done; + + expect(ctx.processFrontMatter).not.toHaveBeenCalled(); + expect(ctx.notices).toEqual(['No results found for "nowhere"']); + }); + + it("shows a notice and leaves the note unchanged when the lookup fails", async () => { + const ctx = run({ + address: "Paris", + requestError: new Error("Request failed, status 429"), + }); + vi.spyOn(console, "error").mockImplementation(() => undefined); + await expect(ctx.done).resolves.toBeUndefined(); + + expect(ctx.processFrontMatter).not.toHaveBeenCalled(); + expect(ctx.notices).toEqual([ + 'Could not look up "Paris": Request failed, status 429', + ]); + }); + + it("does not prompt or geocode without an active file", async () => { + const ctx = run({ activeFile: false, address: "Paris" }); + await ctx.done; + + expect(ctx.inputPrompt).not.toHaveBeenCalled(); + expect(ctx.requestUrl).not.toHaveBeenCalled(); + expect(ctx.notices).toEqual(["No active file"]); + }); + + it("does not geocode when the prompt is cancelled", async () => { + const ctx = run({ address: undefined }); + await ctx.done; + + expect(ctx.requestUrl).not.toHaveBeenCalled(); + expect(ctx.processFrontMatter).not.toHaveBeenCalled(); + expect(ctx.notices).toEqual(["No address given"]); + }); +});