Files
website/assets/scripts/map.sh
2025-11-19 06:59:37 -08:00

53 lines
1.3 KiB
Bash

#!/usr/bin/env bash
set -euo pipefail
command_check() {
local MISSING=()
for cmd in "$@"; do
if ! command -v "$cmd" >/dev/null 2>&1; then
MISSING+=("$cmd")
fi
done
if [[ ${#MISSING[*]} -gt 0 ]]; then
echo "Error: Missing required programs:" >&2
for cmd in "${MISSING[@]}"; do
echo " - $cmd" >&2
done
exit 1
fi
}
command_check curl jq
if [[ ! -t 0 ]]; then
QUERY="$(cat)"
elif [[ $# -gt 0 ]]; then
QUERY="$*"
else
printf "Create a map link for a location.\n"
printf "Address? "
read -r QUERY
fi
ENCODED_QUERY="${QUERY// /%20}"
LOCATION_JSON="$(curl -s "https://nominatim.openstreetmap.org/search?q=$ENCODED_QUERY&limit=2&format=json")"
if ! jq empty <<<"$LOCATION_JSON" 2>/dev/null; then
echo "Error: Something wrong, invalid JSON for location query." >&2
exit 1
fi
coordinate() {
local COOR="$1"
local VALUE
VALUE="$(jq -r ".[0].$COOR" <<<"$LOCATION_JSON")"
if [[ "$VALUE" =~ ^-?[0-9]+([.][0-9]+)?$ ]]; then
echo "$VALUE"
else
echo "Error: Not a number" >&2
echo "Usage: $0 <address>" >&2
echo "Query was: $QUERY" >&2
echo "Encoded query was: $ENCODED_QUERY" >&2
echo "Location JSON was: $LOCATION_JSON" >&2
exit 1
fi
}
LAT="$(coordinate lat)"
LON="$(coordinate lon)"
echo "https://www.openstreetmap.org/?mlat=$LAT&mlon=$LON#map=16/$LAT/$LON"