geoService example with broadcast

by jamey777

HTML

<div ng:app="myApp">
 <div ng-controller="Ctrl1">
     <h1>{{coords.latitude}} {{coords.longitude}} {{coords.accuracy}}</h1>
 </div>
</div>

CSS

</style>
<script src="http://ci.angularjs.org/job/angular.js-misko/ws/build/angular.min.js"></script>
<style>
.ng-invalid { border: 1px solid red; } 
body { font-family: Arial,Helvetica,sans-serif; }
body, td, th { font-size: 14px; margin: 0; }
table { border-collapse: separate; border-spacing: 2px; display: table; margin-bottom: 0; margin-top: 0; -moz-box-sizing: border-box; text-indent: 0; }
a:link, a:visited, a:hover { color: #5D6DB6; text-decoration: none; }
.error { color: red; }

JavaScript

var myApp = angular.module('myApp', []);

myApp.factory('geoService', ['$q', '$rootScope', function($q, $rootScope) {
    return function() {
        this.changeLocation= function (coords) {
            $rootScope.$broadcast("locationChanged", {
                coordinates: coords
            });
        };
        var d = $q.defer();
        setTimeout(function () {
            try {
                if (navigator.geolocation) {
                    navigator.geolocation.getCurrentPosition(
                        function (position) {
                            $rootScope.$apply(function () {
                                var longitude = position.coords.longitude;
                                changeLocation(position.coords);
                                d.resolve({
                                    aField: 'Hello ' + position.coords.longitude + '!'
                                });
                            });
                        },
                        function (error) {
                            d.reject(error);
                        }
                    );
                }
                else {
                    d.reject('location services not allowed');
                }
            }
            catch (err) {
                d.reject(err);
            }
        }, 1000);
        return d.promise;
    };}]);

function Ctrl1($scope, geoService) {
    geoService();
    $scope.$on("locationChanged", function (event, parameters) {
        $scope.coords= parameters.coordinates;
    });
}