Sunday, April 7, 2013

GPS with jQuery Mobile

Having never developed on a mobile platform before, I was very curious about using the GPS feature within a web page. Having seen a "request to access my GPS" when I viewed certain sites, I knew it was possible. After a little research I found it was much easier than I through thanks to jQuery mobile.

You must download jQuery and jQuery mobile. I also used the jQuery mobile css.

Click here for demo


<!DOCTYPE html>
<html>
<head>
<meta name=viewport content="user-scalable=no,width=device-width" />
<link rel=stylesheet href="jquery.mobile-1.3.0/jquery.mobile-1.3.0.min.css" />
<script src="jquery-1.9.1.min.js"></script>
<script src="jquery.mobile-1.3.0/jquery.mobile-1.3.0.js"></script>
</head>
<body>

<div data-role=page id=home>
  <div data-role=header><h1>Where Am I?</h1></div>

  <div data-role=content>
  <span> Status : </span> <span id=stat></span> <br />
    <span> Time : </span> <span id=time></span> <br />
<span> Latitude : </span> <span id=lat></span> <br />
    <span> Longitude : </span> <span id=lng></span> <br />
  </div>

  <input type="button" name="ss" value="" id="ss">

  <div id="out1" style="width:96%; height:200px; overflow:scroll; border:1px solid #000; margin-left:2%;"></div>
</div>

</body>
</html>

<script>
(function($) {

$.fn.changeButtonText = function(newText) {
return this.each(function() {
$this = $(this);
if( $this.is('a') ) {
$('span.ui-btn-text',$this).text(newText);
return;
}
if( $this.is('input') ) {
$this.val(newText);
// go up the tree
var ctx = $this.closest('.ui-btn');
$('span.ui-btn-text',ctx).text(newText);
return;
}
});
};

var runGPS = 0;
$("#ss").changeButtonText('Start');
$("#stat").text('Paused');

$('#ss').click(function() {
if (runGPS == 1){
$("#stat").text('Paused');
$("#ss").changeButtonText('Start');
runGPS = 0;
} else {
$("#stat").text('Running');
$('#ss').changeButtonText("Stop");
runGPS = 1;
}
});

var timer = setInterval(function(){
if (runGPS == 1){
navigator.geolocation.getCurrentPosition (function (pos)
{
date = new Date();
$("#time").text (date);

var lat = pos.coords.latitude;
var lng = pos.coords.longitude;
$("#lat").text (lat);
$("#lng").text (lng);

var t = date + " lat:" + lat + "lng:" + lng + "<br>";

$("#out1").append(t);

});
}
},2000);

})(jQuery);
</script>

No comments:

Post a Comment