Geolocation using PhoneGap on Android works only on index.html - javascript

I'm trying to use geolocation using PhoneGap API doc, geolocation works on the index.html
but when I try to use the same function in a different page it doesn't work.
http://docs.phonegap.com/en/1.8.1/cordova_geolocation_geolocation.md.html#Geolocation
This is the JS I'm using.
This is the button I'm using to get to the other page.
I'm also using jQuery Mobile.
Add category</li>
here is the head of test.html
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title></title>
<link rel="stylesheet" href="styles/jquery.mobile-1.1.0.min.css" />
<link rel="stylesheet" href="styles/jquery.mobile.structure-1.1.0.min.css" />
<link rel="stylesheet" href="styles/jquery.mobile.theme-1.1.0.min.css" />
<link rel="stylesheet" href="styles/my.css" />
<script src="scripts/jquery-1.7.2.min.js"></script>
<script src="scripts/jquery.mobile-1.1.0.min.js"></script>
<script src="scripts/cordova-1.8.1.js"></script>
<script>
// Wait for Cordova to load
//
document.addEventListener("deviceready", onDeviceReady, false);
var watchID = null;
// Cordova is ready
//
function onDeviceReady() {
// Throw an error if no update is received every 30 seconds
var options = { timeout: 10000 };
watchID = navigator.geolocation.watchPosition(onSuccess, onError, options);
}
// onSuccess Geolocation
//
function onSuccess(position) {
var element = document.getElementById('geolocation');
element.innerHTML = 'Latitude: ' + position.coords.latitude + '<br />' +
'Longitude: ' + position.coords.longitude + '<br />' +
'<hr />' + element.innerHTML;
}
// onError Callback receives a PositionError object
//
function onError(error) {
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}
</script>

First give permissions in Android Manifest:
android.permission.ACCESS_FINE_LOCATION
android.permission.ACCESS_LOCATION_EXTRA_COMMANDS
android.permission.ACCESS_COARSE_LOCATION
then copy your cordova-1.8.1.js and create index.html inside www subfolder of assets and after that copy cordova-1.8.1.jar to libs and then configure build path with cordova-1.8.1.jar.
then create res-->xml and copy plugins(from earlier downloaded PhoneGap 1.8.1).
then run the application. Definitely you will get the output.

The problem was I didn't load the cordova.jar file to my project and that's why it didn't work

Related

Phonegap build Geolocation not working

js: i use simple alert to display the location, and use phonegap build to compile. Device ready alert is shown! But not any other alerts!
document.addEventListener("deviceready", getDeviceLocation , false);
function getDeviceLocation () {
alert('device ready');
navigator.geolocation.getCurrentPosition(showPosition, showError, { enableHighAccuracy: true } );
}
function showPosition(position) {
alert('show postion called');
alert("Latitude: " + position.coords.latitude +
"Longitude: " + position.coords.longitude);
}
function showError(error) {
alert('show error called');
alert("Errorcode: " + error.code +
"Errormessage: "+ error.message );
}
html:the html page is as follows:
<!DOCTYPE html>
<html ng-app>
<head>
<link rel="stylesheet" href="style.css">
<!--<link rel="stylesheet" href="bootstrap.css">-->
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="bootstrap.css">
<!-- Latest compiled and minified JavaScript -->
<script src="angular.min.js"></script>
<script src="cordova.js"></script>
<script src="angular.animate.min.js"></script>
<script src="angular.route.min.js"></script>
<link rel="stylesheet" href="font-awesome.css">
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
</head>
<body>
</body>
<script type="text/javascript" src="pro.js"></script>
<script type="text/javascript" src="bootstrap.js"></script>
<script type="text/javascript" src="script.js"></script>
</html>
This code works for me. Hope will help you.
newMapForGuest: function()
{
// setting here default latitude and longitude in case geolocation does not work.
var defaultLatLng = new google.maps.LatLng(1.290, 103.851);
if ( navigator.geolocation )
{
function success(pos) // function will call on success
{
alert('Latitude: '+ pos.coords.latitude +' Longitude: '+pos.coords.longitude);
}
function fail(error) // function will call on fail
{
alert('error message: ' +error);
}
// intializing geolocation to get current position
navigator.geolocation.getCurrentPosition(success, fail, {maximumAge: 500000, enableHighAccuracy:true, timeout: 10000});
}
else
{
// in case geolocation does not work then call code mentioned here.
}
},

