The code below works, but I'm wondering where things could be improved. I'm attempting to wrap the Geolocation API and would greatly appreciate any suggestions.
import jsffi
type
GPError* = enum
PERMISSION_DENIED = 1
POSITION_UNAVAILBLE = 2
TIMEOUT = 3
PositionOptions {.importc.} = ref object
enableHighAccuracy: bool
timeout: uint
maximumAge: uint
GeolocationCoordinates {.importc.} = ref object
latitude: float
longitude: float
altitude: float
accuracy: float
altitudeAccuracy: float
heading: float
speed: float
GeolocationPositionError {.importc.} = ref object
code: GPError
message: cstring
GeolocationPosition {.importc.} = ref object
coords: GeolocationCoordinates
timestamp: int
var navigator {.importc, nodecl.}: JsObject
proc geolocation(navigator: JsObject): bool {.importcpp: "#.geolocation".}
proc getCurrentPosition(navigator: JsObject, success: proc(
position: GeolocationPosition), error: proc(
err: GeolocationPositionError)){.
importcpp: "#.geolocation.getCurrentPosition(#,#)".}
proc watchPosition(navigator: JsObject, success: proc(
position: GeolocationPosition), error: proc(
err: GeolocationPositionError)): int {.
importcpp: "#.geolocation.watchPosition(#,#)".}
proc clearWatch(navigator: JsObject, id: int) {.
importcpp: "#.geolocation.clearWatch(#)".}
# tests
proc showPosition(position: GeolocationPosition) =
echo "Lat = " & $position.coords.latitude
echo "Lon = " & $position.coords.longitude
echo "Date " & $position.timestamp
proc showError(error: GeolocationPositionError) =
echo $error.message
echo $error.code
var watchID: int
proc geoMe(){.exportc.} =
if navigator.geolocation:
echo "Geolocation is supported"
getCurrentPosition(navigator, showPosition, showError)
proc watchMe(){.exportc.} =
if navigator.geolocation:
watchID = watchPosition(navigator, showPosition, showError)
proc stopWatching() {.exportc.} =
clearWatch(navigator, watchID)
echo "Not Watching..."
And html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title></title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="">
</head>
<body>
<button id="find-me" , onclick=geoMe()>Show my location</button><br />
<button id="watch-me" , onclick=watchMe()>Watch</button><br />
<button id="stop-watch" , onclick=stopWatching()>Clear Watch</button><br />
<p id="status"></p>
<a id="map-link" target="_blank"></a>
<script src="main.js"></script>
</body>
</html>
Didn't know about standardjs. Nice to see the indexeddb there.
No git repo yet.
I guess more specifically, I'm wondering if there is a better way to handle the Navigator and geolocation object in the code above. std/dom has Navigator implemented but no geolocation.