Created
August 4, 2018 13:19
-
-
Save amitlzkpa/fdbd8a2f95d887d241881fb9f866e882 to your computer and use it in GitHub Desktop.
Used for an ethereum smart-contract project to store coordinates as int256 in Solidity.
This file contains 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
function pad(n, len=6) { | |
n = n.toString(); | |
n.trim(); | |
let q = n.length; | |
for(let i=q; i<len; i++) { | |
n = "0"+n; | |
} | |
return n; | |
} | |
function parseToFxLengStr(n) { | |
let isNeg = n < 0; | |
let m = n.toFixed(3).toString().replace('.', '').replace('-', ''); | |
m = pad(m); | |
if(isNeg) m = "1" + m; | |
else m = "0" + m; | |
return m | |
} | |
// Encode world coordinates as ints. | |
function encodeCoord(coord) { | |
let la = parseToFxLengStr(coord.Latitude); | |
let lo = parseToFxLengStr(coord.Longitude); | |
let loc = la + lo; | |
let i = parseInt(loc); | |
return i; | |
} | |
// decode a string representation of the coordinates to a coordinate object | |
function decodeCoord(str) { | |
let paddedStr = pad(str, 14); | |
let laEnc = paddedStr.slice(0, 7); | |
let loEnc = paddedStr.slice(7, paddedStr.length); | |
let laIsNeg = (laEnc.charAt(0) == '1'); | |
let loIsNeg = (loEnc.charAt(0) == '1'); | |
laEnc = laEnc.slice(1, laEnc.length); | |
loEnc = loEnc.slice(1, loEnc.length); | |
laEnc = [laEnc.slice(0, 3), '.', laEnc.slice(3)].join(''); | |
loEnc = [loEnc.slice(0, 3), '.', loEnc.slice(3)].join(''); | |
let la = parseFloat(laEnc) * ((laIsNeg) ? -1 : 1); | |
let lo = parseFloat(loEnc) * ((loIsNeg) ? -1 : 1); | |
return { "latitude": la, "longitude": lo }; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment