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 is required to process package imports. If you need a different preprocessor remove all packages first.

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

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="ionic.example">
  <head>
    <meta charset="utf-8">
    <title>Map</title>
    <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
    
    <link href="//code.ionicframework.com/nightly/css/ionic.css" rel="stylesheet">
    <script src="//code.ionicframework.com/nightly/js/ionic.bundle.js"></script>
  </head>
  <body ng-controller="MapCtrl" data-ng-init="init()">
    <ion-header-bar class="bar-dark" >
      <h1 class="title">Map</h1>
    </ion-header-bar>
    <ion-content>
      <div class="map-container" ng-show="$root.enableMap">
        <div id="map" data-tap-disabled="true"></div>
      </div>
    </ion-content>
  </body>
</html>
              
            
!

CSS

              
                #map {
  width: 100%;
  height: 100%;
  background-color: #fff !important;
}

.scroll {
  height: 100%;
}

.map-container {
  background-color: #fff;
  padding-left: 20px;
  padding-right: 20px;
  padding-bottom: 10px;
  width: 100%;
  height: 100%;
}

              
            
!

JS

              
                angular.module('ionic.example', ['ionic'])

/*
===========================================================================
  G O O G L E   M A P S
===========================================================================
*/
.factory('GoogleMapsService', ['$rootScope', '$ionicLoading', '$timeout', '$window', '$document', 'ConnectivityService', function($rootScope, $ionicLoading, $timeout, $window, $document, ConnectivityService) {

  var apiKey = false,
    map = null,
    mapDiv = null,
    directionsService,
    directionsDisplay,
    routeResponse;

  function initService(mapEl, key) {
    mapDiv = mapEl;
    if (typeof key !== "undefined") {
      apiKey = key;
    }
    if (typeof google == "undefined" || typeof google.maps == "undefined") {
      disableMap();
      if (ConnectivityService.isOnline()) {
        $timeout(function() {
          loadGoogleMaps();
        }, 0);
      }
    } else {
      if (ConnectivityService.isOnline()) {
        initMap();
        enableMap();
      } else {
        disableMap();
      }
    }
  }

  function initMap() {
    if (mapDiv) {
      var mapOptions = {
        zoom: 10,
        mapTypeId: google.maps.MapTypeId.ROADMAP
      };
      map = new google.maps.Map(mapDiv, mapOptions);
      directionsService = new google.maps.DirectionsService();
      directionsDisplay = new google.maps.DirectionsRenderer();
      directionsDisplay.setMap(map);
      // Wait until the map is loaded
      google.maps.event.addListenerOnce(map, 'idle', function() {
        enableMap();
      });
    }
  }

  function enableMap() {
    // For demonstration purposes we’ll use a $rootScope variable to enable/disable the map.
    // However, an alternative option would be to broadcast an event and handle it in the controller.
    $rootScope.enableMap = true;
  }

  function disableMap() {
    $rootScope.enableMap = false;
  }

  function loadGoogleMaps() {
    // This function will be called once the SDK has been loaded
    $window.mapInit = function() {
      initMap();
    };

    // Create a script element to insert into the page
    var script = $document[0].createElement("script");
    script.type = "text/javascript";
    script.id = "googleMaps";

    // Note the callback function in the URL is the one we created above
    if (apiKey) {
      script.src = 'https://maps.google.com/maps/api/js?key=' + apiKey + '&sensor=true&callback=mapInit';
    } else {
      script.src = 'https://maps.google.com/maps/api/js?sensor=true&callback=mapInit';
    }
    $document[0].body.appendChild(script);
  }

  function checkLoaded() {
    if (typeof google == "undefined" || typeof google.maps == "undefined") {
      $timeout(function() {
        loadGoogleMaps();
      }, 2000);
    } else {
      enableMap();
    }
  }

  function addRoute(origin, destination, waypts, optimizeWaypts) {
    routeResponse = null;
    if (typeof google !== "undefined") {
      var routeRequest = {
        origin: origin,
        destination: destination,
        waypoints: waypts,
        optimizeWaypoints: optimizeWaypts,
        travelMode: google.maps.TravelMode.DRIVING
      };

      directionsService.route(routeRequest, function(response, status) {
        if (status == google.maps.DirectionsStatus.OK) {
          directionsDisplay.setDirections(response);
          google.maps.event.trigger(map, 'resize');
          // Save the response so we access it from controller
          routeResponse = response;
          // Broadcast event so controller can process the route response
          $rootScope.$broadcast('googleRouteCallbackComplete');
        }
      });
    }
  }

  function removeRoute() {
    if (typeof google !== "undefined" && typeof directionsDisplay !== "undefined") {
      directionsDisplay.setMap(null);
      directionsDisplay = null;
      directionsDisplay = new google.maps.DirectionsRenderer();
      directionsDisplay.setMap(map);
    }
  }

  return {
    initService: function(mapEl, key) {
      initService(mapEl, key);
    },
    checkLoaded: function() {
      checkLoaded();
    },
    disableMap: function() {
      disableMap();
    },
    removeRoute: function() {
      removeRoute();
    },
    getRouteResponse: function() {
      return routeResponse;
    },
    addRoute: function(origin, destination, waypts, optimizeWaypts) {
      addRoute(origin, destination, waypts, optimizeWaypts);
    }
  };

}])

