HTML5 JavaScript GeolocationAPI with Example

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 = ""; // Thanks to Wikipedia function drawMap(position){ canvas.getContext().width=map_image.width; canvas.getContext().height=map_image.height;"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."; }

Explore OakFrame

    Basic Programing with Javascript

    Welcome to the OakFrame Interactive Basic Programming with Javascript course. This course is provided through an...


    Play games in your browser for free, handcrafted by us here at OakFrame!

    Oak Studio Documentation

    Simple to Embed and Integrate We designed OakFrame to be easy to extend in order to provide further integration...

    Design Systems

    A complete, reliable, flexible, and cost-effective infrastructure is a fundamental requirement in modern companies....

    About OakFrame

    OakFrame is a design, development, and research firm located in Dallas, Texas, developing experiences for audiences...