How to use Angular geolocation directive with google map ? - angularjs

I am using Angular geolocation for get location. Its returning latitude and longitude of location. I want to show map using this latitude and longitude. Also want to show a circle with 5 km. take a look of my code index.html
<html>
<head>
<title>ngGeolocation</title>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.3/angular.js"></script>
<script src="./ngGeolocation.js"></script>
<script src="./index.js"></script>
</head>
<body ng-app="geolocationDemo">
<div ng-controller="AppController">
<h1>Basic (fetch once)</h1>
Latitude: {{location.coords.latitude}}
<br />
Longitude: {{location.coords.longitude}}
<br />
</div>
</body>
</html>
Index.js
angular
.module('geolocationDemo', ['ngGeolocation'])
.controller('AppController', function($scope, $geolocation){
$scope.$geolocation = $geolocation
// basic usage
$geolocation.getCurrentPosition().then(function(location) {
$scope.location = location
});
// regular updates
$geolocation.watchPosition({
timeout: 60000,
maximumAge: 2,
enableHighAccuracy: true
});
$scope.coords = $geolocation.position.coords; // this is regularly updated
$scope.error = $geolocation.position.error; // this becomes truthy, and has 'code' and 'message' if an error occurs
//console.log($scope.coords);
});
ngGeolocation.js
angular
.module('ngGeolocation', [])
.factory('$geolocation', ['$rootScope', '$window', '$q', function($rootScope, $window, $q) {
function supported() {
return 'geolocation' in $window.navigator;
}
var retVal = {
getCurrentPosition: function(options) {
var deferred = $q.defer();
if(supported()) {
$window.navigator.geolocation.getCurrentPosition(
function(position) {
$rootScope.$apply(function() {
retVal.position.coords = position.coords;
deferred.resolve(position);
});
},
function(error) {
$rootScope.$apply(function() {
deferred.reject({error: error});
});
}, options);
} else {
deferred.reject({error: {
code: 2,
message: 'This web browser does not support HTML5 Geolocation'
}});
}
return deferred.promise;
},
watchPosition: function(options) {
if(supported()) {
if(!this.watchId) {
this.watchId = $window.navigator.geolocation.watchPosition(
function(position) {
$rootScope.$apply(function() {
retVal.position.coords = position.coords;
delete retVal.position.error;
$rootScope.$broadcast('$geolocation.position.changed', position);
});
},
function(error) {
$rootScope.$apply(function() {
retVal.position.error = error;
delete retVal.position.coords;
$rootScope.$broadcast('$geolocation.position.error', error);
});
}, options);
}
} else {
retVal.position = {
error: {
code: 2,
message: 'This web browser does not support HTML5 Geolocation'
}
};
}
},
position: {}
//console.log(position);
};
return retVal;
}]);
How to i can do it ? Please suggest me some solutions.

Have a look at angular-google-maps, you should be able to create the map and circle:
http://angular-ui.github.io/angular-google-maps/

Related

Data Store using $resource, $cacheFactory with errorHandlingDirective

