-
-
Notifications
You must be signed in to change notification settings - Fork 199
fix(docs): write Map View lat,lng location without MetaEdit in geocoding example #1810
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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()); | ||
| } | ||
| const response = await obsidian.requestUrl({url: url.toString()}); | ||
| return response.json; | ||
| } | ||
|
coderabbitai[bot] marked this conversation as resolved.
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Binary file added
BIN
+206 KB
docs/src/content/docs/docs/Images/examples/macro-location-map-view.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file not shown.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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<void>; | ||
|
|
||
| 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<string, unknown>; | ||
| 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<string, unknown>) => 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"]); | ||
| }); | ||
| }); |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.