Question

Scribunto is a MediaWiki-hosted version of Lua.
I believe it is fairly standard Lua.

I want to convert geographic coordinates from this format:

42°33'N, 1°33'E

... to this format:

42.55|1.55

How to do this in Scribunto?

Was it helpful?

Solution

This assumes the input string is strictly of the form in the post. If there's any variability e.g. it can omit the minutes, include seconds, latitude and longitude can be separated differently, or whatever, the pattern will need to change.

function translate_coords(str)
    assert(type(str)=="string")
    local patt = "(%d+)°(%d+)'([NS]), (%d+)°(%d+)'([WE])"
    local latd,latm,latdir,lngd,lngm,lngdir = string.match(str,patt)
    assert(latd and latm and latdir)
    assert(lngd and lngm and lngdir)
    latd = latdir=="S" and -latd or latd
    lngd = lngdir=="W" and -lngd or lngd
    return ""..(latd+latm/60).."|"..(lngd+lngm/60)

end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top