/*
===========================================================================
  C O N N E C T I V I T Y
===========================================================================
*/
.factory('ConnectivityService', [function() {
    return {
      isOnline: function() {
        var status = localStorage.getItem('networkStatus');
        if (status === null || status == "online") {
          return true;
        } else {
          return false;
        }
      }
    };
  }])
  /*
  ===========================================================================
    N E T W O R K
  ===========================================================================
  */
  .factory('NetworkService', ['GoogleMapsService', function(GoogleMapsService) {
    /*
     * handles network events (online/offline)
     */
    return {
      networkEvent: function(status) {
        var pastStatus = localStorage.getItem('networkStatus');
        if (status == "online" && pastStatus != status) {
          // The app has regained connectivity...
          GoogleMapsService.checkLoaded();
        }
        if (status == "offline" && pastStatus != status) {
          // The app has lost connectivity...
          GoogleMapsService.disableMap();
        }
        localStorage.setItem('networkStatus', status);
        return true;
      }
    };
  }])

.controller('MapCtrl', function($scope, $rootScope, $timeout, GoogleMapsService) {

  // Ideally, this initService should be called on page load and before code below is run
  $scope.init = function () {
    GoogleMapsService.initService(document.getElementById("map"));
  };
  
  $scope.journeyLegs = [];
  var journeyLeg = {
    "zipPostalCode": "66045",
    "contactId": "1"
  };
  $scope.journeyLegs.push(journeyLeg);

  // Call this method to add the route
  $scope.addRoute = function(origin, destination) {
    if (origin !== "" && destination !== "") {
      // Callout to Google to get route between first and last contact.
      // The 'legs' between these contact will give us the distance/time
      var waypts = [];
      for (i = 0, len = $scope.journeyLegs.length; i < len; i++) {
        waypts.push({
          location: $scope.journeyLegs[i].zipPostalCode,
          stopover: true
        });
      }
      GoogleMapsService.addRoute(origin, destination, waypts, true);
    }
  };

  // Handle callback from Google Maps after route has been generated
  var deregisterUpdateDistance = $rootScope.$on('googleRouteCallbackComplete', function(event, args) {
    $scope.updateDistance();
  });

  // We'll add the route after the initService has loaded the Google Maps javascript
  // We're only adding this timeout here because we've called the initService in the code above, and we need to give it time to load the js
  $timeout(function() {
    // Call the method to add the route
    $scope.addRoute("94087", "27215");
  },3000);
    
  // Deregister the handler when scope is destroyed
  $scope.$on('$destroy', function() {
    deregisterUpdateDistance();
  });

  $scope.updateDistance = function() {
    $timeout(function() {
      // Get the route saved after callback from Google directionsService (to get route)
      var routeResponse = GoogleMapsService.getRouteResponse();
      if (routeResponse) {
        // We’ve only defined one route with waypoints (or legs) along it
        var route = routeResponse.routes[0];
        // The following is an example of getting the distance and duration for the last leg of the route
        var distance = route.legs[route.legs.length - 1].distance;
        var duration = route.legs[route.legs.length - 1].duration;
        console.log("distance.value = ", distance.value);
        console.log("duration.value = ", duration.value);
        console.log("duration.text = ", duration.text);
      }
    });
  };

});
              
            
!
999px

Console