Geolocation

Objectives

Geolocation basics

  1. geolocation may not be available
  2. devices have many ways for obtaining their location: IP address, wireless connection points, satellite GPS
  3. the web page may have to be on a server for geolocation to work
  4. retrieving position: navigator.geolocation.getCurrentPosition(handlerFunction)
  5. watching a position: navigator.geolocation.watchPosition(handlerFunction)
  6. clearing a position watch: navigator.geolocation.clearWatch()
  7. Google static maps API

In-class demonstration code

<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title></title> <script> var url; function $(id) { return document.getElementById(id); } function loadMap(zoom) { $('map').src = url + "&zoom=" + zoom; } function setZoom() { var zoom = $('zoomlevel').value; if (!zoom.match(/^[0-9]+$/)) { $('zoomlevel').value = ""; $('msg').innerHTML = "Illegal zoom value"; } else { zoom = parseInt(zoom); if (zoom < 1 || zoom > 20) { $('zoomlevel').value = ""; $('msg').innerHTML = "Zoom value out of range (1-20)"; } else { loadMap(zoom); $('msg').innerHTML = ""; } } return false; } function showMap() { if (!navigator.geolocation) { $('container').innerHTML = "Your browser does not support geolocation." } else { navigator.geolocation.getCurrentPosition(function (pos) { var lat = pos.coords.latitude; var lng = pos.coords.longitude; var acc = pos.coords.accuracy; url = "http://maps.google.com/maps/api/staticmap?center=" + lat + "," + lng + "&size=320x320&sensor=true"; loadMap(10); }); } } window.onload = showMap; </script> <style> h1 { text-align: center; } #container { border: 1px solid #000000; width: 320px; height: 320px; margin: 0 auto; } #frm { margin-top: 1em; display: block; text-align: center; } </style> </head> <body> <h1>You are here</h1> <div id="container"><img id="map" width="320" height="320" src="" /></div> <form id="frm"> <label for="zoomlevel">Zoom (1-20): </label>   <input type="text" id="zoomlevel" required pattern="^(([1-9])|([12][0-9]))$" />   <input type="submit" value="Zoom" onclick="return setZoom();" onkeydown="$('msg').innerHTML = '';"><br> <label id="msg"></label> </form> </body> </html>