Finding the UUID of the device - UniqueDeviceID plugin

Trying to retrieve the Unique device ID of the Device .
Using the plugin - UniqueDeviceID
When tring to run the following code
var exec = require('cordova/exec');
module.exports = {
get: function(success, fail) {
cordova.exec(success, fail, 'UniqueDeviceID', 'get', []);
}
};
`
I am getting the following error-
"Uncaught ReferenceError: module is not defined"
This is indeed defined in cordova.js
How do i fix this issue.
Thanks in advance
The get method needs to be called in the device.ready() of the application initialization.
Placing it elsewhere lead to the above mentioned error , worked fine for me .
There is an in built function, for getting uuid:
var string = device.uuid;
Full Example:
<!DOCTYPE html>
<html>
<head>
<title>Device Properties Example</title>
<script type="text/javascript" charset="utf-8" src="cordova.js"></script>
<script type="text/javascript" charset="utf-8">
// Wait for device API libraries to load
//
document.addEventListener("deviceready", onDeviceReady, false);
// device APIs are available
//
function onDeviceReady() {
var element = document.getElementById('deviceProperties');
element.innerHTML = 'Device Model: ' + device.model + '<br />' +
'Device Cordova: ' + device.cordova + '<br />' +
'Device Platform: ' + device.platform + '<br />' +
'Device UUID: ' + device.uuid + '<br />' +
'Device Version: ' + device.version + '<br />';
}
</script>
</head>
<body>
<p id="deviceProperties">Loading device properties...</p>
</body>
</html>
Kindly, visit this link:
http://docs.phonegap.com/en/3.1.0/cordova_device_device.md.html#device.uuid
See, if that helps.
I used the UniqueDeviceID Plugin from this link: https://www.npmjs.com/package/cordova-plugin-uniquedeviceid
Very simple and powerful. Tried to unistall and reinstall the app and still returned the same UUID.
Two changes I had to make to make this plugin work for me:
1. The above link mentions to add a separate line to the config.xml file. I followed the same and I was unable to build my app. I removed the line and it works fine.
2. Also add a loop for the fail case just like the success case shown, otherwise there is a runtime error.
function fail(error) {
console.log(error); };

Cordova and multi core plugins won't work together

I'm currently learning this and am trying to get more than one core plugin to work in my app, I've been coding manually then submitting it to phonegap to build and test. Now I've got cordova setup on windows 7, followed the instructions from adobe documentation.
Making more than one core plugin into a app which phonegap then builds for me does not work. The only code I've used is in adobe's phonegaps documentation on version 3.5. If you use one core plugin however it works. All the code that you require for this question is in their documentation.
Code: index.html
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="css/themes/default/jquery.mobile-1.4.3.min.css" />
<link rel="stylesheet" href="css/animate.min.css" />
<script src="js/jquery.js"></script>
<script src="js/jquery.mobile-1.4.3.min.js"></script>
<script src="cordova.js"></script>
<script>
</script>
</head>
<body>
<!--/////////////////////////////Home - API \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\-->
<div data-role="page" id="home">
<div data-role="header">
<h1>API</h1>
</div><!-- /header -->
<div role="main" class="ui-content">
<ul data-role="listview">
<li>Accelerometer</li>
<li>GPS</li>
<li>Compass</li>
</ul>
</div><!-- /content -->
<div data-role="footer" data-position="fixed">
<h4>Joshua</h4>
</div><!-- /footer -->
</div><!-- /page -->
<!--/////////////////////////////Home - API - END \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\-->
<!--/////////////////////////////Accel - API \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\-->
<div data-role="page" id="accel">
<div data-role="header">
<h1>Accelerometer</h1>
</div><!-- /header -->
<script>
// The watch id references the current `watchAcceleration`
var AccelID = null;
// Wait for device API libraries to load
//
function readyAccel() {
document.addEventListener("deviceready", onDeviceReadyAccel, false);
}
// device APIs are available
//
function onDeviceReadyAccel() {
startAccel();
}
// Start watching the acceleration
//
function startAccel() {
// Update acceleration every .1 seconds
var options = { frequency: 100 };
AccelID = navigator.accelerometer.watchAcceleration(onSuccess, onError, options);
}
// Stop watching the acceleration
//
function stopAccel() {
if (AccelID) {
navigator.accelerometer.clearWatch(AccelID);
AccelID = null;
}
}
// onSuccess: Get a snapshot of the current acceleration
//
function onSuccess(acceleration) {
var element = document.getElementById('accelerometer');
element.innerHTML = 'Acceleration X: ' + acceleration.x + '<br />' +
'Acceleration Y: ' + acceleration.y + '<br />' +
'Acceleration Z: ' + acceleration.z + '<br />' +
'Timestamp: ' + acceleration.timestamp + '<br />';
}
// onError: Failed to get the acceleration
//
function onError() {
alert('onError!');
}
if(!isset($element)) {
alert('failed');
}
</script>
</head>
<body>
<div id="accelerometer">Waiting for accelerometer...</div>
<button onclick="stopAccel();">Stop Watching</button>
</div>
<!--/////////////////////////////Accel - API - END \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\-->
<!--/////////////////////////////GPS - API \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\-->
<div data-role="page" id="gps">
<div data-role="header">
<h1>GPS</h1>
</div>
<script>
// Wait for device API libraries to load
//
function readyGPS() {
document.addEventListener("deviceready", onDeviceReadyGeo, false);
}
var GeoID = null;
// device APIs are available
//
function onDeviceReadyGeo() {
// Get the most accurate position updates available on the
// device.
var options = { enableHighAccuracy: true };
GeoID = navigator.geolocation.watchPosition(onSuccess, onError, options);
}
// onSuccess Geolocation
//
function onSuccess(position) {
var element = document.getElementById('geolocation');
element.innerHTML = 'Latitude: ' + position.coords.latitude + '<br />' +
'Longitude: ' + position.coords.longitude + '<br />' +
'<hr />' + element.innerHTML;
}
// clear the watch that was started earlier
//
function clearGeo() {
if (GeoID != null) {
navigator.geolocation.clearWatch(GeoID);
GeoID = null;
}
}
// onError Callback receives a PositionError object
//
function onError(error) {
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}
////////Default Script Start\\\\\\\\\\
// // Wait for device API libraries to load
// //
// document.addEventListener("deviceready", onDeviceReady, false);
//
// var watchID = null;
//
// // device APIs are available
// //
// function onDeviceReady() {
// // Get the most accurate position updates available on the
// // device.
// var options = { enableHighAccuracy: true };
// watchID = navigator.geolocation.watchPosition(onSuccess, onError, options);
// }
//
// // onSuccess Geolocation
// //
// function onSuccess(position) {
// var element = document.getElementById('geolocation');
// element.innerHTML = 'Latitude: ' + position.coords.latitude + '<br />' +
// 'Longitude: ' + position.coords.longitude + '<br />' +
// '<hr />' + element.innerHTML;
// }
//
// // clear the watch that was started earlier
// //
// function clearWatch() {
// if (watchID != null) {
// navigator.geolocation.clearWatch(watchID);
// watchID = null;
// }
// }
//
// // onError Callback receives a PositionError object
// //
// function onError(error) {
// alert('code: ' + error.code + '\n' +
// 'message: ' + error.message + '\n');
// }
//////////Default Script End\\\\\\\\\\\\\\\\\
</script>
</head>
<body>
<!--
<p id="geolocation">Watching geolocation...</p>
<button onclick="clearGeo();">Clear Location</button>
-->
<p id="geolocation">Watching geolocation...</p>
<button onclick="clearWatch();">Clear Watch</button>
</div>
<!--/////////////////////////////GPS - API - END \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\-->
<!--/////////////////////////////COMPASS - API \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\-->
<div data-role="page" id="compass">
<div data-role="header">
<h1>Compass</h1>
</div>
<script>
// The watch id references the current `watchHeading`
var CompassID = null;
// Wait for device API libraries to load
//
function readyCompass() {
document.addEventListener("deviceready", onDeviceReadyCompass, false);
}
// device APIs are available
//
function onDeviceReadyCompass() {
startCompass();
}
// Start watching the compass
//
function startCompass() {
// Update compass every .1 seconds
var options = { frequency: 100 };
CompassID = navigator.compass.watchHeading(onSuccess, onError, options);
}
// Stop watching the compass
//
function stopCompass() {
if (CompassID) {
navigator.compass.clearWatch(CompassID);
CompassID = null;
}
}
// onSuccess: Get the current heading
//
function onSuccess(heading) {
var element = document.getElementById('heading');
element.innerHTML = 'Heading: ' + heading.magneticHeading;
}
// onError: Failed to get the heading
//
function onError(compassError) {
alert('Compass error: ' + compassError.code);
}
</script>
</head>
<body>
<div id="heading">Waiting for heading...</div>
<button onclick="stopCompass();">Stop Compass</button>
</div>
<!--/////////////////////////////COMPASS - API - END \\\\\\\\\\\\\\\\\\\\\\\\\\\\\-->
</body>
</html>
Code: config.xml
<?xml version='1.0' encoding='utf-8'?>
<widget id="io.cordova.hellocordova" version="0.0.1" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0">
<preference name="loglevel" value="DEBUG" />
<preference name="AndroidLaunchMode" value="singleTop" />
<feature name="App">
<param name="android-package" value="org.apache.cordova.App" />
</feature>
<feature name="Accelerometer">
<param name="android-package" value="org.apache.cordova.devicemotion.AccelListener" />
</feature>
<feature name="Compass">
<param name="android-package" value="org.apache.cordova.deviceorientation.CompassListener" />
</feature>
<name>App Multi</name>
<description>
"Multi plugins"
</description>
<author email="email#address.com" href="http://google.com">
Joshua
</author>
<content src="index.html" />
<access origin="*" />
</widget>
I've changed the watchID's to see if it was in conflict with other plugins however this did not work.
Link to JS of API's:-
Accelerometer : https://github.com/apache/cordova-plugin-device-motion/blob/master/doc/index.md
GPS : https://github.com/apache/cordova-plugin-geolocation/blob/master/doc/index.md
I cannot post more than two links so I think you can find the compass pretty easily from phonegaps documentation.

$(document).ready function won't fire up

I'm building a project made of several jquery mobile pages, each has a navbar.
when I view each page the $(document).ready function fires up well, but when I go to the page through the navbar it won't fire up.. also in the chrome debugger I see only one html page (the one I'm currently viewing) in the source folder.
when I refresh the page the function works ok
tried to replace the "$(document).ready(function () {" with:
"$("div[data-role*='page']").live('pageshow', function(event, ui) {" as someone suggested
but that doesn't work as well.
that's the first page I load:
<!DOCTYPE html>
<html>
<head>
<title>My Page</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="css/jquery.mobile-1.2.0.min.css" rel="stylesheet" type="text/css" />
<script src="js/jquery-1.8.2.min.js" type="text/javascript"></script>
<script src="js/jquery.mobile-1.2.0.min.js" type="text/javascript"></script>
<link href="css/TableCSSCode.css" rel="stylesheet" type="text/css" />
<script>
$(document).ready(function () {
$.ajax({
type: "POST",
url: "getdata.aspx/return_member_list",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (res) {
var parsedData = JSON.parse(res.d);
var tableStr = "<table class='CSSTableGenerator'>";
$.each(parsedData, function () {
tableStr += "<tr><td>" + this.fName + "</td><td>" + this.lName + "</td></tr>";
});
tableStr += "</table>";
$('#tableDiv').html(tableStr);
},
error: function (res, msg, code) {
// log the error to the console
alert("The following error occured: " + msg + " " + code);
} //error
});
});
</script>
</head>
<body>
<div id="page1" data-role="page" data-theme="a">
<div data-role="header" data-theme="a">
<h1>חברי העמותה</h1>
</div>
<div data-role="navbar">
<ul>
<li>חברי העמותה</li>
<li>בניית צוות</li>
<li> בדיקה</li>
</ul>
</div>
<div data-role="content">
<div id="tableDiv"></div>
</div>
<div data-role="footer">
<h1>footer area</h1>
</div>
</div>
</body>
</html>
And below are the second and third page's head:
build.htm:
<head>
<title>My Page</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="css/jquery.mobile-1.2.0.min.css" rel="stylesheet" type="text/css" />
<script src="js/jquery-1.8.2.min.js" type="text/javascript"></script>
<script src="js/jquery.mobile-1.2.0.min.js" type="text/javascript"></script>
<link href="css/TableCSSCode.css" rel="stylesheet" type="text/css" />
<script type="text/javascript">
function save_crew()
{
p_num = new Object();
p_num.p1 = p1.value;
p_num.p2 = p2.value;
p_num.p3 = p3.value;
p_num.p4 = p4.value;
l_num = new Object();
l_num.l1 = l1.value;
l_num.l2 = l2.value;
l_num.l3 = l3.value;
s_num = new Object();
s_num.s1 = s1.value;
s_num.s2 = s2.value;
s_num.s3 = s3.value;
var photo = { 'p1': p_num.p1, 'p2': p_num.p2, 'p3': p_num.p3, 'p4': p_num.p4 };
var light = { 'l1': l_num.l1, 'l2': l_num.l2, 'l3': l_num.l3, 'l4': l_num.l4 };
var sound = { 's1': s_num.s1, 's2': s_num.s2, 's3': s_num.s3, 's4': s_num.s4 };
// Put the object into storage
localStorage.setItem('photo', JSON.stringify(photo));
localStorage.setItem('light', JSON.stringify(light));
localStorage.setItem('sound', JSON.stringify(sound));
// Retrieve the object from storage
var retrievedObject = localStorage.getItem('sound');
var ro = JSON.parse(retrievedObject);
alert(ro.s2);
window.location.href="test.htm";
}
</script>
</head>
test.htm:
<head>
<title>My Page</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="css/jquery.mobile-1.2.0.min.css" rel="stylesheet" type="text/css" />
<script src="js/jquery-1.8.2.min.js" type="text/javascript"></script>
<script src="js/jquery.mobile-1.2.0.min.js" type="text/javascript"></script>
<link href="css/TableCSSCode.css" rel="stylesheet" type="text/css" />
<script type="text/javascript">
$(document).ready(function () {
var sound_RO = localStorage.getItem('sound');
var photo_RO = localStorage.getItem('photo');
var light_RO = localStorage.getItem('light');
sound_RO = JSON.parse(sound_RO);
photo_RO = JSON.parse(photo_RO);
light_RO = JSON.parse(light_RO);
$.each(sound_RO, function (index, value) {
alert(value);
});
$.ajax({
type: "POST",
url: "getdata.aspx/return_prof",
data: "{prof:'צלם'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (res) {
var parsedData = JSON.parse(res.d);
$('[data-role="content"]').append('<div id="collapsible-set" data-role="collapsible-set"></div>');
$("#collapsible-set").append('<div id="collapsible" data-role="collapsible"></div>');
$("#collapsible").append('<h3>צלמים </h3>');
for (i = 0; parsedData[i] != null; i++) {
$("#collapsible").append('<p>' + parsedData[i].fName + ' ' + parsedData[i].lName + '</p>');
}
$('[data-role="content"]').trigger('create');
},
error: function (res, msg, code) {
// log the error to the console
alert("The following error occured: " + msg + " " + code);
} //error
});
});
</script>
</head>
Reason
When jQuery Mobile loads pages after the initial one (with ajax), it will only load its BODY content, which means any js or css file initialized in HEAD (and if it is not initialized in first loaded HTML) will be disregarded. So all your custom js code will never be executed.
Solution
Move all of your js code into the first HTML file
You should create a new js file, name it whatever you want. Put all of your js code (from every page) into it. Then initialize it in the first HTML file to load.
Move your js code into the page BODY
Simply open every page and move its javascript code from HEAD to the BODY. Because of this, javascript code will be loaded into the DOM and executed when page is shown.
Final thoughts
All of this is described in more details + examples in my other answer/article: Why I have to put all the script to index.html in jquery mobile
You should also think about switching to the jQuery Mobile page events instead of document ready. Document ready usually works correctly but sometimes it will trigger before page is loaded into the DOM. That why jQM page events must be used instead. They will make sure page content is triggered only after page is safely loaded into the DOM. To find out more take a look at this answer/article: jQuery Mobile: document ready vs page events

how to show google map and get coordinates on device through javascript code?

I did it in android but now i need to build app through phone-gap and i need to load map on the device and get current position coordinate(latitude and longitude) of the device.
So i need to have javascript code now and to be frank i am not much familiar with java script for now…Any code/help.
This is my code through which i am showing the map
Thanks
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0; padding: 0 }
#map_canvas { height: 100% }
</style>
<script type="text/javascript"
src="http://maps.googleapis.com/maps/api/js?key*****************&sensor=true">
</script>
<script type="text/javascript">
function initialize() {
var myOptions = {
center: new google.maps.LatLng(-34.397, 150.644),
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
}
</script>
</head>
<body onload="initialize()">
<div id="map_canvas" style="width:100%; height:100%"></div>
</body>
</html>
In the place of "*" i am having my google api key..
Now i need to get the coordinates…
modified and currently using this code got from the link http://docs.phonegap.com/en/1.0.0/phonegap_geolocation_geolocation.md.html but even then i am getting this error "KCLErrorDomain Error 0"
<!DOCTYPE html>
<html>
<head>
<title>Device Properties Example</title>
<script type="text/javascript" charset="utf-8" src="cordova-1.9.0.js"></script>
<script type="text/javascript" charset="utf-8">
document.addEventListener("deviceready", onDeviceReady, false);
var watchID = null;
function onDeviceReady() {
var options = { frequency: 5000 };
watchID = navigator.geolocation.watchPosition(onSuccess, onError, options);
}
function onSuccess(position) {
var element = document.getElementById('geolocation');
element.innerHTML = 'Latitude: ' + position.coords.latitude + '<br />' +
'Longitude: ' + position.coords.longitude + '<br />' +
'<hr />' + element.innerHTML;
}
function onError(error) {
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}
</script>
</head>
<body>
<p id="geolocation">locating coordinates...</p>
</body>
</html>
I am not getting how to solve this error…using xcode 4.0.1 for phonegap apps development and trying to run on 4.3 simulator..
Here a quote from the PhoneGap documentation on Geolocation (http://docs.phonegap.com/en/1.0.0/phonegap_geolocation_geolocation.md.html):
Geolocation provides location information for the device, such as latitude and longitude. Common sources of location information include Global Positioning System (GPS) and location inferred from network signals such as IP address, RFID, WiFi and Bluetooth MAC addresses, and GSM/CDMA cell IDs. No guarantee is given that the API returns the device's actual location.
This API is based on the W3C Geo location API Specification. Some devices already provide an implementation of this spec. For those devices, the built-in support is used instead of replacing it with PhoneGap's implementation. For devices that don't have geolocation support, PhoneGap's implementation should be compatible with the W3C specification.
So basically, you can use the HTML5 Geolocation API without having to worry about any differences in PhoneGap. If you want to get the user's position once, use navigator.geolocation.getCurrentPosition() and if you want to periodically be sent the user's position, use navigator.geolocation.watchPosition():
navigator.geolocation.watchPosition(locationSuccess, locationError, {timeout: 30000});
function locationSuccess(position)
{
// this is your position as a LatLng object. use it however you need
var latLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
}
function locationError(err)
{
if (err.code == 1)
alert("You must allow this website to use the Geolocation API to access your position.");
else if (err.code == 3)
alert("Unfortunately, your position request timed out.");
else
alert("Unfortunately, your position could not be determined.");
}

Categories