randomfox (randomfox) wrote,
randomfox
randomfox

Vim: Convert ddd mm.mmm coordinates to decimal degrees

This Vim macro converts coordinates from "N ddd mm.mmm W ddd mm.mmm" to "dd.ddddd -dd.ddddd".


" ------------------------------------------------------------------
" For converting coordinates from N ddd mm.mmm W ddd mm.mmm to 
" dd.ddddd -dd.ddddd

function! ToDecimals(deg, minwhole, mindec)
    " Trim leading zeros so that the string won't be treated as octal.
    let deg = substitute(a:deg, "^0*", "", "")
    let minwhole = substitute(a:minwhole, "^0*", "", "")

    " Force the decimal portion of the minutes to be 3 decimal places.
    " And then trim leading zeros.
    let mindec = strpart(a:mindec, 0, 3)
    let mindec = mindec . strpart("000", 0, 3 - strlen(mindec))
    let mindec = substitute(mindec, "^0*", "", "")

    let val = (minwhole * 1000000 + mindec * 1000 + 30) / 60
    return deg . "." . strpart("000000", 0, 6 - strlen(val)) . val
endfunction

function! ConvertCoords()
    let coord = '\(\d\+\)\s\+\(\d\+\).\(\d\+\)'
    let x = substitute(getline("."), 'N\s*' . coord . '\s\+W\s*' . coord, '\=ToDecimals(submatch(1), submatch(2), submatch(3)) . "\<cr>-" . ToDecimals(submatch(4), submatch(5), submatch(6))', "")
    execute "normal o" . x . "\<esc>"
endfunction

nmap <f12>g :call ConvertCoords()<cr>
vmap <f12>g <esc>:call ConvertCoords()<cr>
imap <f12>g <esc>:call ConvertCoords()<cr>

Subscribe
  • Post a new comment

    Error

    Anonymous comments are disabled in this journal

    default userpic

    Your reply will be screened

    Your IP address will be recorded 

  • 0 comments