Skip to content

Instantly share code, notes, and snippets.

@cjwinchester
Created September 17, 2018 22:55
Show Gist options
  • Save cjwinchester/f7a945097700ca022179a61ef127c579 to your computer and use it in GitHub Desktop.
Save cjwinchester/f7a945097700ca022179a61ef127c579 to your computer and use it in GitHub Desktop.
Quick CLI duder to geocode a place and return coordinates
####################################################
# quick bash script to geocode a place name and #
# load tab-separated coordinates to clipboard #
# (n.b. uses osx `pbcopy`, so swap in whatever #
# works for your os in the last line) #
# #
# you'll need jq and an opencage geocode API key, #
# which i stored in an environment variable called #
# $OPENCAGE_GEOCODE_API #
# #
# example usage: ./geocode.sh "pavillion, wy" #
# #
# https://stedolan.github.io/jq/ #
# https://opencagedata.com #
####################################################
# check that something got passed to the script
if [ "$1" == "" ]; then
echo "gotta hand me a place name to geocode, bub"
exit 1
fi
# replace spaces with %20
ORIGINAL_PLACE=$1
PLACE=${ORIGINAL_PLACE// /%20}
# make the API call and hand results off to jq, targeting "geometry" in the result
GEOM=$(curl -s "https://api.opencagedata.com/geocode/v1/json?q=$PLACE&key=$OPENCAGE_GEOCODE_KEY&limit=1&pretty=1" | jq '.results[0].geometry')
# ~~~ TODO - check to make sure we actually got something back ~~~
# grab lat and lng
LAT=$(echo $GEOM | jq '.lat')
LNG=$(echo $GEOM | jq '.lng')
# lemme know what happened
echo "Coordinates copied for $ORIGINAL_PLACE: $LAT, $LNG"
# load tab-separated coordinates pair into my clipboard
echo $LAT'\t'$LNG | pbcopy
@cjwinchester
Copy link
Author

(i use this mainly for one-off things where i need to copy/paste lat/lng pairs into a spreadsheet next to a place name but i don't need to roll up A Whole Thing ( manually filling in small bits of missing data, etc.))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment