Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <html ng-app="whereismycar">
<head>
    <title>Where is my car</title>
    <meta http-equiv="Content-type" content="text/html; charset=utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=0" />
    
    <link rel="stylesheet" href="https://code.ionicframework.com/1.0.0-beta.3/css/ionic.min.css" />
    <link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.7.2/leaflet.css" />
    
    <script type="text/javascript" src="http://cdn.leafletjs.com/leaflet-0.7.2/leaflet.js"></script>
    <script type="text/javascript" src="https://code.ionicframework.com/1.0.0-beta.3/js/ionic.bundle.min.js"></script>
    <script type="text/javascript" src="https://cdn.rawgit.com/gsklee/ngStorage/master/ngStorage.min.js"></script>
</head>
<body ng-controller="ApplicationCtrl">
    <ion-header-bar class="bar-transparent">
      <h1 class="title">Where Is My Car??</h1>
      <div class="buttons">
        <button ng-click="updatePosition()" ng-if="!saved" class="button button-icon icon ion-loop"></button>
        <a class="button button-icon icon ion-close" ng-if="inProgress || saved" ng-click="reinitialize()"></a>
      </div>
    </ion-header-bar>
    <ion-content scroll="false">
      <div id="map"></div>
    </ion-content>
    <ion-footer-bar class="bar-dark">
      <div class="buttons">
        <a ng-click="updatePosition()" ng-if="!saved && !carPosition" class="button button-icon icon ion-refresh">Update location</a>
        <a ng-click="savePosition()" ng-if="!saved && carPosition" class="button button-icon icon ion-location">Remember this location</a>
        <a ng-click="findCar()" ng-if="saved && !inProgress" class="button button-icon icon ion-model-s">Find my car</a>
      </div>
      <h1 class="title" ng-if="inProgress">Distance to the car {{ distanceToCar | number}}Km</h1>
    </ion-footer-bar>
  </body>
</html>

              
            
!

CSS

              
                 #map {
   width: 100%;
   height: 100%;
 }

.scroll {
  height: 100%;
}

              
            
!

JS

              
                /*

The MIT License (MIT)

Copyright (c) [year] [fullname]

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

*/

var App = angular.module('whereismycar', [
    'ionic',
    'ngStorage'
]);

App.factory('Geolocation', [
    '$rootScope', 
    '$q', 
    '$interval', 
    '$http', 
    function($rootScope, $q, $interval, $http) {
        var watchId = null;
        var url = 'https://maps.googleapis.com/maps/api/geocode/json?sensor=true&latlng=';

        var options = {
            enableHighAccuracy: false,
            timeout: 5000,
            maximumAge: 0
        };

        var toRad = function(deg) {
          return deg * (Math.PI/180);
        };

        function _distance(pos1, pos2) {
            var R = 6371; // Radius of the earth in km
            var dLat = toRad(pos1.coords.latitude - pos2.coords.latitude);  // deg2rad below
            var dLon = toRad(pos2.coords.longitude - pos1.coords.longitude); 
            var a = 
                Math.sin(dLat/2) * Math.sin(dLat/2) +
                Math.cos(toRad(pos1.coords.latitude)) * Math.cos(toRad(pos2.coords.latitude)) * 
                Math.sin(dLon/2) * Math.sin(dLon/2); 
            var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); 
            var d = R * c; // Distance in km
            return d;
        }

        function _getCurrentPosition() {
            var d = $q.defer();

            navigator.geolocation.getCurrentPosition(
                function (pos) {
                    d.resolve(pos);
                }, 
                function (err) {
                    d.reject(err);
                },
                options
            );

            return d.promise;
        }

        // NOTE: after some blocking issues between getCurrentPosition and watchPosition, 
        // I decided to emulate watchPosition with a $interval and getCurrentPosition
        function _alternativeWatchPosition() {
            watchId = $interval(function() {
                navigator.geolocation.getCurrentPosition(
                    function (pos) {
                        $rootScope.$broadcast('positionChanged', pos);
                    }, 
                    function (err) {

                    },
                    options
                );
            }, 15000);
        }

        function _clearWatch() {
            $interval.cancel(watchId);
            watchId = undefined;
        }

        function _reverseGeocoding(pos) {
            var d = $q.defer();
            
            $http.get(url + pos.coords.latitude +','+ pos.coords.longitude)
                .success(function(response) {
                    if (response.status === 'OK') {
                        d.resolve(response.results[0].formatted_address);
                    } else {
                        d.reject();
                    }  
                })
                .error(function() {
                    d.reject();
                });

            return d.promise;
        }

        return {
            getCurrentPosition: _getCurrentPosition,
            watchPosition: _alternativeWatchPosition,
            clearWatch: _clearWatch,
            distance: _distance,
            reverseGeocoding: _reverseGeocoding
        };
    }
]);


App.controller('ApplicationCtrl', [
    'Geolocation', 
    '$localStorage', 
    '$ionicLoading', 
    '$ionicPopup',
    '$timeout',
    '$scope', 
    function(Geolocation, $localStorage, $ionicLoading, $ionicPopup, $timeout, $scope) {
        // leaflet variables
        var map = L.map('map');
        var userMarker = L.marker();
        var carMarker = L.marker();
        var radio = L.circle();

        $scope.carPosition = null;
        $scope.inProgress = false;
        $scope.saved = false;
        $scope.distanceToCar = 0.0;
        
        function initialize() {
            
            $ionicLoading.show({
                content: 'Initializing...',
                showBackdrop: true
            });
            
            // set the tile layer
            L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
                attribution: 'Map data © <a href="http://openstreetmap.org">OpenStreetMap</a> contributors',
                maxZoom: 18
            }).addTo(map);

            if ($localStorage.carPosition) {
                var pos = $localStorage.carPosition;
                var latlng = [pos.coords.latitude, pos.coords.longitude];
                $scope.saved = true;
                map.setView(latlng, 16);
                // display car marker on the map
                carMarker.setLatLng(latlng).addTo(map);
                
                // reverse geocoding geocoordinates
                Geolocation.reverseGeocoding(pos).then(function(address) {
                    carMarker.bindPopup('<b>'+ address +'</b>');
                });
                
                $ionicLoading.hide();
                return;
            }
            
            Geolocation.getCurrentPosition().then(
                function(pos) {
                    // center the map on the current coordinates
                    var latlng = [pos.coords.latitude, pos.coords.longitude];
                    map.setView(latlng, 16);
                    // display car marker on the map
                    carMarker.setLatLng(latlng).addTo(map);
                    
                    // reverse geocoding geocoordinates
                    Geolocation.reverseGeocoding(pos).then(function(address) {
                        carMarker.bindPopup('<b>'+ address +'</b>');
                    });
                    
                    carMarker.on('mousedown', function() {
                        carMarker.togglePopup();
                    });
                    
                    $scope.carPosition = pos;
                    $ionicLoading.hide();
                }, 
                function(error) {
                    alert('Unable to get location: ' + error.message);
                    $ionicLoading.hide();
                }
            );
        }
        
        initialize();
        
        $scope.$on('positionChanged', function(event, pos) {
            $timeout(function(){    //use this instead of calling $apply or $digest
                // calculate the distance between the user and his car
                $scope.distanceToCar = Geolocation.distance(pos, $localStorage.carPosition);
                // if the distance is less than 50 meters
                if ($scope.distanceToCar <= 0.05) {
                    $ionicPopup.alert({title: 'Where is my car?', template: 'You have found your car!'});
                    $scope.reinitialize();
                } else {
                    var latlng = [pos.coords.latitude, pos.coords.longitude];
                    // update marker position
                    userMarker.setLatLng(latlng).update();
                    radio.setRadius(pos.coords.accuracy).setLatLng(latlng).addTo(map);
                    // recenter map around user position
                    map.setView(latlng);
                }
            });
        });
        
        $scope.savePosition = function() {
            if ($scope.carPosition) {
                $localStorage.carPosition = $scope.carPosition;
                $scope.saved = true;
            }
        };
        
        $scope.findCar = function() {
            
            $ionicLoading.show({
              content: 'Getting user location...',
              showBackdrop: true
            });
            
            Geolocation.getCurrentPosition().then(
                function(pos) {
                    $scope.inProgress = true;
                    // initialize user marker
                    userMarker.setLatLng([pos.coords.latitude, pos.coords.longitude]).update().addTo(map);
                    $scope.$broadcast('positionChanged', pos);
                    // start tracking user position
                    Geolocation.watchPosition();
                    $ionicLoading.hide();
                }, 
                function(error) {
                    alert('Unable to get location: ' + error.message);
                    $scope.inProgress = false;
                    $ionicLoading.hide();
                }
            );
        };
        
        $scope.reinitialize = function() {
            Geolocation.clearWatch();
            $scope.carPosition = null;
            $scope.inProgress = false;
            $scope.saved = false;
            $scope.distanceToCar = 0.0;
            map.removeLayer(userMarker);
            delete $localStorage.carPosition;
        };
        
        $scope.updatePosition = function() {
            $ionicLoading.show({
              content: 'Getting current location...',
              showBackdrop: true
            });

            Geolocation.getCurrentPosition().then(
                function(pos) {
                    var latlng = [pos.coords.latitude, pos.coords.longitude];
                    carMarker.setLatLng(latlng).update().addTo(map);
                    // reverse geocoding geocoordinates
                    Geolocation.reverseGeocoding(pos).then(function(address) {
                        carMarker.setPopupContent('<b>'+ address +'</b>');
                    });
                    map.setView(latlng);
                    $scope.carPosition = pos;
                    $ionicLoading.hide();
                }, 
                function(error) {
                    alert('Unable to get location: ' + error.message);
                    $ionicLoading.hide();
                }
            );
        };
    }
]);

              
            
!
999px

Console