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 * 'unsafe-inline'; script-src * 'unsafe-inline' 'unsafe-eval'">
<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
Related
I am working on Ionic Mobile Application. After Creating Facebook Login button(Working fine) i want to get User data (Public profile and Email for my database.
My Index.html
<script src="lib/ionic/js/ionic.bundle.js"></script>
<script src="lib/angular-sanitize/angular-sanitize.min.js"></script>
<script src="js/ng-cordova.min.js"></script><script src="lib/ng-cordova-oauth/dist/ng-cordova-oauth.min.js"></script>
<!-- cordova script (this will be a 404 during development) -->
<script src="cordova.js"></script>
<!-- your app's js -->
<script src="js/app.js"></script>
<script src="js/services.js"></script>
<script src="js/controllers.js"></script>
Controller.js
.controller('login',['$scope','myService','$location','$state','$timeout',function($scope,myService,$location,$state,$timeout)
{
$scope.fbLogin = function ($cordovaOauth,$http) {
facebookLogin(window.cordovaOauth, window.http);
console.log(fbLogin);
}
}])
app.js
var app = angular.module('starter', ['ionic', 'starter.controllers','starter.services','ngSanitize', 'ngCordova', 'ngCordovaOauth']);
Please tell me where i am doing wrong.
And Sometimes i Get $cordovaOauth error.
Modular is not Injected.
function login(){
facebookLogin(window.cordovaOauth, window.http);
}
function facebookLogin($cordovaOauth, $http)
{
$cordovaOauth.facebook("1633195863589792", ["email", "public_profile"], {redirect_uri: "http://localhost/callback"}).then(function(result){
displayData($http, result.access_token);
}, function(error){
alert("Error: " + error);
});
}
function displayData($http, access_token)
{
$http.get("https://graph.facebook.com/v2.2/me", {params: {access_token: access_token, fields: "name,gender,location,picture", format: "json" }}).then(function(result) {
var name = result.data.name;
var gender = result.data.gender;
var picture = result.data.picture;
}, function(error) {
alert("Error: " + error);
});
}
I've an hybrid app for android, i'm using cordova and onsen + angular js.
This is my index.html file:
<html lang="en" ng-app="AppModel">
<head>
<meta charset="utf-8">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="mobile-web-app-capable" content="yes">
<title>AppModel</title>
<!-- <link rel="stylesheet" href="css/plugins.css"/> -->
<link rel="stylesheet/less" href="css/plugins.less"/>
<link rel="stylesheet" href="lib/onsen/css/onsenui.css">
<link rel="stylesheet" href="lib/onsen/css/onsen-css-components.css">
<link rel="stylesheet/less" href="css/app.less"/>
<link rel="stylesheet/less" href="css/base-layout.less"/>
<script src="css/less.min.js" type="text/javascript"></script>
<script src="http://maps.google.com/maps/api/js"></script>
<script src="js/lodash_3.2.0.min.js"></script>
<script src="lib/onsen/js/angular/angular.js"></script>
<script src="js/angular-google-maps_2.0.12.min.js"></script>
<script src="lib/onsen/js/angular/angular-touch.js"></script>
<script src="lib/onsen/js/onsenui.min.js"></script>
<script src="js/jquery.min.js"></script>
<script src="js/plugins.js"></script>
<script type="text/javascript" src="cordova.js"></script>
<script src="js/appStart.js"></script>
<script src="js/data/data.js"></script>
<script src="js/angularApp/controllers.js"></script>
<script src="js/angularApp/directives.js"></script>
<script src="js/angularApp/filters.js"></script>
</head>
<body >
<ons-sliding-menu
menu-page="modules/core/menu.html" main-page="modules/account_profile/login.html" side="left"
var="menu" type="reveal" max-slide-distance="260px" swipable="true" swipe-target-width="50">
</ons-sliding-menu>
</body>
</html>
This is the appStart.js
var app = {
// Application Constructor
initialize: function() {
this.bindEvents();
},
// Bind Event Listeners
//
// Bind any events that are required on startup. Common events are:
// 'load', 'deviceready', 'offline', and 'online'.
bindEvents: function() {
document.addEventListener('deviceready', this.onDeviceReady, false);
},
// deviceready Event Handler
//
// The scope of 'this' is the event. In order to call the 'receivedEvent'
// function, we must explicity call 'app.receivedEvent(...);'
exitFunction : function(){
if (navigator.notification.confirm("Vuoi chiudere l'app?",
function(index) {
if (index == 1) { // OK button
navigator.app.exitApp(); // Close the app
}
},
"AppModel",
["Ok","Annulla"]
));
},
onDeviceReady: function() {
app.receivedEvent('deviceready');
ons.setDefaultDeviceBackButtonListener(function() {
if (navigator.notification.confirm("Vuoi chiudere l'app?",
function(index) {
if (index == 1) { // OK button
navigator.app.exitApp(); // Close the app
}
},
"AppModel",
["Ok","Annulla"]
));
});
/*
// Open any external link with InAppBrowser Plugin
$(document).on('click', 'a[href^=http], a[href^=https]', function(e){
e.preventDefault();
var $this = $(this);
var target = $this.data('inAppBrowser') || '_blank';
window.open($this.attr('href'), target);
});
*/
$(document).on('click', 'a', function(e){
e.preventDefault();
var $this = $(this);
//var target = $this.data('inAppBrowser') || '_blank';
window.open($this.attr('href'), "_system");
});
},
// Update DOM on a Received Event
receivedEvent: function(id) {
//var parentElement = document.getElementById(id);
//var listeningElement = parentElement.querySelector('.listening');
//var receivedElement = parentElement.querySelector('.received');
//listeningElement.setAttribute('style', 'display:none;');
//receivedElement.setAttribute('style', 'display:block;');
console.log('Received Event: ' + id);
}
};
(function() {
var app = angular.module('AppModel', ['onsen', 'angular-carousel', 'uiGmapgoogle-maps'])
.config( [
'$compileProvider',
function( $compileProvider )
{
$compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|file|ftp|mailto|tel|geo):/);
}
]);
document.addEventListener('deviceready', function() {
angular.bootstrap(document, ['AppModel']);
}, false);
})
And data.js, controller.js, filter.js, directive.js are all like this:
var app = angular.module('AppModel'); //this is the first line in each file
app.factory('MenuData', function(){ [...]
But when i launch the app in google chrome, the console says:
Uncaught Error: [$injector:nomod] Module 'AppModel' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.
http://errors.angularjs.org/1.2.10/$injector/nomod?p0=AppModel
This message appears for the files data.js, controller.js, filter.js, directives.js due to the first line of each file.
I don't know what to do. Can someone help me?
Doesn't look like you're executing the line where the app module is created.
You must run the line
angular.module('appName', [dependencies]);
before you created your controllers and services, like the error message says.
Are you calling the anonymous function that creates the module? Just add an empty parenthesis and it should run:
(function() {
var app = angular.module(...
})();
As the error message says, you must specify the dependencies as the second argument. If none is needed, then pass an empty array.
change
var app = angular.module('AppModel'); //this is the first line in each file
to
var app = angular.module('AppModel', []); //this is the first line in each file
and run it again.
Additional information: https://docs.angularjs.org/api/ng/function/angular.module
i am trying to retrive some data with sqlite from ionic framework. But i am newbie, so i need your help.
I want to retrieve data from db with sqlite as a list, all data.
If // console.log line command is open, i only get one data, not the others.
If app.js is like this, i get this error.
TypeError: Cannot read property 'push' of undefined
at app.js:65
at processQueue (ionic.bundle.js:20962)
at ionic.bundle.js:20978
at Scope.$get.Scope.$eval (ionic.bundle.js:22178)
at Scope.$get.Scope.$digest (ionic.bundle.js:21994)
at Scope.scopePrototype.$digest (hint.js:1468)
at ionic.bundle.js:22216
at completeOutstandingRequest (ionic.bundle.js:12714)
at ionic.bundle.js:13094
app.js
var db = null;
var example = angular.module('starter', ['ionic', 'ngCordova'])
.run(function($ionicPlatform, $cordovaSQLite) {
$ionicPlatform.ready(function() {
if(window.cordova && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
}
if(window.StatusBar) {
StatusBar.styleDefault();
}
if (window.cordova) {
db = $cordovaSQLite.openDB({ name: "my.db" }); //device
}else{
db = window.openDatabase("my.db", '1', 'my', 1024 * 1024 * 100); // browser
}
$cordovaSQLite.execute(db, "CREATE TABLE IF NOT EXISTS people (id integer primary key, firstname text, lastname text)");
});
});
example.controller("ExampleController", function($scope, $cordovaSQLite) {
$scope.insert = function(firstname, lastname) {
var query = "INSERT INTO people (firstname, lastname) VALUES (?,?)";
$cordovaSQLite.execute(db, query, [firstname, lastname]).then(function(result) {
console.log("INSERT ID -> " + result.insertId);
}, function (error) {
console.error(error);
});
}
$scope.select = function(lastname) {
var query = "SELECT firstname, lastname FROM people WHERE lastname = ?";
$cordovaSQLite.execute(db, query, [lastname]).then(function(result) {
if(result.rows.length > 0) {
console.log("SELECTED -> " + result.rows.item(0).firstname + " " + result.rows.item(0).lastname);
} else {
console.log("No results found");
}
}, function (error) {
console.error(error);
});
}
$scope.selectAll = function() {
var query = "SELECT firstname, lastname FROM people";
var outputs = [];
$cordovaSQLite.execute(db, query, []).then(function(result) {
if(result.rows.length > 0) {
for(var i = 0; i < result.rows.length; i++) {
//console.log("SELECTED -> " + result.rows.item(i).firstname + " " + result.rows.item(i).lastname);
/* $scope.outputs = [
{"firstname": result.rows.item(i).firstname}
]; */
$scope.outputs.push({
"firstname" : result.rows.item(i).firstname,
});
}
} else {
console.log("No results found");
}
}, function (error) {
console.error(error);
});
}
});
example.controller("PeopleCtrl", function($scope) {
$scope.people = [
{firstName: 'John', lastName: 'Doe', address: {city: 'Chandler', state: 'AZ', zip: 85248}},
{firstName: 'Jane', lastName: 'Doe', address: {city: 'Chandler', state: 'AZ', zip: 85248}},
{firstName: 'Johnny', lastName: 'Doe', address: {city: 'Phoenix', state: 'AZ', zip: 85003}}
];
});
and index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
<title></title>
<link href="lib/ionic/css/ionic.css" rel="stylesheet">
<link href="css/style.css" rel="stylesheet">
<script src="lib/ionic/js/ionic.bundle.js"></script>
<script src="js/ng-cordova.min.js"></script>
<script src="cordova.js"></script>
<script src="js/app.js"></script>
</head>
<body ng-app="starter">
<ion-pane>
<ion-header-bar class="bar-stable">
<h1 class="title">Ionic Blank Starter</h1>
</ion-header-bar>
<ion-content>
<div ng-controller="ExampleController">
<button class="button" ng-click="insert('Arzu','Acar')">Insert</button>
<button class="button" ng-click="selectAll()">Select</button>
<ul>
<li ng-repeat="output in outputs">
<span class="bold">{{output.firstname}}</span>
</li>
</ul>
</div>
<div ng-controller="PeopleCtrl">
<div id="peopleContainer">
People:<br /><br />
<ul>
<li ng-repeat="person in people">
<span class="bold">{{person.firstName}} {{person.lastName}}</span>
<br />
{{person.address.city}}, {{person.address.state}} {{person.address.zip}}
</li>
</ul>
</div>
</div>
</ion-content>
</ion-pane>
</body>
</html>
Thank you.
In ExampleController:selectAll, you have the following declaration:
var outputs = [];
Then push to an array that doesn't exist on $scope:
$scope.outputs.push({
"firstname" : result.rows.item(i).firstname,
});
I think you meant to initialize the $scope.outputs array each time selectAll is called:
$scope.outputs = [];
You must declare in the controller's main scope:
$scope.outputs = [];
Your "selectAll" function should be like this:
$scope.selectAll = function() {
var query = "SELECT firstname, lastname FROM people";
$scope.outputs.length = 0;
$cordovaSQLite.execute(db, query).then(function(result) {
if(result.rows.length > 0) {
for(var i = 0; i < result.rows.length; i++) {
$scope.outputs.push({
firstName : result.rows.item(i).firstname
});
}
} else {
console.log("No results found");
}
}, function (error) {
console.error(error);
});
}
Hope this works! :)
I have a problem with this code. I can see the Google Maps correctly, with my actual location in the center of the android screen, but I cannot see the marker whatever I do.
This is the html:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
<link href="lib/ionic/css/ionic.css" rel="stylesheet">
<link href="css/style.css" rel="stylesheet">
<style>
html, body {
height:100%;
}
</style>
<script src="lib/ionic/js/ionic.bundle.js"></script>
<script src="cordova.js"></script>
<script src="js/app.js"></script>
<script src="js/services.js"></script>
</head>
<body ng-app="starter" ng-controller="GeoCtrl" class="platform-android">
<div id="map_canvas" style="width:100%; height:100%"></div>
</body>
</html>
This is the services.js
angular.module('starter.services', [])
.factory('Location', ['$q', function($q) {
return {
getLocation: function(options) {
var q = $q.defer();
navigator.geolocation.getCurrentPosition(function(position) {
q.resolve(position);
}, function(err) {
q.reject(err);
});
return q.promise;
}
}
}]);
And this is the app.js:
angular.module('starter', ['ionic', 'starter.services'])
.run(function($ionicPlatform) {
...
})
.controller('GeoCtrl', function($scope, Location) {
$scope.lat;
$scope.long;
$scope.map;
$scope.marker;
Location.getLocation().then(function (position) {
$scope.lat = position.coords.latitude;
$scope.long = position.coords.longitude;
var mapOptions = {
center: new google.maps.LatLng($scope.lat, $scope.long),
zoom: 14,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
$scope.map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
}, function(err) {
// error
});
$scope.marker = new google.maps.Marker({
position: new google.maps.LatLng($scope.lat, $scope.long),
map: $scope.map,
title: 'Holas!'
}, function(err) {
console.err(err);
});
});
Thank you!
I hope this can help to somebody:
I called the marker outside the then flow, whereas it has to be called inside:
Location.getLocation().then(function (position) {
$scope.lat = position.coords.latitude;
$scope.long = position.coords.longitude;
var mapOptions = {
center: new google.maps.LatLng($scope.lat, $scope.long),
zoom: 14,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
$scope.map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
$scope.marker = new google.maps.Marker({
position: new google.maps.LatLng($scope.lat, $scope.long),
map: $scope.map,
title: 'Holas!'
}, function(err) {
console.err(err);
});
}, function(err) {
// error
});
Now it works.
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/