iOS emulator GPS does not work? - angularjs

I tested my app in the iOS emulator and noticed that the gps does not work.
In the emulator I set the location to "Apple"
and installed the corodova plugin by: "cordova plugin add org.apache.cordova.geolocation".
Here is my Code:
angular.module('home', ['services'])
.controller('homeCtrl',
function ($scope, $location, $state, serverAPI, $ionicPopup) {
$scope.buttonType = "icon ion-search";
$scope.buttonDisable = false;
$scope.text = 'Search';
var UID = JSON.parse(window.localStorage.getItem('Credentials')).UID;
serverAPI.getUserData(UID, function (data) {
$scope.userName = data.userName;
$scope.points = data.points;
$scope.fotoId = data.fotoId;
console.log(data);
});
$scope.click = function () {
$scope.buttonDisable = true;
$scope.text = 'Searching';
$scope.buttonType = 'icon ion-loading-a';
// //Grap geoLocation
var location = navigator.geolocation.getCurrentPosition(saveGeoData, onError);
//
function onError(error) {
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
};
var saveGeoData = function (geoData) {
console.log("nach geo");
var myPosition = {
'longitude': geoData.coords.longitude,
'latitude': geoData.coords.latitude
};
console.log("ss");
console.log(myPosition.latitude);
window.localStorage.setItem('myPosition', JSON.stringify(myPosition));
//If geoloaction is saved successfully => Send geodata to server to receive teammate
sendToServer(myPosition);
}
//Send current location to Server to receive teammate
var sendToServer = function (myPosition) {
serverAPI.searchPartnerToPlayWith(myPosition.longitude, myPosition.latitude, UID, function (data) {
//No other players around you. Server returns -1
if (data == -1) {
$ionicPopup.alert({
title: 'Too bad :(',
template: 'Unfortunateley there are no other players around you. Try it some other time!'
});
} else {
window.localStorage.setItem('teammate', data.username);
window.localStorage.setItem('isEnummeration', data.taskType);
window.localStorage.setItem('task', data.task);
var teammatePosition = {
'longitude': data.longitude,
'latitude': data.latitude
};
window.localStorage.setItem('teammatePosition', teammatePosition);
//TODO: data.fotoId => request foto from server
$state.go('tab.play-screen');
}
})
}
};
})
When the function click is called, it just stops in Line:
var location = navigator.geolocation.getCurrentPosition(saveGeoData, onError);
Do you have a guess whats my problem? In the browser it works just fine.
Thanks!

Make sure you include this file into your project.
https://github.com/apache/cordova-plugin-geolocation/blob/master/www/geolocation.js
It can be high probability cause from there, this function not exist in your project, getCurrentPosition.

Related

Redirection error in angularjs