Learning AngularJS and trying to create a SPA with a data store for a
REST server. To reduce the traffic as much as possible, I want to
cache the data whenever possible. In the case of an error response
from the server, I would like to handle in one common directive for all callbacks. This would allow me to the directive across several controllers in a common way.
This post all works except the $emit and/or $broadcast are not
firing off the event that the directive is waiting $on. If it was working the template in the Directive will have the error description and be displayed on the HTML page when isError becomes true. At least that is my present thinking...
Plunker
My sample HTML file:
<!DOCTYPE html>
<html ng-app="app">
<head>
<script data-require="angular.js#1.2.x" src="https://code.angularjs.org/1.2.16/angular.js" data-semver="1.2.16"> </script>
<script data-require="angular-resource#1.2.14" data-semver="1.2.14" src="http://code.angularjs.org/1.2.14/angular-resource.js"></script>
<!--script src="app.js"></!--script-->
</head>
<body ng-controller="MainCtrl">
<h1>Hello Plunker!</h1>
{{data}}
<br />
<br />
isError: <error></error>
<br /><br />
Cached Data: {{dataCache}}
<br /><br />
<button ng-click="getData()">Data Callback</button>
<br /><br /><br />
<button ng-click="getError()">Callback Error</button>
<br /><br /><br />
Cache Info: {{oDataServiceInfo}}<br />
<button ng-click="resetCache()">Reset Cache</button>
</body>
</html>
My sample Controller:
var app = angular.module('app', ['ngResource']);
app.controller('MainCtrl', ['$scope', '$rootScope', 'loDataService', function ($scope,$rootScope, loDataService) {
$scope.getData = function () {
loDataService.getData(function (data) {
$scope.dataCache = loDataService.lCache
$scope.oDataServiceInfo = loDataService.oInfo;
$scope.data = data;
}, function (error) {
console.log(error);
})
};
$scope.getError = function () {
loDataService.getError(function (data) {
$scope.dataCache = loDataService.lCache
$scope.oDataServiceInfo = loDataService.oInfo;
$scope.data = data;
}, function (error) {
$rootScope.$broadcast("resourceError", error);
console.log(error);
})
};
$scope.resetCache = function () {
loDataService.resetCache();
$scope.oDataServiceInfo = loDataService.oInfo;
};
}]);
My sample data store:
app.factory('loDataService', ['$resource','$cacheFactory','$rootScope', function ($resource, $cacheFactory, $rootScope) {
var dbcCache = $cacheFactory('loDataService');
var oDBC = $resource('/', {},
{
'GetError': { url:'nonExistingConnection',method: 'GET' },
'GetData': { url: 'sampleData.json', method: 'GET', isArray: false }
});
return {
lCache: true,
oInfo: {},
resetCache: function () {
dbcCache.removeAll();
this.oInfo = dbcCache.info();
},
getData: function (callback, callbackError) {
_this = this;
var markets = dbcCache.get('Markets');
if (!markets) {
// fetch from server
_this.lCache = false;
oDBC.GetData(function (response) {
// store in cache
dbcCache.put('Markets', response.Markets);
_this.oInfo = dbcCache.info();
// return response
callback(response.Markets);
},
function (error) {
// oh no, what went wrong?
callbackError(error);
});
} else {
// return the cache
_this.lCache = true;
callback(markets);
}
},
getError: function (callback, callbackError) {
_this = this;
var marketsX = dbcCache.get('MarketsX');
if (!marketsX) {
// fetch from server
_this.lCache = false;
oDBC.GetError(function (response) {
// store in cache
dbcCache.put('MarketsX', response.Markets);
// return response
callback(response.Markets);
},
function (error) {
// oh no, what went wrong?
callbackError(error);
$rootScope.$broadcast("resourceError", error);
});
} else {
// return the cache
_this.lCache = true;
callback(marketsX);
}
}
}
}]);
My sample Directive:
app.directive("resourceError", ['$rootScope', function ($rootScope) {
return {
restrict: 'E',
template: '<div class="alert-box alert" ng-show="isError" >Error!!!</div>',
link: function (scope) {
$rootScope.$on("resourceError", function (event, error) {
scope.isError = true;
console.log(error);
})
}
}
}]);
Here in my "sampleData.json" file.
{
"Markets": [{
"id": 1,
"name": "Downtown",
"eventday": "1/1/1991",
"active": true
}, {
"id": 2,
"name": "County",
"eventday": "2/2/1991",
"active": true
}, {
"id": 3,
"name": "Beach",
"eventday": "3/3/1991",
"active": false
}]
}
Any thoughts?

I want to update map with the user's location co-ordinates. The map is first rendered but not getting updated

I am trying to update the map coordinates with the user's location. Right now what is happening the ng-maps is getting loaded with defined constants. Geolocation service gets the user coordinates but map is not getting updated.
<!DOCTYPE html>
<html ng-app='App'>
<head>
<style type='text/css'>
body, html { height: 50%; margin: 0;}
.google-map { height: 50%; }
</style>
<script src='//maps.googleapis.com/maps/api/js'></script>
<script src='//ajax.googleapis.com/ajax/libs/angularjs/1.3.3/angular.min.js'></script>
<script src='Scripts/ng-maps.js'></script>
<script>
angular.module('App', ['ngMaps'])
.factory('GeolocationService', [
'$q', '$window', '$rootScope', function ($q, $window, $rootScope){
return function () {
var deferred = $q.defer();
if (!$window.navigator) {
$rootScope.$apply(function() {
deferred.reject(new Error("Geolocation is not supported"));
});
} else {
$window.navigator.geolocation.getCurrentPosition(function (position) {
$rootScope.$apply(function() {
deferred.resolve(position);
});
}, function (error) {
$rootScope.$apply(function() {
deferred.reject(error);
});
});
}
return deferred.promise;
}
}])
.controller('Main',['$scope', 'GeolocationService', function ($scope, geolocation) {
geolocation().then(function (position) {
console.log(position.coords.latitude);
console.log(position.coords.longitude);
//$scope.position = position;
$scope.map = {
center: [position.coords.latitude, position.coords.longitude]
}
$scope.marker = {
position: [position.coords.latitude, position.coords.longitude],
options: function () {
return {
draggable: true
}
},
events: {
click: function (e) {
alert(e.latLng)
}
}
}
}, function (reason) {
$scope.message = "Could not be determined."
});
$scope.apply();
}]);
</script>
</head>
<body ng-controller="Main">
<map ng-transclude class='google-map' center="map.center" >
<marker position="marker.position" options="marker.options" events="marker.events"></marker>
</map>
</body>
</html>
I am new to angular might be missing a smaal.

