I am using phonegap geolocation API in my phonegap android application.It always shows error code code 3,Timeout error.I am also try to change timeout variable value to increased,enableHighAccuracy to be true.But no change in result.But it will works on browser not runs in application.Give me the solution for this problem.
This is my code
<!DOCTYPE html>
<html>
<head>
<meta name="viewport"
content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no" />
<link rel="stylesheet" href="css/contact.css" type='text/css' />
<link rel="stylesheet" href="css/jquery.mobile-1.3.1.min.css"
type='text/css' />
<script type="text/javascript"
src="http://maps.googleapis.com/maps/api/js?key=AIzaSyCJAbwOQjaVjDy9XJ0UEZCvTdZeW_atXak&sensor=false">
</script>
<script type="text/javascript" charset="utf-8" src="cordova-2.9.0.js"></script>
<script src="jquery.mobile/jquery-1.10.2.min" type='text/javascript'></script>
<script>
document.addEventListener("deviceready", onDeviceReady, false);
$(document).on("mobileinit", function() {
$.mobile.phonegapNavigationEnabled = true;
$.support.cors = true;
$.mobile.allowCrossDomainPages = true;
$.mobile.loadingMessageTextVisible = true;
$.mobile.pageLoadErrorMessage;
});
$(document).ready(function() {
$('#Login').show();
$('#Contacts').hide();
});
function success(name) {
alert(name);
}
function error() {
alert("error");
}
function login() {
var name = $("#name").val();
if (navigator.notification) {
navigator.notification.alert("Welcome " + name, alertDismissed, 'Sample App', 'Ok');
} else {
alert("Welcome " + name);
}
var options = {
enableHighAccuracy: true,
timeout: 8000,
maximumAge: 10000
};
navigator.geolocation.getCurrentPosition(onSuccess, onError, options);
$("#Login").hide();
$("#Contacts").show();
}
function alertDismissed() {
console.log("ok");
}
function onSuccess(position) {
var latt1 = position.coords.latitude;
var lont1 = position.coords.longitude; //alert(latt1+" "+lont1);
var myLatlng1 = new google.maps.LatLng(latt1, lont1);
var mapOptions1 = {
center: myLatlng1,
zoom: 10,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions1);
var marker1 = new google.maps.Marker({
position: myLatlng1,
map: map,
title: "You are here! (at least within a " + position.coords.accuracy + " meter radius)"
});
var circle = new google.maps.Circle({
radius: 26000,
strokeColor: "#00FF00",
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: "#C0C0C0",
fillOpacity: 0.35,
map: map
});
marker1.setIcon("./images/blue_dot_circle.png");
marker1.setMap(map);
}
function onError(error) {
if (navigator.notification) {
navigator.notification.alert('code: ' + error.code + '\n' + 'message: ' + error.message + '\n', alertDismissed, 'Sample App', 'Ok');
} else {
alert('code: ' + error.code + '\n' + 'message: ' + error.message + '\n');
}
}
function AlertConfirmed(buttonIndex) {
if (buttonIndex == 1) {
device.exitApp();
console.log(buttonIndex);
} else {
console.log(buttonIndex);
}
}
function goHome() {
navigator.app.loadUrl("http://www.google.co.in", {
openExternal: true
});
}
</script>
<script src="jquery.mobile/jquery.mobile-1.3.1.min.js"
type='text/javascript'></script>
</head>
<body>
<div data-role="page" >
<div id="Login">
<div data-role="header" data-position="fixed" data-theme="b"
data-tap-toggle="false" class="header" data-transition="none"
id="myFixedHeader">
<p>Sample Application</p>
</div>
<div data-role="content">
<div id="title">
<div
style="width: 90%; padding-left: 5%; padding-right: 5%; padding-top: 3%; padding-bottom: 1%;">
<input type="text" name="password" id="name" data-mini="true"
placeholder="Enter Your Name " value="" data-inline="true">
</div>
<center>
<div id="log" onclick="login()">Login</div>
</center>
</div>
</div>
<div data-role="footer" data-theme="b" data-position="fixed"
class="footer" data-transition="none" data-tap-toggle="false">
<p onclick="goHome()">© 2014
Sample App Reserved, LLC.</p>>
</div>
</div>
<div id="Contacts">
<div data-role="header" data-theme="b" data-tap-toggle="false"
data-position="fixed" class="header" data-transition="none">
<h3 id="htitle">Home Page</h3>
</div>
<div data-role="content" id="map_canvas" >
</div>
<div data-role="footer" data-theme="b" data-position="fixed"
class="footer" data-transition="none" data-tap-toggle="false">
<p onclick="goHome()">© 2014
Sample App Reserved, LLC.</p>
</div>
</div>
</body>
</html>
I have added Permissions INTERNET,FINE_LOCATION,COARSE_LOCATION in manifest file
and corrova 2.9.0.js
Please make sure that you have <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> set in your android manifest.
I made one mistake in config.xml.Now,I have added
<access origin="*"/>
<access origin="*://*.googleapis.com/*" subdomains="true" />
<access origin="*://*.gstatic.com/*" subdomains="true" />
<access origin="*://*.google.com/*" subdomains="true" />
<access origin="*://*.googleusercontent.com/*" subdomains="true" />
in my config.xml file.googlemap geolocation showed successfully
Make entry in app/res/xml/config.xml
Entry:
And in app/AndroidManifest.xml
Entry:
Also make sure that the enablehighAccuracy parameter is set to true.
Cheers!!
Related
I am trying to call ajax from android webview and it's not working. I am getting this error in console window
08-29 12:28:16.411: E/CONTENT(14146): [object Object] # 1: http://loconav.com/assets/m/history_selector-1b620f001e31e9dfeff6981b3ee9b290.js
08-29 12:28:16.536: E/CONTENT(14146): Uncaught TypeError: undefined is not a function # 1: http://loconav.com/assets/m/history_selector-1b620f001e31e9dfeff6981b3ee9b290.js
08-29 12:28:16.683: E/CONTENT(14146): Uncaught TypeError: undefined is not a function # 1: http://loconav.com/assets/m/history_selector-1b620f001e31e9dfeff6981b3ee9b290.js
08-29 12:28:16.883: E/CONTENT(14146): Uncaught TypeError: undefined is not a function # 1: http://loconav.com/assets/m/history_selector-1b620f001e31e9dfeff6981b3ee9b290.js
08-29 12:28:17.202: E/CONTENT(14146): Uncaught TypeError: undefined is not a function # 1: http://loconav.com/assets/m/history_selector-1b620f001e31e9dfeff6981b3ee9b290.js
I am using this android code
webview = (WebView) findViewById(R.id.webview);
webview.setWebViewClient(new WebViewClient(){
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url)
{
return super.shouldOverrideUrlLoading(view, url);
}
public void onPageStarted(WebView view, String url, Bitmap favicon) {
dialog.show();
}
#Override
public void onPageFinished(WebView view, String url) {
if(url.equals("http://xyz")){
editor.putString("login", "true");
editor.commit();
trytologin = false;
}else if(url.equals("http://xyz")){
editor.clear();
editor.commit();
Intent intent = new Intent(WebActivity.this,MainActivity.class);
if(trytologin == true){
intent.putExtra("login", "failed");
}
startActivity(intent);
finish();
}
if(!isNetworkAvailable()){
alertDialog();
linearLayout.setVisibility(View.VISIBLE);
webview.setVisibility(View.GONE);
}else{
webview.setVisibility(View.VISIBLE);
imageView.setVisibility(View.VISIBLE);
}
dialog.dismiss();
//pd.dismiss();
//Toast.makeText(WebActivity.this, url, Toast.LENGTH_LONG).show();
}
});
webview.setWebChromeClient(new WebChromeClient(){
#Override
public boolean onConsoleMessage(ConsoleMessage cm)
{
Log.e("CONTENT", String.format("%s # %d: %s",
cm.message(), cm.lineNumber(), cm.sourceId()));
return true;
}
});
webview.getSettings().setJavaScriptEnabled(true);
webview.getSettings().setAppCacheEnabled(true);
webview.getSettings().setDatabaseEnabled(true);
webview.getSettings().setDomStorageEnabled(true);
webview.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
webview.getSettings().setSupportZoom(true);
webview.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
webview.getSettings().setAllowFileAccessFromFileURLs(true);
webview.getSettings().setAllowUniversalAccessFromFileURLs(true);
webview.getSettings().setLoadsImagesAutomatically(true);
webview.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
webview.getSettings().setLoadWithOverviewMode(true);
webview.getSettings().setAllowContentAccess(true);
webview.getSettings().setUseWideViewPort(true);
I am trying to call this ajax file
function GoogleFetchAndFillHistoryLocation(t,e,n,o){$.ajax({url:"http://maps.googleapis.com/maps/api/geocode/json?latlng="+t+","+e,success:function(t){var e=[],c="",r="";t.results[0].address_components.forEach(function(t,n,o){"Unnamed Road"!=t.long_name&&e.push(t.long_name),t.types.includes("sublocality")&&(c=t.long_name),t.types.includes("locality")&&(r=t.long_name)}),console.log(t.results[0].formatted_address);var i=e.join(", "),a=c+", "+r;o.html(i),n.html(a)},error:function(t){o.html("Some error occurred while fetching address")}})}function HistorySelector(t){this.$selector=t}!function(t){"use strict";var e=function(t,n){var o=/[^\w\-\.:]/.test(t)?new Function(e.arg+",tmpl","var _e=tmpl.encode"+e.helper+",_s='"+t.replace(e.regexp,e.func)+"';return _s;"):e.cache[t]=e.cache[t]||e(e.load(t));return n?o(n,e):function(t){return o(t,e)}};e.cache={},e.load=function(t){return document.getElementById(t).innerHTML},e.regexp=/([\s'\\])(?!(?:[^{]|\{(?!%))*%\})|(?:\{%(=|#)([\s\S]+?)%\})|(\{%)|(%\})/g,e.func=function(t,e,n,o,c,r){return e?{"\n":"\\n","\r":"\\r"," ":"\\t"," ":" "}[e]||"\\"+e:n?"="===n?"'+_e("+o+")+'":"'+("+o+"==null?'':"+o+")+'":c?"';":r?"_s+='":void 0},e.encReg=/[<>&"'\x00]/g,e.encMap={"<":"<",">":">","&":"&",'"':""","'":"'"},e.encode=function(t){return(null==t?"":""+t).replace(e.encReg,function(t){return e.encMap[t]||""})},e.arg="o",e.helper=",print=function(s,e){_s+=e?(s==null?'':s):_e(s);},include=function(s,d){_s+=tmpl(s,d);}","function"==typeof define&&define.amd?define(function(){return e}):t.tmpl=e}(this),HistorySelector.prototype.bindEvents=function(){var t=this;this.$selector.on("change",function(){t.fetchData()})},HistorySelector.prototype.fetchData=function(){$.ajax({context:this,url:this.$selector.data("url"),data:{profiles:{interval:this.$selector.val()}},headers:{"X-Auth-Token":$("#auth-token").data("token")},success:function(t){console.log(t),this.populateData(t),$(".location-panel").each(function(t,e){var n=$(e);setTimeout(function(){GoogleFetchAndFillHistoryLocation(n.data("lat"),n.data("long"),n.find(".short-location"),n.find(".formatted-address"))},200*t)})},error:function(t){console.log(t)}})},HistorySelector.prototype.populateData=function(t){var e=$(tmpl("history-locations",t).trim());$(".history-locations").empty().append(e),$("body").scrollTop()<180&&$("html, body").animate({scrollTop:"180vh"},"slow")},HistorySelector.prototype.init=function(){},$(function(){$(".selectors input").each(function(){var t=new HistorySelector($(this));t.init(),t.bindEvents()})});
you can see the ajax file on this link as well - http://www.loconav.com/assets/m/history_selector-1b620f001e31e9dfeff6981b3ee9b290.js
I am using this html code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Babatrucks</title>
<meta content="authenticity_token" name="csrf-param" />
<meta content="lNJn5/GLbnS0cgUYjalFUT+UsgCcDckhWHcqI32OeJ0=" name="csrf-token" />
<link href="/assets/application-33b3164661d3b2d630f9cbc88419feb4.css" media="all" rel="stylesheet" />
<link href="/assets/m_application-9613cb73f45d486ef514a74fa1964a46.css" media="all" rel="stylesheet" />
<script src="/assets/application-95d8b0297f927b393dd0e1aaf163bc4d.js"></script>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-xs-12">
<link href="/assets/m/trucks/show-bcd1a590d01e03df2a78b4c5dbd1a975.css" media="screen" rel="stylesheet" />
<script src="/assets/m/history_selector-1b620f001e31e9dfeff6981b3ee9b290.js"></script>
<div class="row top-bar">
<div class="col-xs-2 text-center">
<a class="back-arrow" href="/m/trucks">
<i class="fa fa-chevron-left" aria-hidden="true"></i>
</a> </div>
<div class="col-xs-8 text-center title">
NL 01L 2273
</div>
<div class="col-xs-2 text-right">
</div>
</div>
<div class="row">
<iframe class='locate-map' src="/m/trucks/296/locate"></iframe>
<div class="col-xs-12">
<div class="row">
<div class="selectors rohan-container">
<ul class="backline">
<hr class="rohan-hr">
<li>
<label for="profiles_interval_1">1 hours</label>
<!-- <input type="radio" id="f-option" name="selector"> -->
<input data-url="http://www.example.com/" id="profiles_interval_1" name="profiles[interval]" type="radio" value="1" />
<div class="check"></div>
</li>
<li>
<label for="profiles_interval_6">6 hours</label>
<!-- <input type="radio" id="s-option" name="selector"> -->
<input data-url="http://www.example.com/" id="profiles_interval_6" name="profiles[interval]" type="radio" value="6" />
<div class="check">
<div class="inside"></div>
</div>
</li>
<li>
<label for="profiles_interval_24">24 hours</label>
<!-- <input type="radio" id="t-option" name="selector"> -->
<input data-url="http://www.example.com/" id="profiles_interval_24" name="profiles[interval]" type="radio" value="24" />
<div class="check">
<div class="inside"></div>
</div>
</li>
</ul>
</div>
<!-- rohan ends -->
</div>
<div class="row history">
<div class="col-xs-12">
<div class="row">
<div class="history-locations col-xs-12"></div>
</div>
</div>
</div>
</div>
</div>
<div class="hidden" id="auth-token" data-token=""></div>
<script src="/assets/timeline/modernizr-04ac4151e53119ba85cdc7679379cd0d.js"></script>
<script type="text/x-tmpl" id="history-locations">
<section id="cd-timeline" class="cd-container">
{% for (var i = 0; i < o['profiles'].length; i++) { %}
<div class="cd-timeline-block location-panel" data-lat="{%= o['profiles'][i]['lat'] %}" data-long="{%= o['profiles'][i]['long'] %}">
<div class="cd-timeline-img cd-picture">
<img alt="Picture" src="/assets/timeline/cd-icon-location-20955b176b47169a313e3c8c11803cc1.svg" />
</div> <!-- cd-timeline-img -->
<div class="cd-timeline-content">
<h2 class="">{%= o['profiles'][i]['actual_received_at'] %}</h2>
<p class="formatted-address"></p>
</div> <!-- cd-timeline-content -->
</div> <!-- cd-timeline-block -->
{% } %}
</section>
</script>
<script src="/assets/timeline/main-f1dcfd5d7be80e6258f34c7dded2ee86.js"></script>
<script type="text/javascript">
function FetchAndFillLocation(lat, long, infoDiv, truckNumber, speed) {
var request = new XMLHttpRequest();
var method = 'GET';
var url = 'http://maps.googleapis.com/maps/api/geocode/json?latlng='
+ lat
+ ','
+ long
+ '&sensor=true';
var async = true;
request.open(method, url, async);
request.onreadystatechange = function(){
if(request.readyState == 4 && request.status == 200){
var data = JSON.parse(request.responseText);
var address = data.results[0];
infoDiv.empty();
infoDiv.append('<div class="info-box-title"><span class="left-align-number"><i class="fa fa-truck"></i> '+ truckNumber +'</span><span class="right-align-speed"><i class="fa fa-tachometer"></i> ' + speed + ' Km/h</span></div><div class="info-box-text">' + address.formatted_address + '</div>');
}
};
request.send();
}
function UpdateMarkerPosition(current_location_div) {
var request = new XMLHttpRequest();
var method = 'GET';
var url = '/api/v1/trucks/location?truck[slug]=abc';
var async = true;
request.open(method, url, async);
request.setRequestHeader('X-Auth-Token', 'abc');
request.onreadystatechange = function(){
if(request.readyState == 4){
if(request.status == 200) {
var data = JSON.parse(request.responseText).current_cordinate;
var truckCords = { lat: data.lat, lng: data.long }
FetchAndFillLocation(truckCords.lat, truckCords.lng, current_location_div, data.key, data.speed);
}
setTimeout(function() {
UpdateMarkerPosition(current_location_div)
}, 10000);
}
};
request.send();
}
$(function() {
UpdateMarkerPosition($('.current-location'));
})
</script>
</div>
</div><!--/row-->
<footer>
</footer>
</div> <!-- /container -->
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-81486803-1', 'auto');
ga('send', 'pageview');
</script>
</body>
</html>
I assume, that a lot of individual files don't end their code with a semicolon. Most jQuery scripts end with (jQuery) and you need to have (jQuery);.
Consider adding jquery locally or via a CDN.
I have this weird error in a Cordova/AngularJS app.
Sometimes (rarely) AngularJS cannot find the controller and chrashes, leaving users with a half-loaded unresponsive view.
The error only seems to happen when the phone has been locked for some time and is next to impossible for me to recreate at a regular basis. It just happens sometimes.
When the user close the app and restart it everything works fine again.
Thus far I have only received complaints about this error for Android devices and not for iOS devices.
EDIT: I have also now seen the error on iOS devices.
I really hope someone is able to shed light on this issue.
My index.html looks like this
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<!DOCTYPE html>
<html ng-app="guideApp">
<head>
<meta charset="utf-8" />
<meta name="format-detection" content="telephone=no" />
<meta name="msapplication-tap-highlight" content="no" />
<meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no">
<meta http-equiv="Content-Security-Policy" content="default-src * 'unsafe-inline'; script-src * 'self' 'unsafe-eval' 'unsafe-inline' https://api.tiles.mapbox.com/mapbox.js/v2.1.6/mapbox.js http://connect.facebook.net/en_GB/sdk.js;">
<link rel="stylesheet" href="css/snap.css" />
<link rel='stylesheet' href='css/mapbox.css' />
<link rel="stylesheet" href="css/leaflet.css" />
<link rel="stylesheet" href="css/guideapp.css" />
<link rel="stylesheet" href="css/xpengineicons.css" />
<!--<link rel="stylesheet" href="css/guideappTest.css" />-->
<title></title>
<link rel="icon" type="image/png" href="img/favicon.png"/>
<meta name="application-name" content="GuideApp"/>
<meta name="msapplication-TileColor" content="#000000" />
<meta name="msapplication-TileImage" content="img/favicons/mstile-144x144.png" />
<meta name="msapplication-square70x70logo" content="img/favicons/mstile-70x70.png" />
<meta name="msapplication-square150x150logo" content="img/favicons/mstile-150x150.png" />
<meta name="msapplication-wide310x150logo" content="img/favicons/mstile-310x150.png" />
<meta name="msapplication-square310x310logo" content="img/favicons/mstile-310x310.png" />
</head>
<body ng-controller="globalCtrl" data-snap-ignore="true">
<div class="snap-drawers">
<div class="snap-drawer snap-drawer-left sideMenu">
{{::langPack.startPage[lang]}}
{{::langPack.selectTour[lang]}}
{{::langPack.map[lang]}}
{{::langPack.news[lang]}}
{{::langPack.photoMenu[lang]}}<i class="icon-angle-down fotoToggleAngle"></i>
<div class="fotoMenu" id="fotoMenu">
{{::langPack.followAnothersTour[lang]}}
{{::langPack.endPhototour[lang]}}
{{::langPack.seePreviousTour[lang]}}
<!--{{::langPack.photoFromGallery[lang]}}-->
{{::langPack.selectFromGallery[lang]}}
<!--[Smaller radius]-->
<!--[Larger radius]-->
<!--[{{langPack.toggleActionRadius[lang]}}]-->
<!--[End waypoint tour] -->
</div>
{{::langPack.about[lang]}}
<a href="#" ng-click="sync.checkUpdates();">
{{::langPack.sync[lang]}}
<span id="updateCheck" class="updateCheck"><div class="circle"></div>{{::langPack.checkForUpdates[lang]}}</span>
<span id="uptodate" class="updateCheck uptodate"><i class="icon-ok"></i>{{::langPack.upToDate[lang]}}</span>
</a>
{{::langPack.showIntroOverlay[lang]}}
</div>
</div>
<div id="content" class="snap-content content" ng-style="customBg">
<nav id="header" ng-controller="cameraCtrl">
<img src="img/menu-regular.svg"><!--<div class="menuNotification" ng-if="photosInUploadQue > 0">{{photosInUploadQue}}</div>-->
<i class="icon-angle-up"></i>
<h1></h1>
<img ng-src="{{customLogo}}" id="logo">
<!-- Kamera når det virker -->
<i class="icon-camera"></i>
<!-- <i class="icon-angle-down"></i> -->
<!-- <i class="icon-angle-up"></i> -->
<!-- <a onclick = "window.open('http://guideapp.tmts.dk/', '_blank', 'location=yes'); return false;" id="viewInBrowser" class="uploadBtn"><i class="icon-angle-down"></i></a> -->
<div id="uploadPopupOverlay" class="popupOverlay" ng-click="closeUploadPopup();"></div>
<section id="uploadPopup">
<p>{{::langPack.uploadAndShare[lang]}}</p>
<form novalidate ng-submit="uploadPhotosSubmittedByPopup($event)">
<label for="emailInput" ng-show="showEmail === true">
{{::langPack.yourEmail[lang]}}
<div class="error" ng-if="emailMsg">{{::emailMsg}}</div>
</label>
<input type="email" value="{{emailAdress}}" required name="emailInput" ng-model="emailAdress" ng-show="showEmail === true" id="emailAdress">
<label for="titleInput">
{{::langPack.yourTitel[lang]}}
<div class="error" ng-if="titleMsg">{{::titleMsg}}</div>
</label>
<input type="text" value="{{tourTitle}}" name="titleInput" ng-model="tourTitle" id="uploadTitle" required>
<p class="emailExists" ng-show="showEmail === false"><span compile="langPack.sendTo[lang]"></span> [{{::langPack.editEmail[lang]}}]</p>
<button class="btn left" ng-click="closeUploadPopup();">{{::langPack.cancel[lang]}}</button>
<button type="submit" class="btn right">{{::langPack.ok[lang]}}</button>
</form>
</section>
</nav>
<div class="slideInLeft" ng-view></div>
</div>
<aside ng-class="{active: showIntro}" id="intro" ng-swipe-left="nextSlide()" class="" ng-swipe-right="prevSlide()">
<div>
<div id="introSwipe">
<section id="intro{{$index+1}}" class="introSlide" ng-class="{'active': $index === 0}" ng-repeat="slide in introSlides" style="background-image: url('{{slide}}')"></section>
</div>
<section id="noShow">
<div class="slideNavigation">
<button ng-click="prevSlide()" ng-class="{disabled: firstSlide}">{{::langPack.prevSlide[lang]}}</button>
<div class="slideProgress">{{slideProgress}}/{{introSlides.length}}</div>
<button ng-click="nextSlide()" ng-class="{disabled: lastSlide}">{{::langPack.nextSlide[lang]}}</button>
</div>
</section>
</div>
<a id="closeIntro" href="#" ng-click="toggleIntro(); $event.preventDefault()">{{::langPack.toggleIntroText[lang]}}</a>
</aside>
<section id="confirmOverlay" class="popupOverlay" ng-click="confirmValue = false;">
<section class="checkPopup confirmPopup" id="confirmPopup">
<p id="confirmMessage"></p>
<button class="btn right" ng-click="confirmValue = true;">{{::langPack.ok[lang]}}</button>
<button class="btn left" ng-click="confirmValue = false;">{{::langPack.cancel[lang]}}</button>
</section>
</section>
<section id="spinnerOverlay" class="popupOverlay">
<section class="checkPopup spinnerPopup" id="spinnerPopup">
<div class="circle"></div>
<div class="spinnerText" id="spinnerText"></div>
</section>
</section>
<section id="statusOverlay" class="popupOverlay" ng-click="status.hide()">
<section class="checkPopup statusPopup" id="statusPopup">
<p id="statusText"></p>
<button class="btn" ng-click="status.hide()">Ok</button>
</section>
</section>
<!-- JavaScript libraries -->
<script src="cordova.js"></script>
<script src="js/libs/angular.min.js"></script>
<script src="js/libs/angular-locale_da-dk.js"></script>
<script src="js/libs/angular-route.min.js"></script>
<script src="js/libs/angular-animate.min.js"></script>
<script src="js/libs/angular-touch.min.js"></script>
<script src="js/libs/snap.min.js"></script>
<script src="js/libs/md5.js"></script>
<script src="js/libs/angular-listview.min.js"></script>
<!-- Mapbox -->
<!--<script src='https://api.tiles.mapbox.com/mapbox.js/v2.1.6/mapbox.js'></script>-->
<!-- <script src='https://api.mapbox.com/mapbox.js/plugins/leaflet-omnivore/v0.2.0/leaflet-omnivore.min.js'></script> Draw GPX 20151014 -->
<!-- leaflet -->
<script src="js/libs/leaflet.js"></script>
<script src='js/libs/leaflet-omnivore.min.js'></script> <!-- Draw GPX 20151014 -->
<script src='js/libs/leaflet-tilelayer-cordova.js'></script> <!-- Offline maps -->
<!-- Custom script files -->
<script src="js/app.js"></script>
<script src="js/index.js"></script>
<!-- included controllers -->
<script src="controllers/globalCtrl.js"></script>
<script src="controllers/homeCtrl.js"></script>
<script src="controllers/aboutCtrl.js"></script>
<script src="controllers/tourSelectCtrl.js"></script>
<script src="controllers/mapCtrl.js"></script>
<script src="controllers/cameraCtrl.js"></script>
<script src="controllers/viewtoursCtrl.js"></script>
<script src="controllers/commonToursCtrl.js"></script>
<script src="controllers/highscoreCtrl.js"></script>
<script src="controllers/downloadCtrl.js"></script>
<script src="controllers/waypointCtrl.js"></script>
<script src="controllers/waypointGalleryCtrl.js"></script>
<script src="controllers/endCtrl.js"></script>
<script src="controllers/newsCtrl.js"></script>
</body>
</html>
AngularJS is loaded with app.js:
// Init angular.js
var guideApp = angular.module('guideApp', ['ngRoute', 'ngAnimate', 'ngTouch']);
guideApp.config(['$routeProvider', '$compileProvider', function ($routeProvider, $compileProvider) {
$routeProvider.when('/', {
controller: 'homeCtrl',
templateUrl: 'views/home.html'
}).when('/home', {
controller: 'homeCtrl',
templateUrl: 'views/home.html'
}).when('/tourSelect', {
controller: 'tourSelectCtrl',
templateUrl: 'views/tourSelect.html'
}).when('/map', {
controller: 'mapCtrl',
templateUrl: 'views/map.html'
}).when('/about', {
controller: 'aboutCtrl',
templateUrl: 'views/about.html'
}).when('/viewtours', {
controller: 'viewtoursCtrl',
templateUrl: 'views/viewtours.html'
}).when('/commonTours', {
controller: 'commonToursCtrl',
templateUrl: 'views/commonTours.html'
}).when('/highscore', {
controller: 'highscoreCtrl',
templateUrl: 'views/highscore.html'
}).when('/download', {
controller: 'downloadCtrl',
templateUrl: 'views/download.html'
}).when('/waypoint', {
controller: 'waypointCtrl',
templateUrl: 'views/waypoint.html'
}).when('/waypointGallery', {
controller: 'waypointGalleryCtrl',
templateUrl: 'views/waypointGallery.html'
}).when('/end', {
controller: 'endCtrl',
templateUrl: 'views/end.html'
}).when('/news', {
controller: 'newsCtrl',
templateUrl: 'views/news.html'
}).otherwise({
redirectTo: '/'
});
$compileProvider.imgSrcSanitizationWhitelist(/^\s*(https?|cdvfile|file):/);
}]);
guideApp.directive('compile', ['$compile', function ($compile) {
return function(scope, element, attrs) {
scope.$watch(
function(scope) {
// watch the 'compile' expression for changes
return scope.$eval(attrs.compile);
},
function(value) {
// when the 'compile' expression changes
// assign it into the current DOM
element.html(value);
// compile the new DOM and link it to the current
// scope.
// NOTE: we only compile .childNodes so that
// we don't get into infinite loop compiling ourselves
$compile(element.contents())(scope);
}
);
};
}])
// custom on touchstart directive
/*guideApp.directive('guideappTouchstart', [function () {
return function(scope, element, attr) {
element.on('touchstart', function (event) {
scope.$apply(function () {
scope.$eval(attr.guideappTouchstart);
});
});
};
}]);*/
The index.js file looks like this:
var http,
app = {
initialize: function () {
this.bindEvents();
},
bindEvents: function () {
if (!window.cordova) {
this.onDeviceReady();
} else {
document.addEventListener('deviceready', this.onDeviceReady, false);
}
},
onDeviceReady: function () {
app.receivedEvent('deviceready');
console.log('Device ready');
if (window.cordova) {
// find and set the filesystem root
window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem;
window.requestFileSystem(1, 0, function (fileSystem) {
console.log("got filesystem: "+fileSystem.name); // displays "persistent"
//console.log(fileSystem.root.fullPath); // displays "/"
window.rootFS = fileSystem.root;
});
}
},
receivedEvent: function (id) {
//angularInit();
this.platform();
},
server: function (wwwroot) {
if (httpd) {
httpd.getURL(function (url) {
if(url.length > 0) {
document.getElementById('url').innerHTML = "server is up: <a href='" + url + "' target='_blank'>" + url + "</a>";
} else {
httpd.startServer({
'www_root' : wwwroot,
'port' : 8080
}, function (url) {
//updateStatus();
}, function (error) {
console.log('server error ', error);
});
}
}, function () {});
} else {
console.log('CorHttpd plugin not available/ready');
}
},
platform: function () {
var deviceType;
if (navigator.userAgent.match(/Android/i)) { // Android
if (navigator.userAgent.match(/Mobile/i)) { // Android smartphone
console.log('Android smartphone');
deviceType = 'mobile';
} else { // Android tablets
//console.log('Android tablet');
deviceType = 'tablet';
}
} else if (navigator.userAgent.match(/iPad/i)) { // IOS ipad
//console.log('IOS tablet');
deviceType = 'tablet';
} else if (navigator.userAgent.match(/iPhone/i)) { //IOS smartphone
//console.log('IOS smartphone');
deviceType = 'mobile';
} else { // Dekstop as default
//console.log('desktop');
deviceType = 'tablet';
}
}
};
app.initialize();
Here is the code
App.js
(...)
.state('app.dishdetails', {
url: '/menu/:id',
views: {
'mainContent': {
templateUrl: 'templates/dishdetail.html',
controller: 'DishDetailController'
}
}
});
Controller.js
.controller('DishDetailController', ['$scope', '$stateParams', 'menuFactory', 'favoriteFactory', 'baseURL','$ionicPopover', '$ionicListDelegate', '$ionicModal', function($scope, $stateParams, menuFactory, favoriteFactory, baseURL, $ionicPopover, $ionicListDelegate, $ionicModal) {
$scope.addFavoriteMenu = function(index){
console.log("index is " + index);
};
// .fromTemplateUrl() method
$ionicPopover.fromTemplateUrl('templates/dish-detail-popover.html', {
scope: $scope
}).then(function(popover) {
$scope.popover = popover;
});
$scope.openPopover = function($event) {
$scope.popover.show($event);
};
$scope.closePopover = function() {
$scope.popover.hide();
};
//Cleanup the popover when we're done with it!
$scope.$on('$destroy', function() {
$scope.popover.remove();
});
// Execute action on hide popover
$scope.$on('popover.hidden', function() {
// Execute action
});
// Execute action on remove popover
$scope.$on('popover.removed', function() {
// Execute action
});
}])
Main HTML
<ion-view view-title="Dish Details">
<ion-nav-buttons side="secondary">
<div class="buttons">
<button class="button button-icon icon ion-more"
ng-click="openPopover($event)"></button>
</div>
</ion-nav-buttons>
<ion-content>
(...)
</ion-content>
</ion-view>
Popover HTML
<ion-popover-view>
<ion-content>
<ul class="list">
<li class="item" ng-click="addFavoriteMenu({{dish.id}})">
Add to Favorites
</li>
</ul>
</ion-content>
db.json
"dishes": [
{"id": 0};
{"id": 1};
{"id": 2};
]
I can't get the parameter in the "addFavoriteMenu({{dish.id}})" in the controller.js, it always come out as undefined
but, when I try to inspect using Google Chrome, the ID could display properly in [ion-popover-view]
Is there any mistake that I create on here? or anything?
Trying to reproduce your issue I noticed that your JSON is wrong: there are semicolons (;) at the end of each line instead of colons (,).
Howevere here is a working snippet:
angular.module('ionicApp', ['ionic'])
.controller('AppCtrl', function($scope, $ionicPopover) {
$scope.dishes = [
{"id": 0},
{"id": 1},
{"id": 2}
];
$scope.addFavoriteMenu = function(index) {
console.log(index);
alert("index is "+index);
}
$ionicPopover.fromTemplateUrl('templates/popover.html', {
scope: $scope,
}).then(function(popover) {
$scope.popover = popover;
});
});
<html ng-app="ionicApp">
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
<title>Ionic Popover</title>
<link href="//code.ionicframework.com/nightly/css/ionic.css" rel="stylesheet">
<script src="//code.ionicframework.com/nightly/js/ionic.bundle.js"></script>
</head>
<body class="platform-ios" ng-controller="AppCtrl">
<div class="bar bar-header bar-positive">
<h1 class="title">Popover</h1>
<div class="buttons">
<button class="button button-icon ion-more" ng-click="popover.show($event)">
</button>
</div>
</div>
<ion-content class="padding has-header">
Click the more info icon in the top right. In an actual app the platform style will automatically be set.
</ion-content>
<script id="templates/popover.html" type="text/ng-template">
<ion-popover-view>
<ion-content>
<ul class="list">
<li ng-repeat="dish in dishes" class="item" ng-click="addFavoriteMenu({{dish.id}})">
Add to Favorites {{dish.id}}
</li>
</ul>
</ion-content>
</ion-popover-view>
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title></title>
<script type='text/javascript' src='http://code.jquery.com/jquery-1.8.3.js'></script>
<!--<link rel="stylesheet" type="text/css" href="/css/normalize.css">-->
<script type="text/javascript" src="http://code.jquery.com/mobile/1.4.2/jquery.mobile- 1.4.2.js"></script>
<link rel="stylesheet" type="text/css" href="http://code.jquery.com/mobile/1.4.2/jquery.mobile-1.4.2.css">
<script type='text/javascript' src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"></script>
<script type='text/javascript' src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/additional-methods.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script type='text/javascript'>
$(document).on('pageinit', function () {
//$.support.cors =true,
//$.mobile.allowCrossDomainPages = true;
$('#frmLogin').validate({
rules: {
username: {
required: true
},
password: {
required: true
}
},
messages: {
username: {
required: "Please enter your username."
},
password: {
required: "Please enter your password."
}
},
errorPlacement: function (error, element) {
error.appendTo(element.parent().prev());
},
submitHandler: function (form) {
//alert('there doesn't exist a valid url as yet');
$("#frmLogin").submit(function (event) {
//event.preventDefault();
var credentials = { username: $("#username").val(), password: $("#password").val() };
$.ajax({
type: "POST",
url: "api/auth", // this url is just a placeholder
cache: false,
data: JSON.stringify(credentials),
contentType: "application/json; charset=utf-8",
success: function(data,status,jqxhr)
{
//validate the response here, set variables... whatever needed
//and if credentials are valid, forward to the next page
if (data.status == "success")
{
var obj = $.parseJSON(data);
localStorage.setItem("acccessToken", obj.accessToken);
alert(obj.accessToken);
//authUsername = $("#username").val();
//var encrytPswd = mm.crypt.encrypt('sha1', $("#password").val());
//localStorage.setItem(authUsername, encrytPswd);
//localStorage.setItem('authUsername', authUsername);
//localStorage.setItem('authPassword', encrytPswd);
//mm.page.show('configuration', {});
//$.mobile.changePage($("#main_page"));
//window.location.href = "http://www.jqueryvalidation.org";
}
else if(data.status== "error")
{
alert("Authentication Invalid.Please try again!");
return false;
}
//or show an error message
},
error: function (jqxhr, status, errorMsg)
{
// server couldn't be reached or other error
alert("jqXHR Status : " + jqxhr.status + " Status: " + status + " Error: " + errorMsg);
}
}, "json");
return false;
});
//$(':mobile-pagecontainer').pagecontainer('change', '#success', {
// reload: false
//});
}
});
});
</script>
<style type="text/css">
label.error {
color: red;
font-size: 16px;
font-weight: normal;
line-height: 1.4;
margin-top: 0.5em;
width: 100%;
float: none;
}
#media screen and (orientation: portrait){
label.error { margin-left: 0; display: block; }
}
#media screen and (orientation: landscape){
label.error { display: inline-block; margin-left: 22%; }
}
em { color: red; font-weight: bold; padding-right: .25em; }
</style>
</head>
<body id="loginBody">
<div data-role="page" id="login">
<div data-role="header">
</div>
<div data-role="content">
<a id="main_page" href="www.google.com"></a>
<form id="frmLogin" method="post" action="api/auth" data-ajax="false">
<div data-role="fieldcontain">
<label for="username">
<em>* </em> Username:
</label>
<input type="text" id="username"
name="username" />
</div>
<div data-role="fieldcontain">
<label for="password">
<em>* </em>Password:
</label>
<input type="password" id="password"
name="password" />
</div>
<div class="ui-body ui-body-b">
<button class="btnLogin" type="submit" id="loginBtn"
data-theme="a">
Login
</button>
</div>
</form>
</div>
<div data-role="page" id="success" data-theme="b">
<div data-role="header">
<h1>Thank You!!!</h1>
</div>
</div>
</div>
</body>
</html>
Whenever I click button to fire submit event on the form and given the fact that the url that I'm posting my request to doesn't exist so it should execute the following function:
error: function (jqxhr, status, errorMsg)
{
// server couldn't be reached or other error
alert("jqXHR Status : " + jqxhr.status + " Status: " + status + " Error: " + errorMsg);
}
which it does but I have to click the button two times, why not after a single click the above function is executed?
Javascript does not work outside index.html page:
Project Test 1:
Index.html (with GEOLOCATION PAGE CODE) works fine
Project Test 2:
Index.html (with MENU PAGE CODE)
Geolocation.html (with GEOLOCATION PAGE CODE) javascript does not work
The page Geolocation.html opens up, but javascript does not run.
What am i missing?
GEOLOCATION PAGE CODE:
<!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" charset="utf-8" src="js/cordova-2.5.0.js"></script>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false">
</script>
<script type="text/javascript">
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
var element = document.getElementById('geoTemp');
element.innerHTML = 'Ready...';
navigator.geolocation.getCurrentPosition(onSuccess, onError, { maximumAge: 3000, timeout: 10000, enableHighAccuracy: false });
}
function onSuccess(position) {
var element = document.getElementById('geoTemp');
element.innerHTML = 'Success...';
initialize(position.coords.latitude, position.coords.longitude);
}
function onError(error) {
var element = document.getElementById('geoTemp');
element.innerHTML = 'Error...';
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}
function initialize(latitude, longitude) {
var mapOptions = {
center: new google.maps.LatLng(latitude, longitude),
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"),
mapOptions);
}
function onBodyLoad(){
alert("test!");
}
</script>
</head>
<body>
<h2>Location</h2>
<p id="geolocation">Finding geolocation...</p>
<p id="geoTemp"></p>
<div id="map_canvas" style="width:100%; height:100%"></div>
</body>
</html>
MENU PAGE CODE:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Test</title>
<link rel="stylesheet" href="css/themes/default/jquery.mobile-1.3.0.css">
<link rel="shortcut icon" href="favicon.ico">
<script src="js/jquery.js"></script>
<script src="js/jquery.mobile-1.3.0.js"></script>
<script type="text/javascript" src="js/cordova-2.5.0.js"></script>
</head>
<body>
<div data-role="page" id="pageMain">
<div data-role="header">
<h1>
TestPage
</h1>
</div>
<div data-role="content">
<ul data-role="listview">
<li><a href="geolocation.html" data-transition="slide">
<h2>Geolocation Test</h2>
<p>Testing</p>
</a></li>
</ul>
</div>
</div>
</body>
</html>
I have also tried to add an onload function to the body tag and call a test function but it didn't work either.
In the link to geolocation.html, add this attribute data-ajax="false". This will prevent jQuery from loading the page via Ajax.