A Complete Example
Letâs work through an example of using geo.js to attempt to get the userâs location and display a map of the immediate surroundings.
When the page loads, it will need to call geo_position_js.init()
to determine whether
geolocation is available through any of the interfaces that
geo.js supports. If so, you can set up a link the
user can click to look up her location. Clicking that link calls the
lookup_location()
function, shown
here:
function lookup_location() { geo_position_js.getCurrentPosition(show_map, show_map_error); }
If the user gives consent to track her location,
and the backend service was actually able to
determine that location, geo.js calls the first
callback function, show_map()
, with a
single argument, loc
. The loc
object has a coords
property that contains latitude,
longitude, and accuracy information. (This example doesnât use the
accuracy information.) The rest of the show_map()
function uses the Google Maps API to
set up an embedded map:
function show_map(loc) { $("#geo-wrapper").css({'width':'320px','height':'350px'}); var map = new GMap2(document.getElementById("geo-wrapper")); var center = new GLatLng(loc.coords.latitude, loc.coords.longitude); map.setCenter(center, 14); map.addControl(new GSmallMapControl()); map.addControl(new GMapTypeControl()); map.addOverlay(new GMarker(center, {draggable: false, title: "You are here (more or less)"})); }
If geo.js is unable to determine the location,
it calls the second callback function, show_map_error() ...
Get HTML5: Up and Running now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.