Where are you? How to write a geosensitive application
Archive - Originally posted on "The Horse's Mouth" - 2013-09-18 19:46:55 - Graham Ellis
So - how would you write this geolocation into you code?
I have a simple page [here] which uses Javascript to ask the user to permit his location to be used (that's built in to modern browsers) then submits it up as a form. You'll find lots of sophisticated examples on line... I have tried to keep mine simple to show you what's happening.
1. When you load the page, it runs the Javascript:
<body onload='reportwhere()'>
2. The reportwere function runs the built in geolocation, passing the values it gets to two other functions which I've called nextpage and errhandler - the first if the user approves of his location being sent to the server, the second if he does not approve or geolocation isn't working:
function reportwhere() {
navigator.geolocation.getCurrentPosition(nextpage,errhandler);
}
3. These two functions save the status code, and location if it's available, into variables which are passed in to another function which calls up the next page
function nextpage(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
post_to_url("http://www.wellho.net/twapp/railinfo.php",{'scode':0, 'lati':latitude, 'longi':longitude})
}
function errhandler(problem) {
var whatswrong = problem.code;
post_to_url("http://www.wellho.net/twapp/railinfo.php",{'scode':whatswrong})
}
4. Here's that function that calls up the next page:
function post_to_url(url, params) {
var form = document.createElement('form');
form.action = url;
form.method = 'GET';
for (var i in params) {
if (params.hasOwnProperty(i)) {
var input = document.createElement('input');
input.type = 'hidden';
input.name = i;
input.value = params[i];
form.appendChild(input);
}
}
form.submit();
}
Moving on, I've pointed that form at a short piece of PHP code (full source [here] which will report on which railway stations you're nearest to, indicating which are busiest and adding a link to live departure boards. Again this is a prototype...
Illustration - Melksham's Spa Houses, dating from 1815.