First, let’s set up a helper function that is going to convert coordinate latitude and longitude to a pixel X and Y position. This will be useful for displaying our coordinates on a 2d image of a map, which we’ll be doing later.
function coordinatesToXY(image_size_x, image_size_y, coords){
return {
x : (image_size_x) * (180 + coords.latitude) / 360,
y : (image_size_y) * (90 - coords.longitude) / 180
}
}
With the returned data, we’re going draw our map, and then a circle at our returned X and Y position.
canvas = new Oak.Rendering.Surface();
print(canvas.getElement());
map_image = new Image();
map_image.src = "https://upload.wikimedia.org/wikipedia/commons/thumb/8/8e/BlankMap_World_simple.svg/1200px-BlankMap_World_simple.svg.png"; // Thanks to Wikipedia
function drawMap(position){
canvas.getContext().width=map_image.width;
canvas.getContext().height=map_image.height;
canvas.element.style.width="100%";
canvas.fill("blue");
canvas.getContext().drawImage(map_image,0,0, canvas.getContext().width, canvas.getContext().height);
canvas.getContext().beginPath();
canvas.getContext().arc(position.x, position.y, 6, 0, 2 * Math.PI);
canvas.getContext().stroke();
}
Lets set up a handler function that will be called with the Geolocation information as an argument.
function handlePosition(position) {
print( "Latitude: " + position.coords.latitude +
"
Longitude: " + position.coords.longitude);
drawMap(coordinatesToXY(canvas.getContext().width, canvas.getContext().height, {longitude:parseFloat(position.coords.longitude),latitude:parseFloat(position.coords.latitude)}));
}
Now, let’s request the current position from the user and set the function we’ve just made as the callback.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(handlePosition);
} else {
return "Geolocation is not supported by this browser.";
}