jquery not working in phonegap android - android

i have this simple app , that works fine in a browser , but when building it using phonegap it's just shows a simple html page, means that jquery not working ,
in my page i call the jquery mobile.min.css ,jquery.min.js than this script :
$(document).bind("pagebeforechange", function (event, data) {
$.mobile.pageData = (data && data.options && data.options.pageData)
? data.options.pageData
: null;
});
$(document).ready( function (event) {
compSearch('');
$("#searchbtn").click(function () {
var sText = $("#searchtxt").val();
$("#search").dialog("close");
compSearch(sText)
});
});
function compSearch(searchString) {
var theUrl = serverName + "MobileService.asmx/getOrgPage";
var orgId = qString("org");
$.ajax({
type: "POST",
url: theUrl,
data: '{"OrgId":' + orgId +
',"SearchString":"' + searchString +
'"}',
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function (msg) {
var s = msg.d[0];
$("#header").html(s).trigger("create");
$("#footer").html(msg.d[3]).trigger("create");
$("#contentHeading").html(msg.d[1]);
$("#content").html(msg.d[2]).find("ul").listview();
$("#newscontent").html(msg.d[4]);
},
error: function (msg) {
alert('error ' + msg.d[0]);
}
});
}
$(document).on('pagebeforeshow', '#indivnews', function (event, data) {
if ($.mobile.pageData && $.mobile.pageData.np) {
var orgId = qString("org");
var itemId = $.mobile.pageData.np;
var theUrl = serverName + "MobileService.asmx/getNewsPage";
var clubName = "";
$.ajax({
type: "POST",
url: theUrl,
data: '{"orgId":' + orgId +
',"compId":' + 0 +
',"itemId":' + itemId +
',"clubName":"' + clubName +
'"}',
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function (msg) {
var s = msg.d[0];
$("#indivcontent").html(msg.d[4]);
},
error: function (msg) {
alert('error ' + msg.d[0]);
}
});
}
});
than the jquery mobile.min.js
like i said it's works fine in a browser,please if you have and idea to solve it
thank you.

It may be that you are loading the html page before PQ and JQM are properly initialized. I use the following in my project to ensure the framework is loaded correctly:
var deviceReadyDeferred = $.Deferred();
var jqmReadyDeferred = $.Deferred();
document.addEventListener("deviceReady", deviceReady, false);
function deviceReady() {
deviceReadyDeferred.resolve();
}
$(document).one("pageinit", function () {
jqmReadyDeferred.resolve();
});
$.when(deviceReadyDeferred, jqmReadyDeferred).then(frameworksLoaded);
function frameworksLoaded() {
$.support.cors = true;
$.mobile.allowCrossDomainPages = true;
jQm.allowCrossDomainPages = true;
console.log('PG & JQM ready');
}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width =device-width, initial-scale=1.0, user-scalable=no" />
<title>Test</title>
<link href="Example.css" rel="stylesheet" />
<link href="../www/Content/jquery.mobile-1.4.0.css" rel="stylesheet" />
<link href="../www/Content/jquery.mobile-1.4.0.min.css" rel="stylesheet" />
<script src="../www/Scripts/jquery-2.1.0.min.js"></script>
</head>
<body>
</body>
</html>
Reference to Deferred and Jquery Promises:
http://api.jquery.com/deferred.promise/

Related

Getting error while running my ionic project on devices

