I have an application using phonegap and jQM. i'm trying to get my geolocation to work when clicking the button but i get an error in the console saying geolocation is not defined.
The error is pointing to the onclick="getLocation()". Can anyone help me please?
Heres an example of my code:
<div data-role="page" id="geo" data-add-back-btn="true" onload="onBodyLoad()">
<header data-role="header" data-position="fixed">
<h1>Geolocation</h1>
</header>
<div data-role="content">
<button data-role="button" onclick="getLocation()">Click to get your current position</button>
<div id="mapholder"></div>
</div>
</div>
$("#geo").on('pageinit', function () {
console.log("Geo page loaded!");
function onBodyLoad(){
document.getElementById('geolocation').empty();
document.addEventListener("deviceready", onDeviceReady, false);
}
function onDeviceReady(){
phoneGapReady.innerHTML = ("")
}
var x=document.getElementById("demo");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition,showError);
}else {
x.innerHTML="Your Browser does not support Geolocation.";}
}
function showPosition(position) {
lat=position.coords.latitude;
lon=position.coords.longitude;
latlon=new google.maps.LatLng(lat, lon);
mapholder=document.getElementById('mapholder')
mapholder.style.height='250px';
mapholder.style.width='100%';
var myOptions= {
center:latlon,zoom:14,
mapTypeId:google.maps.MapTypeId.ROADMAP,
mapTypeControl:false,
navigationControlOptions:
{style:google.maps.NavigationControlStyle.SMALL}
};
var map = new
google.maps.Map(document.getElementById("mapholder"),myOptions);
var marker=new
google.maps.Marker({position:latlon,map:map,title:"Your Location."});
}
function showError(error)
{
switch(error.code)
{
case error.PERMISSION_DENIED:
x.innerHTML="User did not allow Geolocation."
break;
case error.POSITION_UNAVAILABLE:
x.innerHTML="Location Data is not Available."
break;
case error.TIMEOUT:
x.innerHTML="Request Timed Out."
break;
case error.UNKNOWN_ERROR:
x.innerHTML="Unknown Error."
break;
}
}
});
Assuming you're using Phonegap 3.x, make sure you've added the geolocation plugin to your project:
phonegap local plugin add https://git-wip-us.apache.org/repos/asf/cordova-plugin-geolocation.git
Make sure the config.xml includes it:
<feature name="Geolocation">
<param name="android-package" value="org.apache.cordova.GeoBroker" />
</feature>
Make sure you allow access in the android manifest:
<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 changing
if (navigator.geolocation) {
to
if (typeof(navigator.geolocation) != "undefined") {
Related
I am developing an Ionic-App and I want to set the Screen Orientation to Portrait.
and I know I could set it with this:
<preference name="orientation" value="portrait" />
but this isn't working,
I found a cordova plugin called screen-orientation-plugin but this is not working too. Do you have any another solution for this? Or Can anyone explain me how these 2 methods are working correctly?
.config(function($ionicConfigProvider, $stateProvider, $urlRouterProvider, $compileProvider) {
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
$scope.changeOriantationPortrait = function() {
screen.lockOrientation('portrait');
}
changeOriantationPortrait();
}
I have used this plugin for my project and it is worked perfectly
cordova plugin add net.yoik.cordova.plugins.screenorientation
Controller
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
$scope.changeOriantationLandspace = function() {
screen.lockOrientation('landscape');
}
$scope.changeOriantationPortrait = function() {
screen.lockOrientation('portrait');
}
}
HTML
<button class="button button-full button-positive " ng-click="changeOriantationLandspace()">Change To Landspace Mode</button>
<br/>
<button class="button button-full button-positive " ng-click="changeOriantationPortrait ()">Change To Portrait Mode</button>
Reference
I am developing an iOS app by using Meteor. When I applied "browser side API", I can get back physical address on browser perfectly. However, it doesn't work on iOS simulator or iOS devices.
So, I applied another APIKey for iOS application. It still doesn't work. Please advice.
Sometimes it worked, but most of the time, physical address result didn't come back.
//router.js
Router.route('/',{
path:"/",
onBeforeAction: function() {
Session.set('geoLocation',Geolocation.latLng());
console.log(Geolocation.latLng());
this.next();
}
});
//index.html
<head>
<title>Todo List</title>
</head>
<body>
<div class="container">
<header>
<h1>Todo List</h1>
<div class="item">
hi
</div>
</header>
<input class="address" type="search" autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" name="address" placeholder="Address" value="#">
</div>
</body>
//server.js
if (Meteor.isClient) {
if (Session.get('geoLocation')){
var temp = Session.get('geoLocation');
var lat = temp.lat;
var lng = temp.lng;
Meteor.call('getPhysicalAddress', lat, lng, function(err, result){
console.log(result);
console.log(result[0].city);
Session.set('physicalAddress', result[0].city);
physicalAddress = Session.get('physicalAddress');
});
}
Template.body.events({
'click .address': function(e){
var a = Session.get('physicalAddress');
$('.container').append('<h1>'+a+'</h1>');
$('.address').val(Session.get('physicalAddress'));
console.log('im here');
}
});
}
if (Meteor.isServer) {
Meteor.methods({
'getPhysicalAddress':function(lat,lng) {
var geo = new GeoCoder({
geocoderProvider: "google",
apiKey: 'xxx',
httpAdapter: "https"
});
return geo.reverse(lat,lng);
},
'getGoogleAddress':function(address) {
check(address,String);
var geo = new GeoCoder({
geocoderProvider: "google",
apiKey: 'xxx',
httpAdapter: "https"
});
return geo.geocode(address)[0];
}
});
}
I am developing an Phonegap (3.3.0) + Jquery Mobile (1.4) app.
I get an infinite loading page (white page with ui-loader icon). This is erratic and sometimes the app starts well.
I see a very strange bug: none of the first "console.logs" I use in my js file are displayed in the Phonegap Build Weinre debug console.
Only after a certain line (which contain by the way the first asynchronous function) the console.log are displayed in the Weinre console.
So I guess I have a binding order problem related to Jquery Mobile and Phonegap, but I can't find what's wrong in my initialization.
Can I be also due to the order in which I call js files in my index.html ?
I followed this post to register Phonegap and JQM : Correct way of using JQuery-Mobile/Phonegap together?
recommended here : jQuery Mobile : What is the order of page events triggering?
by #Gajotres.
Can you help ?
Thanks
HTML:
<!DOCTYPE html>
<html>
<head>
...
</head>
<body>
<!-- SPLASH PAGE -->
<div id="splash-page" data-role="page">
<div class='toastenjs' style='display:none'></div>
<center id="splashLogoCenter">
<img src="images/splash.png" width="200" />
</center>
</div>
<!-- WELCOME PAGE -->
<div id="welcome-page" data-role="page">
...
</div>
<script src="js/jquery-1.9.1.js"></script>
<script src="js/jquery.jsonp-2.4.0.min.js"></script>
<script src="js/functions.js"></script>
<script src="js/functionCUgly.js"></script>
<script src="js/boardDims.js"></script>
<script src="phonegap.js"></script>
<script src="js/jquery.mobile.config.js"></script>
<script src="js/jquery.mobile-1.4.3.min.js"></script>
<!--POUCHDB -->
<script src="js/pouchdb-2.2.3.min.js"></script>
<!-- Flexslider-->
<!-- <script src="js/flexslider-v2.js"></script>--> <!-- v2.2 doesn't work, maybe because we're not using last versions of jquery and jqm -->
<script src="js/flexsliderV2.3.js"></script>
<!-- iScroll-->
<script type="application/javascript" src="js/iscroll.js"></script>
<script type="application/javascript" src="js/jquery.mobile.iscrollview.js"></script>
<!-- Add2home : create a shortcut icon of the wep app on the phone homescreen -->
<script type="application/javascript" src="js/add2home.js"></script>
<script src="js/GoogleLogin.js"></script> <!--Phonegap module by eric valenzia https://github.com/valenzia10/PhonegapGoogleLogin-->
<script src="js/jquery.ddslick.min.js"></script>
<script src="js/jquery-geturlvar.js"></script>
<script src="js/html2canvas.js"></script>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
if (typeof(google) != 'undefined'){
google.load('visualization', '1.0', {'packages':['corechart']});
}
</script>
JS file:
var deviceReadyDeferred = $.Deferred();
var jqmReadyDeferred = $.Deferred();
$(document).one("mobileinit", function () {
console.log('mobileinit just fired'); //this one is not displayed in the weinre console
jqmReadyDeferred.resolve();
});
if ( isPhoneGap() ) {
document.addEventListener("deviceReady", onDeviceReady, false);
function onDeviceReady() {
deviceReadyDeferred.resolve();
}
$.when(deviceReadyDeferred, jqmReadyDeferred).then( EVERYTHING() ); // !!!!! normalement il faut virer ces parenthèses pour respecter le $.when....mais ça fait tout bugger !!!!!!!!!
} else {
console.log("NOT Running on PhoneGap!");
$.when(jqmReadyDeferred).then( EVERYTHING );
}
function EVERYTHING() {
console.log("on est entré dans EVERYTHING()"); //not displayed in the weinre console
insideEVERYTHING = 1;
console.log("jqmReadyDeferred is "+jqmReadyDeferred.state()); //not displayed in the weinre console
console.log("deviceReadyDeferred is "+deviceReadyDeferred.state()); //not displayed in the weinre console
//FOR EVERY PAGE
$(document).on('pagecontainershow', function (e, ui) {
//...
});
$(document).on('pagecontainershow', function (e, ui) {
//...
});
// --------------- SPLASH PAGE ---------------------
//$(document).on('pagecreate','#splash-page', function(){
$(document).on('pagecontainershow', function (e, ui) {
var activePageId = $(':mobile-pagecontainer').pagecontainer('getActivePage').attr('id');
if (activePageId === 'splash-page') {
console.log("we are in splash-page");
if (typeof debugOptionUseLocalDB != 'undefined' && debugOptionUseLocalDB) {
fallbackToLocalDBfile();
console.log('on yess');
}else{
if(connectionStatus == 'online'){
console.log("launching getJsonpFile...");
//DEBUG TIMER
var time=[];
var dummy;
dummy = new Date().getTime();
time.push(dummy);
getJsonpFile(dbUrl())
.done(function(data) {
console.log("...getJsonpFile done.");
if(localStorage) {
if ( isPhoneGap() || !isIOS() ) { //BUG iOS safari doesn't work with this (Cf. Philippe's ipad), si on est sur phonegap ok, si on n'est pas sur phonegap et pas sur iOS ok
localStorage.setItem("proDB", JSON.stringify(data)); //write to localStorage
}
}
//...JQM bindings are continued below
The best registration is the following :
var isPhoneGap;
var deviceReadyDeferred = $.Deferred();
var jqmReadyDeferred = $.Deferred();
isPhoneGap = checkIfPhoneGap();
if ( isPhoneGap ) {
$.when(deviceReadyDeferred, jqmReadyDeferred).done( Everything );
} else {
console.log("NOT Running on PhoneGap!");
$.when(jqmReadyDeferred).done( Everything );
}
$(document).on("mobileinit", function () {
//alert('mobileinit just fired');
//popShortToast("mobileinit just fired");
jqmReadyDeferred.resolve();
});
document.addEventListener("deviceReady", onDeviceReady, false);
function onDeviceReady() {
//popShortToast("deviceReady just fired");
deviceReadyDeferred.resolve();
}
function checkIfPhoneGap() {
var app = document.URL.indexOf( 'http://' ) === -1 && document.URL.indexOf( 'https://' ) === -1; // && document.URL.indexOf( 'file://' );
if ( app ) {
return true;
} else {
return false;
}
}
function Everything() {
//enter your JQM bindings here, and use Phonegap's features
}
New to Phonegap and having a hard time understanding the FileWriter function. I am trying to get this example to work on iOS6 but I'm stuck with the error message
<script type="text/javascript" charset="utf-8" src="cordova-2.3.0.js"></script>
<script type="text/javascript" charset="utf-8">
var fileWriter;
function onNotesLoad() {
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, onFSComplete, fail);
}
function onFSComplete(fileSystem) {
// Load the notes.txt file, create it if it doesn't exist
fileSystem.root.getFile("notes.txt", {create: true}, onFileEntryComplete, fail);
}
function onFileEntryComplete(fileEntry) {
// set up the fileWriter
fileEntry.createWriter(onFileWriterComplete, fail);
}
function onFileWriterComplete(fileWriter) {
// store the fileWriter in a
// global variable so we have it
// when the user presses save
fileWriter = fileWriter;
}
function saveNotes() {
// make sure the fileWriter is set
if (fileWriter != null) {
// create an oncomplete write function
// that will redirect the user
fileWriter.onwrite = function(evt) {
alert("Saved successfully");
$.mobile.changePage("index.html");
};
var form = document.getElementsByTagName('form')[0].elements;
var notes = form.notes.value;
// save the notes
fileWriter.write(notes);
} else {
alert("There was an error trying to save the file");
}
return false;
}
function fail(error) {
alert(error.code);
}
</script>
HTML:
<body>
<div data-role="page" id="notes-page">
<div data-role="header" data-position="inline">
Cancel
<h1>Your Thoughts?</h1>
<a onClick="return saveNotes()" href="#"
data-icon="check" data-theme="b">Save</a>
</div>
<form action="index.html" method="post">
<textarea name="notes" rows="30" cols="10"></textarea>
</form>
</div>
</body>
The onwrite handler is called as a progress event. I believe you will want to hook to the onwriteend handler.
I have a JQuery Mobile website that people use with their Android device.
(This website mainly deals with clients information.)
I've been looking to integrate a "GET DIRECTION" feature.
I was wondering if it's possible to open Google Navigation app (because it can be used as a GPS, voice navigation) with the current location and one client's address through JQM ?
If not, does anyone has any suggestion?
The official W3C site informs about the W3C Geolocation working group and the milestones that have been set.
You can find here a fresh (May 2012) W3C draft proposal for the Geolocation API.
Below you can find a sample working example that I created. The code finds the current position and provides a direction service. There is a textbox where you can write the target destination and a button which "Get Directions". When you click the button a list at the end of the page is filled with the directions.
You can modify it in order to fit your needs. Furthermore you can find more information about the directions service in the Google Map JavaScript API Directions Service.
<!doctype html>
<html lang="en">
<head>
<title>jQuery mobile with Google maps</title>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.0.1/jquery.mobile-1.0.1.min.css" />
<script type="text/javascript" src="http://code.jquery.com/jquery-1.6.4.min.js"></script>
<script type="text/javascript" src="http://code.jquery.com/mobile/1.0.1/jquery.mobile-1.0.1.min.js"></script>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?v=3&sensor=false&language=en"> </script>
<script type="text/javascript">
var map;
var currentPosition;
var directionsDisplay = new google.maps.DirectionsRenderer();
var directionsService = new google.maps.DirectionsService();
function initialize(lat, lon)
{
currentPosition = new google.maps.LatLng(lat, lon);
map = new google.maps.Map(document.getElementById('map_canvas'), {
zoom: 15,
center: currentPosition,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
directionsDisplay.setMap(map);
//directionsDisplay.setPanel($("#instructions-content"));
var currentPositionMarker = new google.maps.Marker({
position: currentPosition,
map: map,
title: "Current position"
});
var infowindow = new google.maps.InfoWindow();
google.maps.event.addListener(currentPositionMarker, 'click', function() {
infowindow.setContent("Current position: latitude: " + lat +" longitude: " + lon);
infowindow.open(map, currentPositionMarker);
});
}
function locError(error)
{
alert("The position or the map could not be loaded.");
}
function locSuccess(position)
{
initialize(position.coords.latitude, position.coords.longitude);
}
$(document).ready(function()
{
navigator.geolocation.getCurrentPosition(locSuccess, locError);
$("#directions-button").click(function(){
var targetDestination = $("#target-dest").val();
if (currentPosition && currentPosition != '' && targetDestination && targetDestination != '')
{
var request = {
origin:currentPosition,
destination:targetDestination,
travelMode: google.maps.DirectionsTravelMode["DRIVING"]
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setPanel(document.getElementById("instructions-content"));
directionsDisplay.setDirections(response);
// For debuging reasons uncomment
/*
var myRoute = response.routes[0].legs[0];
for (var i = 0; i < myRoute.steps.length; i++) {
alert(myRoute.steps[i].instructions);
}*/
}
});
}
else
{
alert("The target destination is empty or the current position could not be located.");
}
});
});
</script>
</head>
<body>
<div id="basic-map" data-role="page">
<div data-role="header">
<h1><a data-ajax="false" href="/">jQuery mobile with Google maps v3</a> examples</h1>
</div>
<div data-role="content">
<div class="ui-bar-c ui-corner-all ui-shadow" style="padding:1em;">
<div id="map_canvas" style="height:350px;"></div>
</div>
<div data-role="fieldcontain">
<label for="name">Target Destination:</label>
<input type="text" name="target-dest" id="target-dest" value="" />
</div>
Get Directions
<div data-role="collapsible" id="instructions-container">
<h3>Instructions</h3>
<p><div id="instructions-content"></div></p>
</div>
</div>
</div>
</body>
</html>
Put the HTML code in a file map.html and open it directly with Mozilla Firefox (in case you don't want to put it on a server and test it). Otherwise put the file on a server and open it with any browser you want.
Initially you will be asked whether you want to share your current location. After you press the Share button you will see a map with a marker showing your current position. If you click the marker you will see you latitude and longitude.
I hope this helps.