After adding data in location table, clicking on the save button should redirect it to list of data in location table.But ,it stays in the same page after adding.The same path is given to modify location,it works fine. whereas the same path does not redirect when add location.
function locationController($scope, $state, $rootScope, locationServices,$location, locations, location, primaryLocation, $stateParams,locationTypes, countries) {
var vm = this;
$scope.locations = locations.data;
$scope.location = location.data;
if (primaryLocation.data && primaryLocation.data[0])
$scope.primaryLocation = primaryLocation.data[0];
if (!$scope.location) {
var location = {};
if ($stateParams.accountId) {
$scope.location = {accountId: $stateParams.accountId };
} else {
$scope.location = location;
}
}
$rootScope.title = "Locations";
$scope.locationslist = "views/locations.html";
$scope.addOrModifyLocation = function (location) {
if (location._id) {
locationServices.modifyLocation(location).then(function (response) {
$location.path('/account/locations/contacts/' + location.accountId + '/' +location.accountId);
// $state.reload();
})
} else {
location.status = 'ACTIVE';
locationServices.addLocation(location).then(function (response) {
$location.path('/account/locations/contacts/' + location.accountId + '/' +location.accountId);
})
}
};
If you want angular to know about your $location update, you have to do it like this :
$rootScope.$apply(function() {
$location.path("/my-path"); // path must start with leading /
});
If you're using ui-router, a cleaner approach would be to use
$state.go('stateName', {'accountId' : location.accountId, });
edit :
If you have errors that happen during a state change, you can see it by adding the following code in your app after declaring your module :
angular.module("appName").run([
"$rootScope",
function ($rootScope) {
$rootScope.$on("$stateChangeError", function(error) {
console.log(error);
});
}
]);

AngularJS/Ionic promises - sometimes page loads forever

I am using promises in my controller, and most of the times it works well. But sometimes it just loads forever and the WordPress.getAllCategories() function does not even get called.
This is my controller:
var mod = angular.module('app.controllers.home', []);
mod.controller('HomeCtrl', function ($scope, $q, $sce, $ionicPlatform, WordPress, Loading) {
console.log('HomeCtrl init');
$scope.$on('$ionicView.enter', function () {
Loading.show();
WordPress.getAllCategories()
.then(function (cats) {
console.info(angular.toJson(cats));
console.info('cats ^');
$q.all(cats.data.map(function (cat) {
var d = $q.defer();
console.error(cat.name);
WordPress.getLatestPostOfCategory(cat.id)
.then(function (post) {
console.debug(post.data.title.rendered);
WordPress.getMediaById(post.data.featured_media)
.then(function (media) {
console.log(media.data.source_url);
cat.firstPost = {};
cat.firstPost.id = post.data.id;
cat.firstPost.title = post.data.title.rendered;
cat.firstPost.content = post.data.content.rendered;
if (cat.firstPost.title.length > 50) {
cat.firstPost.title = cat.firstPost.title + '...';
}
if (cat.firstPost.content.length > 70) {
cat.firstPost.content = cat.firstPost.content.substr(0, 60) + '...';
}
cat.firstPost.thumbnail = media.data.source_url;
d.resolve(cat);
}, function (err) {
console.error(angular.toJson(err));
});
});
return d.promise;
})).then(function (cats) {
console.log('Loaded all articles and for main page.');
$scope.homeCategories = cats;
Loading.hide();
});
});
});
});
Is there anything wrong in my controller?
P.S. I also debug all the WordPress service functions and they work just fine, and provide the needed data.
EDIT:
Sometimes when it loads forever, I see the console.error(cat.name); debug message only logs 3 messages. But still proceeds to the next function...
This is how I solved it, by Bergi's advice.
Source for help: Promise anti pattern by Gorgi Kosev (bluebird)
var categories = [];
function sort() {
return WordPress.getAllCategories()
.then(function (cats) {
console.log('thens');
return $q.all(cats.data.map(function (cat) {
console.info('cat: ' + cat.name);
var category = {};
category.name = cat.name;
return WordPress.getLatestPostOfCategory(cat.id)
.then(function (post) {
var post = post.data;
category.post = {};
category.post.id = post.id;
category.post.title = post.title.rendered;
category.post.content = post.content.rendered;
console.log('ID: ' + category.post.id + ', title: ' + category.post.title);
return WordPress.getMediaById(post.featured_media);
}).then(function (media) {
category.post.thumbnail = media.data.source_url;
categories.push(category);
console.log('Pushed category "' + category.name + '"');
});
}));
}, function (err) {
console.error('ERR1');
console.error(angular.toJson(err));
});
}
sort()
.then(function () {
console.info('LOADED ALL CATEGORIES');
$scope.categories = categories;
}, function (err) {
console.error('err:' + angular.toJson(err));
});

Common service for sessionstorage in angularjs

Hi in my application i am setting the values in login controller and getting in all the other js files, other than this how to use a common service for setting storage and getting that storage in required js files
My login controller
app.controller('LoginController',function(loginService, $rootScope,$scope, $http,$location) {
$scope.login = function () {
$scope.log=loginService.getLogin( $scope.emailId , $scope.password).
then(function (response) {
console.log($scope.log);
console.log(response)
if (response.data.LoginVerificationResult.length === 0) {
alert('details are not Available for this emailId');
$scope.error=true;
} else {
$rootScope.name=response.data.LoginVerificationResult[0].UserName;
$scope.abc=response.data.LoginVerificationResult[0].UserType
console.log($scope.abc+"from.......");
sessionStorage.setItem("EmaiId",$scope.emailId);
sessionStorage.setItem("User Id",response.data.LoginVerificationResult[0].UserID);
sessionStorage.setItem("UserName",response.data.LoginVerificationResult[0].UserName);
sessionStorage.setItem("UserType",response.data.LoginVerificationResult[0].UserType);
$scope.UserType = sessionStorage.getItem("UserType");
console.log($scope.UserType +"from login controller")
$location.path('/dashboard')
}
});
};
});
My changepassword file
app.controller("ChangePwdController", function($scope, $http, $location,
BaseUrl, changePwdService) {
//$scope.roleId = sessionStorage.getItem("Role ID");
/* $scope.UserType = sessionStorage.getItem("UserType");*/
$scope.username = sessionStorage.getItem("UserName");
$scope.userType = sessionStorage.getItem("UserType");
$scope.EmpName=sessionStorage.getItem("EmpName");
$scope.patientName=sessionStorage.getItem("PatientName")
$scope.changePwd = function() {
$scope.emailAddress = sessionStorage.getItem("EmaiId");
console.log($scope.emailAddress)
var data = {
'emailAddress' : $scope.emailAddress,
'currentPassword' : $scope.opassword,
'newPassword' : $scope.npassword
};
console.log("Hi")
$scope.pwd=changePwdService.postChangePwd(data).success(
function(resp) {
$scope.PostDataResponse = data;
console.log($scope.pwd)
console.log($scope.PostDataResponse);
if (resp.ResetPasswordResult === true) {
alert("Successfully changed");
console.log("success")
$location.path('/dashboard');
} else {
console.log("fail")
alert("Enter valid current password")
}
})
}
})
Is there any alternative way to set and get in one file
There are ways in which you can achieve the same. Please refer this here.

Second jsonp http get request - using $q gives 404 error despite GET showing 200

I've found a couple of similar posts to this, but the answers (which boil down to putting callback=JSONP_CALLBACK into the get request) aren't working for me. Using that in the request generates an immediate 404 error, while using callback=angular.callbacks._0 at least lets the first request return a successful response. The problem is that using the very same request function with the very same params a second time to refresh the data or get the next 20 objects, returns a 404 error even though the actual get returns a 200 and the data can be seen in chrome tools.
I'm, new to using $q deferred promises, so I'm hoping that the issue has something to do with that not allowing enough time for a response before executing the reject. I'm attaching the code, which involves the Yelp API as did the other couple of posts I found on this issue. The most closely related is: (Subsequent JSONP requests give status 404 despite GET status 200), but there's another which uses the same callback string I'm using (Yelp API and AngularJS).
This particular project is for an ionic mobile app that gets coffee shops based on users geolocation.
Here's the code for the service (secret stuff removed):
var app = angular.module('caffeine.services', []);
app.service("YelpService", function ($q, $http, $cordovaGeolocation, $ionicPopup) {
function randomString(length, chars) {
var result = '';
for (var i = length; i > 0; --i) result += chars[Math.round(Math.random() * (chars.length - 1))];
return result;
};
var method = 'GET';
var url = 'http://api.yelp.com/v2/search';
var consumerSecret = ''; //Consumer Secret
var tokenSecret = ''; //Token Secret
var self = {
'page': 1,
'isLoading': false,
'hasMore': true,
'results': [],
'ranStr': randomString(32, '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'),
'timeStamp':new Date().getTime(),
'lat': 51.544440,
'lon': -0.022974,
'term': 'coffee',
'oauthConKey': '', //Consumer Key
'oauthToken': '', //Token
'oauthSigMeth': 'HMAC-SHA1',
'refresh': function () {
self.page = 1;
self.isLoading = false;
self.hasMore = true;
self.results = [];
return self.load();
},
'next': function () {
self.page += 1;
return self.load();
},
'load': function () {
self.isLoading = true;
var deferred = $q.defer();
ionic.Platform.ready(function() {
$cordovaGeolocation
.getCurrentPosition({timeout:10000, enableHighAccuracy:false})
.then(function(position){
self.lat = position.coords.latitude;
self.lon = position.coords.longitude;
console.log('latlong = '+self.lat+','+self.lon);
var params = {
callback: 'angular.callbacks._0',
page: self.page,
ll: self.lat+','+self.lon,
term: self.term,
oauth_consumer_key: self.oauthConKey, //Consumer Key
oauth_token: self.oauthToken, //Token
oauth_signature_method: self.oauthSigMeth,
oauth_timestamp: self.timeStamp,
//new Date().getTime(),
oauth_nonce: self.ranStr
};
var signature = oauthSignature.generate(method, url, params, consumerSecret, tokenSecret, { encodeSignature: false});
params['oauth_signature'] = signature;
console.log('url ='+url);
console.log('params.ll = '+params.ll);
$http.jsonp(url, {params: params}).success(function (callback) {
self.isLoading = false;
console.log(callback.businesses);
if (callback.businesses.length == 0) {
self.hasMore = false;
} else {
angular.forEach(callback.businesses, function (business) {
self.results.push(business);
});
}
self.isLoading = false;
deferred.resolve(callback.businesses);
})
.error( function (callback, status, headers, config) {
self.isLoading = false;
console.error('data not received');
console.error('data: '+callback);
console.error('status: '+status);
console.error('headers: '+headers);
console.error('congig: '+config);
deferred.reject(callback);
});
}, function(err) {
console.error('Error getting position');
console.error(err);
$ionicPopup.alert({
'title': 'Please turn on geolocation',
'template': 'It looks like you have geolocation turned off. Please turn on geolocation in your app settings to use this app.'
});
})
});
return deferred.promise;
}
};
self.load();
return self;
});

Cordova PushPlugin onNotification ecb not fired

myApp.services.factory('GCMHelper', ($q)->
pushNotification = {}
_init = ()->
defer = $q.defer()
ionic.Platform.ready(()->
pushNotification = window.plugins.pushNotification;
window.onNotification = (res)->
console.log('onNotification', res)
defer.resolve()
)
return defer.promise
return {
register: ()->
_init().then(()->
pushNotification.register(
(res)->
console.log('gcm register success', res)
(err)->
console.log('gcm register err', err)
{
"senderID": "*********",
"ecb": "onNotification"
}
);
)
}
)
in controller:
GCMHelper.register()
(Please excuse my poor English)
I'm tring Cordova PushPlugin with Cordova 4.2 and Ionic beta 14, it got success callback every time with "OK" string, but ecb onNotification never fired, and no error at console. I almost have no ideal with that..., any one help?
Use the following for Push Notification in Android and iOS. It will work properly for you. After install the app, user will need to open the app for call ecb methods. In iOS, PushNotifcation's register success method will returns the mobile register id in result but in android, it will return only OK. In Android, onNotificationGCM method will be called for two type event 1) RegisterId and 2) Notification Message. I have also added the showNotificationAPN/GCM method for show notification popups with $ionicPopup.alert().
.run(function ($ionicPlatform, PushProcessingService) {
$ionicPlatform.ready(function () {
try {
PushProcessingService.initialize();
} catch (e) {
//hide event
}
})
})
.factory('PushProcessingService', ["$window", "$ionicPopup", function ($window, $ionicPopup) {
function onDeviceReady() {
var pushNotification = window.plugins.pushNotification;
if (ionic.Platform.isAndroid()) {
pushNotification.register(gcmSuccessHandler, gcmErrorHandler, {'senderID': 'XXXXXXXXXXXXXX', 'ecb': 'onNotificationGCM'});
} else if (ionic.Platform.isIOS()) {
var config = {
"badge": "true",
"sound": "true",
"alert": "true",
"ecb": "pushCallbacks.onNotificationAPN"
};
pushNotification.register(gcmSuccessHandler, gcmErrorHandler, config);
}
var addCallback = function addCallback(key, callback){
if(window.pushCallbacks == undefined){
window.pushCallbacks = {};
}
window.pushCallbacks[key] = callback({registered:true});
}
}
function gcmSuccessHandler(result) {
console.log("Register push notification successfully : " + result);
if (ionic.Platform.isIOS()) {
var mobileType = "ios";
var mobileRegisterId = result;
// Save the ios mobile register Id in your server database
// call the following method on callback of save
addCallback("onNotificationAPN", onNotificationAPN);
}
}
function gcmErrorHandler(error) {
console.log("Error while register push notification : " + error);
}
return {
initialize: function () {
document.addEventListener('deviceready', onDeviceReady, false);
},
registerID: function (id) {
var mobileType = "android";
// Save the android mobile register Id in your server database
console.log("RegisterId saved successfully.");
},
showNotificationGCM: function (event) {
$ionicPopup.alert({
title: "Pajhwok Notification",
subTitle: event.payload.type,
template: event.payload.message
});
},
showNotificationAPN: function (event) {
$ionicPopup.alert({
title: event.messageFrom + "..",
subTitle: event.alert,
template: event.body
});
}
}
}])
onNotificationAPN = function(event) {
if (!event.registered) {
var elem = angular.element(document.querySelector('[ng-app]'));
var injector = elem.injector();
var myService = injector.get('PushProcessingService');
myService.showNotificationAPN(event);
} else {
console.log("Registered successfully notification..");
}
}
function onNotificationGCM(e) {
switch( e.event )
{
case 'registered':
if ( e.regid.length > 0 )
{
// Your GCM push server needs to know the regID before it can push to this device
// here is where you might want to send it the regID for later use.
var elem = angular.element(document.querySelector('[ng-app]'));
var injector = elem.injector();
var myService = injector.get('PushProcessingService');
myService.registerID(e.regid);
}
break;
case 'message':
// if this flag is set, this notification happened while we were in the foreground.
// you might want to play a sound to get the user's attention, throw up a dialog, etc.
var elem = angular.element(document.querySelector('[ng-app]'));
var injector = elem.injector();
var myService = injector.get('PushProcessingService');
myService.showNotificationGCM(e);
break;
case 'error':
alert('<li>ERROR :' + e.msg + '</li>');
break;
default:
alert('<li>Unknown, an event was received and we do not know what it is.</li>');
break;
}
}

Resources