i am getting the following error on my device when running it,where as it runs withour erron on browser and only one of my device and check all the devices but same problem
can any one help me
Uncaught TypeError: Object.keys called on non-object ionic.bundle.js:9110
Failed to load resource: net::ERR_CACHE_MISS https://cdn.auth0.com/client/cWQeRf3L4Ength5tIFSrPhrNPUHgO6yQ.js?t1439965186084
Uncaught Error: [$rootScope:infdig] 10 $digest() iterations reached. Aborting!
Watchers fired in the last 5 iterations: []
http://errors.angularjs.org/1.3.13/$rootScope/infdig?p0=10&p1=%5B%5D ionic.bundle.js:22980
// Ionic Starter App
// angular.module is a global place for creating, registering and retrieving Angular modules
// 'starter' is the name of this angular module example (also set in a <body> attribute in index.html)
// the 2nd parameter is an array of 'requires'
// 'starter.controllers' is found in controllers.js
angular.module('starter', ['ionic', 'ngCordova', 'starter.controllers','starter.directives', 'auth0',
'angular-storage',
'angular-jwt', 'ngFileUpload','ngResource','ngRoute'])
.config(['$httpProvider', function($httpProvider) {
$httpProvider.defaults.useXDomain = true;
$httpProvider.defaults.headers.common = 'Content-Type: application/json';
delete $httpProvider.defaults.headers.common['X-Requested-With'];
}
])
.config(function($compileProvider){
$compileProvider.imgSrcSanitizationWhitelist(/^\s*(https?|file|blob|cdvfile|content):|data:image\//);
})
.run(function($ionicPlatform) {
$ionicPlatform.ready(function() {
// Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
// for form inputs)
if (window.cordova && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
}
if (window.StatusBar) {
// org.apache.cordova.statusbar required
StatusBar.styleDefault();
}
});
})
/*File factory for browse*/
.factory("$fileFactory", function($q) {
var File = function() { };
console.log("This is in file factory");
File.prototype = {
getParentDirectory: function(path) {
var deferred = $q.defer();
window.resolveLocalFileSystemURI(path, function(fileSystem) {
fileSystem.getParent(function(result) {
deferred.resolve(result);
}, function(error) {
deferred.reject(error);
});
}, function(error) {
deferred.reject(error);
});
return deferred.promise;
},
getEntriesAtRoot: function() {
var deferred = $q.defer();
console.log("This is in get Entries in root");
window.webkitrequestFileSystem(1, 0, function(fileSystem) {
var directoryReader = fileSystem.root.createReader();
directoryReader.readEntries(function(entries) {
deferred.resolve(entries);
}, function(error) {
deferred.reject(error);
});
}, function(error) {
deferred.reject(error);
});
return deferred.promise;
},
getEntries: function(path) {
var deferred = $q.defer();
window.resolveLocalFileSystemURI(path, function(fileSystem) {
var directoryReader = fileSystem.createReader();
directoryReader.readEntries(function(entries) {
deferred.resolve(entries);
}, function(error) {
deferred.reject(error);
});
}, function(error) {
deferred.reject(error);
});
return deferred.promise;
}
};
return File;
})
.factory('Post', function($resource) {
return $resource('http://104.155.192.54:8080/api/logins');
})
.config(function($compileProvider){
$compileProvider.imgSrcSanitizationWhitelist(/^\s*(https?|ftp|mailto|file|tel):/);
})
/*This is file browser in ionic */
.factory('Camera', ['$q', function($q) {
return {
getPicture: function(options) {
var q = $q.defer();
navigator.camera.getPicture(function(result) {
// Do any magic you need
q.resolve(result);
}, function(err) {
q.reject(err);
}, options);
return q.promise;
}
}
}])
.config(['$httpProvider', function($httpProvider) {
$httpProvider.defaults.useXDomain = true;
$httpProvider.defaults.headers.common = 'Content-Type: application/json';
delete $httpProvider.defaults.headers.common['*'];
}
])
.factory('merchantRegisterFactory', function($http) {
var urlBase = 'http://104.155.192.54:8080/api/merchantlogins';
var _loginService = {};
_loginService.getLogins = function() {
return $http.get(urlBase);
};
_loginService.saveLogin = function(login) {
console.log("This is factory is merchantlogins app.js save");
return $http.post(urlBase,login);
};
_loginService.updateLogin = function(login) {
return $http.put(urlBase, login);
};
_loginService.deleteLogin = function(id) {
return $http.delete(urlBase + '/' + id);
};
return _loginService;
})
.factory('addOffer', function($http) {
var urlBase = 'http://104.155.192.54:8080/api/addoffers';
var _addofferService = {};
_addofferService.getOffers = function() {
return $http.get(urlBase);
};
_addofferService.saveOffer = function(login) {
console.log("This is factory is addoffers app.js save");
return $http.post(urlBase,login);
};
_addofferService.updateoffer = function(login) {
return $http.put(urlBase, login);
};
_addofferService.deleteOffer = function(id) {
return $http.delete(urlBase + '/' + id);
};
return _addofferService;
})
.factory('loginsFactory', function($http) {
var urlBase = 'http://104.155.192.54:8080/api/logins';
var _loginService = {};
_loginService.getLogins = function() {
return $http.get(urlBase);
};
_loginService.saveLogin = function(login) {
console.log("This is factory Login is app.js save");
return $http.post(urlBase,login);
};
_loginService.updateLogin = function(login) {
return $http.put(urlBase, login);
};
_loginService.deleteLogin = function(id) {
return $http.delete(urlBase + '/' + id);
};
return _loginService;
})
.run(function($rootScope, auth, store, jwtHelper, $location) {
// This events gets triggered on refresh or URL change
var refreshingToken = null;
$rootScope.$on('$locationChangeStart', function() {
var token = store.get('token');
var refreshToken = store.get('refreshToken');
if (token) {
if (!jwtHelper.isTokenExpired(token)) {
if (!auth.isAuthenticated) {
auth.authenticate(store.get('profile'), token);
}
} else {
if (refreshToken) {
if (refreshingToken === null) {
refreshingToken = auth.refreshIdToken(refreshToken).then(function(idToken) {
store.set('token', idToken);
auth.authenticate(store.get('profile'), idToken);
}).finally(function() {
refreshingToken = null;
});
}
return refreshingToken;
} else {
$location.path('/login');
}
}
}
});
})
.config(function($stateProvider, $urlRouterProvider, authProvider, $httpProvider,
jwtInterceptorProvider) {
jwtInterceptorProvider.tokenGetter = function(store, jwtHelper, auth) {
var idToken = store.get('token');
var refreshToken = store.get('refreshToken');
// If no token return null
if (!idToken || !refreshToken) {
return null;
}
// If token is expired, get a new one
if (jwtHelper.isTokenExpired(idToken)) {
return auth.refreshIdToken(refreshToken).then(function(idToken) {
store.set('token', idToken);
return idToken;
});
} else {
return idToken;
}
}
$httpProvider.interceptors.push('jwtInterceptor');
$stateProvider
.state('app', {
url: "/app",
abstract: true,
templateUrl: "templates/menu.html",
controller: 'AppCtrl'
})
.state('app.addoffer', {
url: "/addoffer",
views: {
'menuContent': {
templateUrl: "templates/addoffer.html",
controller: 'MapCtrl'
}
}
})
.state('app.browse', {
url: "/browse",
views: {
'menuContent': {
templateUrl: "templates/browse.html"
}
}
})
.state('app.playlists', {
cache: false,
url: "/playlists",
views: {
'menuContent': {
templateUrl: "templates/playlists.html",
controller: 'ExampleController'
}
}
})
.state('app.single', {
cache: false,
url: "/playlists/:playlistId",
views: {
'menuContent': {
templateUrl: "templates/playlist.html",
controller: 'ExampleController'
}
}
});
authProvider.init({
domain: 'lokaloffers.auth0.com',
clientID: 'cWQeRf3L4Ength5tIFSrPhrNPUHgO6yQ',
loginState: 'login'
});
// if none of the above states are matched, use this as the fallback
$urlRouterProvider.otherwise('/app/playlists');
})
.run(function(auth) {
// This hooks all auth events to check everything as soon as the app starts
auth.hookEvents();
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
<meta http-equiv="Content-Security-Policy" content="default-src *; style-src * &apos;unsafe-inline&apos;; script-src * &apos;unsafe-inline&apos; &apos;unsafe-eval&apos;">
<title></title>
<!-- compiled css output -->
<link href="css/ionic.app.css" rel="stylesheet">
<link href="css/animate.css" rel="stylesheet">
<link href="lib/ionic/css/ionic.css" rel="stylesheet">
<link href="css/style.css" rel="stylesheet">
<!-- IF using Sass (run gulp sass first), then uncomment below and remove the CSS includes above -->
<!-- <link href="css/ionic.app.css" rel="stylesheet">-->
<!-- ionic/angularjs js -->
<script type="text/javascript" src="lib/ionic/js/ionic.bundle.js"></script>
<!-- ngCordova script -->
<script type="text/javascript" src="lib/ngCordova/dist/ng-cordova.js"></script>
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript" src="lib/angular-resource/angular-resource.js"></script>
<script type="text/javascript" src="lib/ng-file-upload/ng-file-upload-shim.min.js"></script>
<script type="text/javascript" src="lib/ng-file-upload/ng-file-upload.min.js"></script>
<!-- Auth0 Lock -->
<script type="text/javascript" src="lib/auth0-lock/build/auth0-lock.js"></script>
<!-- auth0-angular -->
<script type="text/javascript" src="lib/auth0-angular/build/auth0-angular.js"></script>
<!-- angular storage -->
<script type="text/javascript" src="lib/a0-angular-storage/dist/angular-storage.js"></script>
<!-- angular-jwt -->
<script type="text/javascript" src="lib/angular-jwt/dist/angular-jwt.js"></script>
<!--
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCqGXcExPSUxrVMpnfBciUejJRU06ZYelE&sensor=true"></script>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&libraries=places&signed_in=true"></script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyC_cy8C8pj5urqUSWERE-qU8NmkoNg6jpk&sensor=true"></script>
-->
<!-- your app's js -->
<script type="text/javascript" src="js/app.js"></script>
<script type="text/javascript" src="js/app1.js"></script>
<script type="text/javascript" src="js/directives.js"></script>
<script type="text/javascript" src="lib/angular-route/angular-route.min.js"></script>
<script type="text/javascript" src="lib/angular-route/angular-route.js"></script>
<script type="text/javascript" src="js/app.js"></script>
<script type="text/javascript" src="js/factory.js"></script>
<script type="text/javascript" src="js/controllers.js"></script>
<script type="text/javascript" src="js/countries.js"></script>
<script type="text/javascript" charset="utf-8">
// Wait for Cordova to load
//
document.addEventListener("deviceready", onDeviceReady, false);
// Cordova is loaded and it is now safe to make calls Cordova methods
//
function onDeviceReady() {
checkConnection();
}
function checkConnection() {
var networkState = navigator.connection.type;
var states = {};
states[Connection.UNKNOWN] = 'Unknown connection';
states[Connection.ETHERNET] = 'Ethernet connection';
states[Connection.WIFI] = 'WiFi connection';
states[Connection.CELL_2G] = 'Cell 2G connection';
states[Connection.CELL_3G] = 'Cell 3G connection';
states[Connection.CELL_4G] = 'Cell 4G connection';
states[Connection.NONE] = 'No network connection';
alert('Connection type: ' + states[networkState]);
}
</script>
</head>
<body ng-app="starter">
<ion-nav-view></ion-nav-view>
</body>
</html>
HI Thanks for the suggession but i solved my problem its the error with ionic CLI ,updated it to latest and it works fine

Error 3 File-Transfer Cordova

I'm developing an application that will have to send images to an external server, downloaded and installed the file-transfer , however it stopped working appearing error 3, I am running xampp on my local network, below is my code, I took it from the plugin documentation
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>File Transfer 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() {
// Retrieve image file location from specified source
navigator.camera.getPicture(
uploadPhoto,
function(message) { alert('get picture failed'); },
{
quality : 50,
destinationType : navigator.camera.DestinationType.FILE_URI,
sourceType : navigator.camera.PictureSourceType.PHOTOLIBRARY
}
);
}
function uploadPhoto(imageURI) {
var options = new FileUploadOptions();
options.fileKey="file";
options.fileName=imageURI.substr(imageURI.lastIndexOf('/')+1);
options.mimeType="image/jpeg";
var params = {};
params.value1 = "test";
params.value2 = "param";
options.params = params;
var ft = new FileTransfer();
ft.upload(imageURI, encodeURI("http://192.168.0.105/upload/index.php"), win, fail, options);
}
function win(r) {
console.log("Code = " + r.responseCode);
console.log("Response = " + r.response);
console.log("Sent = " + r.bytesSent);
}
function fail(error) {
alert("An error has occurred: Code = " + error.code);
console.log("upload error source " + error.source);
console.log("upload error target " + error.target);
}
</script>
</head>
<body>
<h1>Example</h1>
<p>Upload File</p>
</body>
</html>
PHP:
<?php
$new_image_name = strtolower($_FILES['file']['name']);
move_uploaded_file($_FILES["file"]["tmp_name"], "images/".$new_image_name);
Add the header object to option once.
Solution from here
options.headers = {
Connection: "close"
}

Not able to get the geolocation in Android emulator

I'm doing a small sample app which displays latitude and longitude in a popup when i click on the button
here is my code
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>BlankCordovaApp1</title>
<link href="css/index.css" rel="stylesheet" />
<script src="cordova.js"></script>
<script src="scripts/platformOverrides.js"></script>
<script src="scripts/index.js"></script>
<script type="text/javascript" charset="utf-8">
var alertmsg = function (position) {
var msg = 'Latitude: ' + position.coords.latitude + '<br />' +
'Longitude: ' + position.coords.longitude + '<br />'
navigator.notification.alert(msg);
}
function geoLocation() {
navigator.geolocation.getCurrentPosition(alertmsg)
}
</script>
</head>
<body>
<input type="button" id="btnClick" onclick="geoLocation()" value="click" />
</body>
</html>
It is working in Ripple emulator
But it is not working in Android emulator and Genymotion
I figured out the problem.
If i use this code it is working fine
navigator.geolocation.getCurrentPosition(alertmsg, onError, { timeout: 30000, enableHighAccuracy: true });
It is working in all emulators(Ripple,Android,Genymotion)
I'm using Visual Studio 13 with a Backbone based smartphone app and this was a pain. Adding the timeout option and enableHighAccuracy always throws the onError handler, without these neither return.
So this is a good answer:
//Android Emulator safe version
function getGpsCordinates(callback) {
if ("geolocation" in navigator) {
navigator.geolocation.getCurrentPosition(
//Success
function (position) {
console.log("GPS: Success");
callback(position);
},
//Error
function (error) {
console.log("GPS: Error");
var position = {
coords: {
longitude: 0,
latitude: 0,
speed: 0
}
};
callback(position);
},
{ timeout: 7000, enableHighAccuracy: true });
} else {
var position = {
coords: {
longitude: 0,
latitude: 0,
speed: 0
}
};
console.log("GPS: Not Supported");
callback(position);
}
console.log("GPS: Continued");
}
getGpsCordinates(function(mycallback) {
alert(mycallback.coords.latitude);
});
Code Pen Version

Phonegap app don't show next page

I trying to build an app with phonegap, jquerymobile and JSON (from wordpress json api). I use the code down here and that works for me it displays te list of recent posts (index.html).
<script type="text/javascript">
var wpAPI = "http://myurl.nl/api/get_recent_posts/";
$(document).on('pagebeforeshow', '#index', function(){
$.getJSON(wpAPI, function(result) {
$.each( result.posts, function( i, item ) {
var html = '<li><img src="'+ item.thumbnail +'"><h2>' + item.title + '</h2><p>' + item.excerpt + '</p></li>';
$( ".container>ul" ).append(html);
});
$("#list").listview('refresh');
});
});
</script>
The problem is when I try to open one of the posts (post.html) the post.html doesn't show anything when I export the app for android.
So I think is something with refreshing, but maybe something else hope some can help me.
<script>
function readSinglePost (url,container){
var postId = window.location.search;
var URL = 'http://myurl.nl/api/get_post/'+ postId + '';
jQuery.ajax({
url: URL,
dataType: 'json',
success: function(data) {
console.log(data);
$('.container').html("<h3>" + data.post.title + "</h3>" + data.post.content + "");
}
});
}
$(document).ready(function(){
readSinglePost (URL,'.container');
});
</script>
Replace
<a href="post.html?post_id='+ item.id +'">
with
<a href="post.html?post_id='+ item.id +'" data-ajax="false" data-role="none">
function readSinglePost (url,container){
var postId = window.location.search;
var URL = 'http://myurl.nl/api/get_post/'+postId;
jQuery.ajax({
type: "GET",
url: URL,
dataType: "json",
success: function(data) {
console.log(data);
$('.container').html("<h3>" + data.post.title + "</h3>" + data.post.content);
}
});
return false;
}

HTML5 geolocation app for Android using phonegap eclipse

I am having trouble to get this HTML5 geolocation app for Android running. The app works fine in Firefox browser from my desktop, but once I compile it using Eclipse - PhoneGap, the geolocation button does not perform the command document.write, I have tried with alert(), as well as console.log(), but there is no positive result.
The code is below, can you please point to me if I am missing setting up any of the phone sensors for geolocation?
Below is the code:
<html>
<head>
<meta charset="UTF-8">
<title> Geolocation Test </title>
<script src="js/jquery-1.9.1.min.js"></script>
<script> // Begginning of Google Maps script
window.google = window.google || {};
google.maps = google.maps || {};
(function() {
function getScript(src) {
document.write('<' + 'script src="' + src + '"' +
' type="text/javascript"><' + '/script>');
}
var modules = google.maps.modules = {};
google.maps.__gjsload__ = function(name, text) {
modules[name] = text;
};
google.maps.Load = function(apiLoad) {
delete google.maps.Load;
apiLoad([0.009999999776482582,[[["http://mt0.googleapis.com/vt?lyrs=m#219000000\u0026src=api\u0026hl=en-US\u0026","http://mt1.googleapis.com/vt?lyrs=m#219000000\u0026src=api\u0026hl=en-US\u0026"],null,null,null,null,"m#219000000"],[["http://khm0.googleapis.com/kh?v=131\u0026hl=en-US\u0026","http://khm1.googleapis.com/kh?v=131\u0026hl=en-US\u0026"],null,null,null,1,"131"],[["http://mt0.googleapis.com/vt?lyrs=h#219000000\u0026src=api\u0026hl=en-US\u0026","http://mt1.googleapis.com/vt?lyrs=h#219000000\u0026src=api\u0026hl=en-US\u0026"],null,null,"imgtp=png32\u0026",null,"h#219000000"],[["http://mt0.googleapis.com/vt?lyrs=t#131,r#219000000\u0026src=api\u0026hl=en-US\u0026","http://mt1.googleapis.com/vt?lyrs=t#131,r#219000000\u0026src=api\u0026hl=en-US\u0026"],null,null,null,null,"t#131,r#219000000"],null,null,[["http://cbk0.googleapis.com/cbk?","http://cbk1.googleapis.com/cbk?"]],[["http://khm0.googleapis.com/kh?v=77\u0026hl=en-US\u0026","http://khm1.googleapis.com/kh?v=77\u0026hl=en-US\u0026"],null,null,null,null,"77"],[["http://mt0.googleapis.com/mapslt?hl=en-US\u0026","http://mt1.googleapis.com/mapslt?hl=en-US\u0026"]],[["http://mt0.googleapis.com/mapslt/ft?hl=en-US\u0026","http://mt1.googleapis.com/mapslt/ft?hl=en-US\u0026"]],[["http://mt0.googleapis.com/vt?hl=en-US\u0026","http://mt1.googleapis.com/vt?hl=en-US\u0026"]],[["http://mt0.googleapis.com/mapslt/loom?hl=en-US\u0026","http://mt1.googleapis.com/mapslt/loom?hl=en-US\u0026"]],[["https://mts0.googleapis.com/mapslt?hl=en-US\u0026","https://mts1.googleapis.com/mapslt?hl=en-US\u0026"]],[["https://mts0.googleapis.com/mapslt/ft?hl=en-US\u0026","https://mts1.googleapis.com/mapslt/ft?hl=en-US\u0026"]]],["en-US","US",null,0,null,null,"http://maps.gstatic.com/mapfiles/","http://csi.gstatic.com","https://maps.googleapis.com","http://maps.googleapis.com"],["http://maps.gstatic.com/intl/en_us/mapfiles/api-3/13/5","3.13.5"],[2518365001],1.0,null,null,null,null,1,"",["places"],null,0,"http://khm.googleapis.com/mz?v=131\u0026",null,"https://earthbuilder.googleapis.com","https://earthbuilder.googleapis.com",null,"http://mt.googleapis.com/vt/icon"], loadScriptTime);
};
var loadScriptTime = (new Date).getTime();
getScript("http://maps.gstatic.com/cat_js/intl/en_us/mapfiles/api-3/13/5/%7Bmain,places%7D.js");
})();
</script> / End of Google Maps script
<script> // Script that runs the app
$(document).ready(function() {
$('#startGeo').click(checkLocation);
function checkLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(getLocation, locationFail);
}
else {
document.write('You dont have geolocation');
}
} // ends checkLocation()
function getLocation(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
var accuracy = position.coords.accuracy;
var timestamp = position.timestamp;
document.write(' latitude: ' + latitude + ' longitude: ' + longitude + ' accuracy: ' + accuracy + ' timestamp: ' + timestamp);
}
function locationFail() {
document.write('We did not get your location. You are safe from big broda');
}
});
</script>
</headd>
<body>
<button id="startGeo"> Click here for geolocation </button>
</body>
</html>
document.write seems to be the cause of your problem, rather than a failure in geolocation, assuming of course you have adequate permissions in your AndroidManifest.xml:
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" />
Try this:
<html>
<head>
<meta charset="UTF-8">
<title> Geolocation Test </title>
<script src="js/jquery-1.9.1.min.js"></script>
<script> // Begginning of Google Maps script
window.google = window.google || {};
google.maps = google.maps || {};
(function() {
function getScript(src) {
document.write('<' + 'script src="' + src + '"' +
' type="text/javascript"><' + '/script>');
}
var modules = google.maps.modules = {};
google.maps.__gjsload__ = function(name, text) {
modules[name] = text;
};
google.maps.Load = function(apiLoad) {
delete google.maps.Load;
apiLoad([0.009999999776482582,[[["http://mt0.googleapis.com/vt?lyrs=m#219000000\u0026src=api\u0026hl=en-US\u0026","http://mt1.googleapis.com/vt?lyrs=m#219000000\u0026src=api\u0026hl=en-US\u0026"],null,null,null,null,"m#219000000"],[["http://khm0.googleapis.com/kh?v=131\u0026hl=en-US\u0026","http://khm1.googleapis.com/kh?v=131\u0026hl=en-US\u0026"],null,null,null,1,"131"],[["http://mt0.googleapis.com/vt?lyrs=h#219000000\u0026src=api\u0026hl=en-US\u0026","http://mt1.googleapis.com/vt?lyrs=h#219000000\u0026src=api\u0026hl=en-US\u0026"],null,null,"imgtp=png32\u0026",null,"h#219000000"],[["http://mt0.googleapis.com/vt?lyrs=t#131,r#219000000\u0026src=api\u0026hl=en-US\u0026","http://mt1.googleapis.com/vt?lyrs=t#131,r#219000000\u0026src=api\u0026hl=en-US\u0026"],null,null,null,null,"t#131,r#219000000"],null,null,[["http://cbk0.googleapis.com/cbk?","http://cbk1.googleapis.com/cbk?"]],[["http://khm0.googleapis.com/kh?v=77\u0026hl=en-US\u0026","http://khm1.googleapis.com/kh?v=77\u0026hl=en-US\u0026"],null,null,null,null,"77"],[["http://mt0.googleapis.com/mapslt?hl=en-US\u0026","http://mt1.googleapis.com/mapslt?hl=en-US\u0026"]],[["http://mt0.googleapis.com/mapslt/ft?hl=en-US\u0026","http://mt1.googleapis.com/mapslt/ft?hl=en-US\u0026"]],[["http://mt0.googleapis.com/vt?hl=en-US\u0026","http://mt1.googleapis.com/vt?hl=en-US\u0026"]],[["http://mt0.googleapis.com/mapslt/loom?hl=en-US\u0026","http://mt1.googleapis.com/mapslt/loom?hl=en-US\u0026"]],[["https://mts0.googleapis.com/mapslt?hl=en-US\u0026","https://mts1.googleapis.com/mapslt?hl=en-US\u0026"]],[["https://mts0.googleapis.com/mapslt/ft?hl=en-US\u0026","https://mts1.googleapis.com/mapslt/ft?hl=en-US\u0026"]]],["en-US","US",null,0,null,null,"http://maps.gstatic.com/mapfiles/","http://csi.gstatic.com","https://maps.googleapis.com","http://maps.googleapis.com"],["http://maps.gstatic.com/intl/en_us/mapfiles/api-3/13/5","3.13.5"],[2518365001],1.0,null,null,null,null,1,"",["places"],null,0,"http://khm.googleapis.com/mz?v=131\u0026",null,"https://earthbuilder.googleapis.com","https://earthbuilder.googleapis.com",null,"http://mt.googleapis.com/vt/icon"], loadScriptTime);
};
var loadScriptTime = (new Date).getTime();
getScript("http://maps.gstatic.com/cat_js/intl/en_us/mapfiles/api-3/13/5/%7Bmain,places%7D.js");
})();
</script> / End of Google Maps script
<script> // Script that runs the app
$(document).ready(function() {
$('#startGeo').click(checkLocation);
function checkLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(getLocation, locationFail);
}
else {
$('#result').append('You dont have geolocation');
}
} // ends checkLocation()
function getLocation(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
var accuracy = position.coords.accuracy;
var timestamp = position.timestamp;
$('#result').append("location: "+' latitude: ' + latitude + ' longitude: ' + longitude + ' accuracy: ' + accuracy + ' timestamp: ' + timestamp);
}
function locationFail() {
$('#result').append('We did not get your location. You are safe from big broda');
}
});
</script>
</head>
<body>
<button id="startGeo"> Click here for geolocation </button>
<div id="result"></div>
</body>
BTW, there's a typo in your source code </headd> should be </head>.
You should also really use $(document).on("deviceready") instead of $(document).ready() with Phonegap as 'ready' event only indicates DOM is ready whereas 'deviceready' indicates Phonegap has fully loaded.

Categories

Resources