accessing Json key-value pair for angularjs controller using services

I have been trying to use data from my service for a chart in my angularjs controller.I have made a service in service.js which i am using in my controller.All i get is the Object array,but when i try to access values inside the Object array ,it throws errors for each approach i use .Following is what i am doing
My Service
var demoService= angular.module('demoService',[])
.service('myService',function($http,$q){
var deferred = $q.defer();
$http.get('http://enlytica.com/RSLivee/rest/census').then(function(data)
{
deferred.resolve(data);
});
this.getPlayers=function()
{
return deferred.promise;
}
})
My Controller
angular.module("app.controllers", [])
.controller("gaugeCtrl", ["$scope","config","myService",
function ($scope,config,myService) {
var promise=myService.getPlayers();
promise.then(function(data)
{
$scope.players=data.data;
//console.log($scope.players.Tweets);
($scope.players.Tweets).each(function(index, element) {
console.log(element.FAVOURITE_COUNT);
});
});
return $scope.gaugeHome = {
gaugeData: {
maxValue: 9000,
animationSpeed: 100,
val: 1000
},
gaugeOptions: {
lines: 12,
angle: 0,
lineWidth: 0.47,
pointer: {
length: 0.6,
strokeWidth: 0.03,
color: "#555555"
},
limitMax: "false",
colorStart: config.secondary_color,
colorStop: config.secondary_color,
strokeColor: "#F5F5F5",
generateGradient: !0,
percentColors: [
[0, config.secondary_color],
[1, config.secondary_color]
]
}
}
I have also included the service Module in my app.js :
var app = angular.module("app",["demoService"])
How can i access a particular value for my gaugectrl properly .Is following a wrong way to access it ?
($scope.players.Tweets).each(function(index, element) {
console.log(element.FAVOURITE_COUNT);
Thanks in Advance
Looks like everything is working. It seems like you are trying to access the objects in the array incorrectly.
I think you want to use Array.forEach
someArray.forEach(function(element, index, array) {
// Do stuff here.
});
I made a simplified version of your code:
var app = angular.module('app', []);
app.controller('myController', function($scope, $q, $http) {
var deferred = $q.defer();
$http.get('http://enlytica.com/RSLivee/rest/census').then(function(data) {
deferred.resolve(data);
});
var promise = deferred.promise;
promise.then(function(data) {
var tweets = [];
var total = 0;
$scope.players = data.data;
($scope.players.Tweets).forEach(function(element) {
console.log(element);
tweets.push({FAVOURITE_COUNT: element. FAVOURITE_COUNT, TWEET_ID: element.TWEET_ID});
total += element.FAVOURITE_COUNT;
});
$scope.something.tweets = JSON.stringify(tweets, null, 2);
$scope.something.favoriteTotal = total;
});
$scope.something = {};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
<div ng-app='app' ng-controller='myController'>
{{ something.favoriteTotal }}
<pre>{{ something.tweets }}</pre>
</div>

How to add twitter feed in AngularJS / Ionic apps for android

I have used sample code to add twitter feed in my apps from following link
https://github.com/bradleyprice/ionic_twitterfeed but I got token null, so nothing to show in my app just refreshing screen.After that i refer blog http://blog.ionic.io/displaying-the-twitter-feed-within-your-ionic-app/ it also give me same result.
Please suggest me changes or any another link where i get best solution.
Some code are shown as follows , in index.html
<!-- ionic/angularjs js -->
<script src="lib/ionic/js/ionic.bundle.js"></script>
<!-- cordova script (this will be a 404 during development) -->
<script src="lib/sha.js"></script>
<script src="lib/angular-resource/angular-resource.js"></script>
<script src="lib/ngCordova/dist/ng-cordova.js"></script>
<script src="js/ng-cordova-oauth.js"></script>
<!-- your app's js -->
<script src="js/app.js"></script>
<script src="js/controllers.js"></script>
<script src="js/services.js"></script>
</head>
<body ng-app="starter" ng-controller="AppCtrl">
app.js
angular.module('starter', ['ionic', 'ngResource', 'ngCordova'])
.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) {
StatusBar.styleDefault();
}
});
});
controllers.js
angular.module('starter').controller('AppCtrl', function($scope, $ionicPlatform, $ionicPopup, TwitterService) {
// Should we show the post tweet button
$scope.showUpdateStatus = true;
// 1
$scope.correctTimestring = function(string) {
return new Date(Date.parse(string));
};
// 2
$scope.showHomeTimeline = function() {
alert("1");
TwitterService.getHomeTimeline().then(function(res) {
alert("home_timeline");
$scope.home_timeline = res;
}, function(req) {
console.log(req);
});
};
// 3
$scope.doRefresh = function() {
$scope.showHomeTimeline();
$scope.$broadcast('scroll.refreshComplete');
};
$scope.updateStatus = function() {
TwitterService.updateStatus().then(function(res) {
$scope.showUpdateStatus = false;
$scope.doRefresh();
}, function(req) {
console.log(req);
});
}
// 4
$ionicPlatform.ready(function() {
if (TwitterService.isAuthenticated()) {
$scope.showHomeTimeline();
} else {
TwitterService.initialize().then(function(result) {
if(result === true) {
$scope.showHomeTimeline();
}
});
}
});
});
services.js
angular.module('starter',['ionic', 'ngCordovaOauth']).factory('TwitterService', function($cordovaOauth, $cordovaOauthUtility, $http, $resource, $q) {
// 1
var twitterKey = "";
var clientId = '';
var clientSecret = '';
// 2
function storeUserToken(data) {
window.localStorage.setItem(twitterKey, JSON.stringify(data));
}
function getStoredToken() {
return window.localStorage.getItem(twitterKey);
}
// 3
function createTwitterSignature(method, url) {
var token = angular.fromJson(getStoredToken());
var oauthObject = {
oauth_consumer_key: clientId,
oauth_nonce: $cordovaOauthUtility.createNonce(32),
oauth_signature_method: "HMAC-SHA1",
oauth_timestamp: Math.round((new Date()).getTime() / 1000.0),
oauth_token: token.oauth_token,
oauth_version: "1.0"
};
var signatureObj = $cordovaOauthUtility.createSignature(method, url, oauthObject, {}, clientSecret, token.oauth_token_secret);
$http.defaults.headers.common.Authorization = signatureObj.authorization_header;
}
function createTwitterPostSignature(method, url, message) {
var token = angular.fromJson(getStoredToken());
var oauthObject = {
oauth_consumer_key: clientId,
oauth_nonce: $cordovaOauthUtility.createNonce(32),
oauth_signature_method: "HMAC-SHA1",
oauth_timestamp: Math.round((new Date()).getTime() / 1000.0),
oauth_token: token.oauth_token,
oauth_version: "1.0",
status: message
};
var signatureObj = $cordovaOauthUtility.createSignature(method, url, oauthObject, oauthObject, clientSecret, token.oauth_token_secret);
$http.defaults.headers.common.Authorization = signatureObj.authorization_header;
}
return {
// 4
initialize: function() {
var deferred = $q.defer();
var token = getStoredToken();
alert(token);
if (token !== null) {
deferred.resolve(true);
} else {
$cordovaOauth.twitter(clientId, clientSecret).then(function(result) {
storeUserToken(result);
deferred.resolve(true);
}, function(error) {
deferred.reject(false);
});
}
return deferred.promise;
},
// 5
isAuthenticated: function() {
return getStoredToken() !== null;
},
// 6
getHomeTimeline: function() {
var home_tl_url = 'https://api.twitter.com/1.1/statuses/home_timeline.json';
createTwitterSignature('GET', home_tl_url);
return $resource(home_tl_url).query().$promise;
},
updateStatus: function() {
var message = "test from ionic";
var update_url = 'https://api.twitter.com/1.1/statuses/update.json';
var results = createTwitterPostSignature('POST', update_url, message);
return $resource(update_url, {'status': message}).save().$promise;
},
storeUserToken: storeUserToken,
getStoredToken: getStoredToken,
createTwitterSignature: createTwitterSignature,
createTwitterPostSignature: createTwitterPostSignature
};
})
Might be worth checking out this example on Github
https://github.com/bradleyprice/ionic_twitterfeed

angular, try to display object in ng-repeat fails

i'm writing an mobile application in javascript with angularJS and ionicframework (last beta v.11), i create dinamically an object and want to display all objects inside in a ng-repeat. Why nr-repeat don't display anything?
This is screen from my object:
I use this code for put values in scope:
$scope.distanceSuppliers = myCar;
And this is the code in html:
<ion-item ng-repeat="(id, supplier) in distanceSuppliers">
<div class="items item-button-right" ng-click="openDetails(id)">
{{supplier.name}}<br />
{{supplier.address}}<br />
</div>
</ion-item>
This is my complete code for JS:
.controller('suppliers', function($scope, cw_db, $ionicPopup, $ionicActionSheet, appdelegate, $rootScope, $firebase, $location, $ionicLoading, cw_position) {
$ionicLoading.show({
template: 'Updating data..'
});
var geocoder;
var tot = 0;
var done = 0;
geocoder = new google.maps.Geocoder();
cw_db.getData(cw_db.getSuppliers(), "", function(suppliers) {
cw_position.getPosition(function (error, position) {
suppliers.on('value', function(supp) {
$scope.distanceSuppliers = {};
tot = 0;
done = 0;
supp.forEach(function(childSnapshot) {
tot++;
var childData = childSnapshot.val();
if (childData.address) {
calculateDistance(childData, position.coords.latitude, position.coords.longitude);
}
});
});
$ionicLoading.hide();
});
});
function calculateDistance(childData, usrLat, usrLon) {
var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix(
{
origins: [new google.maps.LatLng(usrLat, usrLon)],
destinations: [childData.address],
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.METRIC,
avoidHighways: false,
avoidTolls: false
}, function(response, status) {
if (status != google.maps.DistanceMatrixStatus.OK) {
alert('Error was: ' + status);
} else {
done++;
var results = response.rows[0].elements;
childData.distance = results[0].distance.value;
$scope.distanceSuppliers.push(childData);
if (done == tot) {
console.log($scope.distanceSuppliers);
}
}
});
}
$scope.openDetails = function(index) {
//appdelegate.setCallId(index);
//$location.path("/app/supplierDetails");
}
})
what's wrong?
Not sure, but I believe you have a data binding update problem.
Try using the $timeout to force the render:
w_position.getPosition(function (error, position) {
$timeout(function() {
suppliers.on('value', function(supp) {
$scope.distanceSuppliers = {};
tot = 0;
done = 0;
supp.forEach(function(childSnapshot) {
tot++;
var childData = childSnapshot.val();
if (childData.address) {
calculateDistance(childData, position.coords.latitude, position.coords.longitude);
}
});
});
$ionicLoading.hide();
});
});
And don't forget to add the $timeout parameter to the controller:
.controller('suppliers', function($scope, ...<other parameters here>..., $timeout) {
I found the problem! Fix using $scope.$apply();
The problem was that i was writing in a different $scope using this code:
cw_position.getPosition(function (error, position) {
suppliers.on('value', function(supp) {
tot = 0;
done = 0;
supp.forEach(function(childSnapshot) {
tot++;
var childData = childSnapshot.val();
if (childData.address) {
calculateDistance(childData, position.coords.latitude, position.coords.longitude);
}
});
});
$ionicLoading.hide();
});
where cw_position.getPosition call a js with this code:
angular.module('cw_position', [])
.service('cw_position', function() {
this.getPosition = function(callback) {
navigator.geolocation.getCurrentPosition(
function (position) {
return callback(null, position);
},
function(error) {
return callback(error, null);
}
);
}
// Built google maps map option
//
this.getGoogleMapOptions = function (lat, lon, zoom, type) {
if (type == null) {
type = google.maps.MapTypeId.ROADMAP;
}
var mapOptions = {
center: new google.maps.LatLng(lat, lon),
zoom: zoom,
mapTypeId: type
};
return mapOptions;
}
});
navigator.geolocation.getCurrentPosition causes the 'problem'
Thx to all for your help

Resources