Navigation

Friday 17 June 2016

Integrating Google Maps Driving Directions with an Ionic App



In this blog I am going to explain you how to integrate the Google Maps JavaScript SDK into an Ionic application.

Generate a New Ionic Application
Generate a new Ionic application by running the following command on your node.js command prompt

ionic start ionic-maps blank

Add the ngCordova Plugin
First check bower is installed with your machine using the following Command
bower -v
If It gives no result or error then first install bower

npm install bower –g

then ngCordova

bower install ngCordova

If plugin will not installing, download the ngCordova folder from here.
And add the ngCordova library to your index.html file.
<!-- cordova script (this will be a 404 during development) -->
    <script src="lib/ngCordova/dist/ng-cordova.js"></script>
    <script src="cordova.js"></script>

Note: The above files are available on following path of downloaded project[ionic-dynamic-master] 

   \Downloads\ng-cordova-master\ng-cordova-master\demo\www\lib\ngCordova
   \Downloads\ng-cordova-master\ng-cordova-master\demo\www\cordova.js

Add the Geolocation Plugin.

For capturing the users current location more accurate we will add the following plugin.

cordova plugin add cordova-plugin-geolocation

This will enable devices GPS to grab a more accurate representation of their location.For more detail follow the link Geolocation plugin.


Require ngCordova in the angular module in app.js

  angular.module('starter', ['ionic','ngCordova'])




ngCordova should now be installed and ready to use in our application. Next, let’s

Include the Google Maps JavaScript SDK.

You can find instructions on how to do that here.
Add the following script to your index.html file

your app's js -->
<script src="js/app.js"></script>
<script src="http://maps.google.com/maps/api/js?key= YOUR_API_KEY_GOES_HERE &sensor=true"></script>

Make sure you put your API Key in the URL above, or just drop the key parameter altogether.

Create a Map in Your Application.

Now we’re going to look at how to actually display a map in our Ionic application. To do that we will be creating a new view with it’s own template.
Create a new templates folder at www/templates
Create a new file called map.html in the templates folder and add the following code
<ion-view title="Directions">
    <ion-content>
        <button type="button" ng-click="launchNavigator();">GetDirection</button>
        <div id="map" data-tap-disabled="true"></div>
    </ion-content>
</ion-view>


Modify the  index.html file to reflect the following: 
<!DOCTYPE html>

<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
    <title></title>

    <!-- compiled css output -->
    <link href="css/ionic.app.css" rel="stylesheet">
    <!-- ionic/angularjs js -->
    <script src="lib/ionic/js/ionic.bundle.js"></script>
    <!-- cordova script (this will be a 404 during development) -->
    <script src="lib/ngCordova/dist/ng-cordova.js"></script>
    <script src="cordova.js"></script>
    <!-- your app's js -->
    <script src="js/app.js"></script>
    <script src="http://maps.google.com/maps/api/js?key=YOUR_API_KEY_GOES_HERE&sensor=true"></script>
    <style>
        .scroll {
            height: 100%;
        }

        #map {
            width: 100%;
            height: 100%;
        }
    </style>
</head>
<body ng-app="starter">
    <ion-pane>
        <ion-header-bar class="bar-stable">
            <h1 class="title">Ionic Maps</h1>
        </ion-header-bar>
        <ion-nav-view></ion-nav-view>
    </ion-pane>
</body>
</html>


Add the following  config to your module in app.js

// Ionic Starter App

// angular.module is a global place for creating, registering and retrieving Angular modules
// 'starter' is the name of this angular module example (also set in a <body> attribute in index.html)
// the 2nd parameter is an array of 'requires'
var latLng;
angular.module('starter', ['ionic','ngCordova'])
.run(function($ionicPlatform) {
  $ionicPlatform.ready(function() {
    if(window.cordova && window.cordova.plugins.Keyboard) {
      // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
      // for form inputs)
      cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);

      // Don't remove this line unless you know what you are doing. It stops the viewport
      // from snapping when text inputs are focused. Ionic handles this internally for
      // a much nicer keyboard experience.
      cordova.plugins.Keyboard.disableScroll(true);
    }
    if(window.StatusBar) {
      StatusBar.styleDefault();
    }
  });
})
.config(function($stateProvider, $urlRouterProvider) {
  $stateProvider
  .state('map', {
    url: '/',
    templateUrl: 'templates/map.html',
    controller: 'MapCtrl'
  });
   $urlRouterProvider.otherwise("/");

})
.controller('MapCtrl', function($scope, $state, $cordovaGeolocation) { 
    var options = {timeout: 10000, enableHighAccuracy: true};
    $cordovaGeolocation.getCurrentPosition(options).then(function(position){
    latLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
    debugger;   
    var mapOptions = {
      center: latLng,
      zoom: 15,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    }; 
    $scope.map = new google.maps.Map(document.getElementById("map"), mapOptions);    
    google.maps.event.addListenerOnce($scope.map, 'idle', function(){

          var marker = new google.maps.Marker({
              map: $scope.map,
              animation: google.maps.Animation.DROP,
              position: latLng
          });    

          var infoWindow = new google.maps.InfoWindow({
             // content: "Here I vijay!"
              content: 'Latitude: ' + latLng.lat() + '<br>Longitude: ' + latLng.lng()
          });
          google.maps.event.addListener(marker, 'click', function () {
              infoWindow.open($scope.map, marker);
          });     
      });
       debugger;
  
     });

    // button click to set directions.
    $scope.launchNavigator = function() {
        debugger;
        var directionsService = new google.maps.DirectionsService;
        var directionsDisplay = new google.maps.DirectionsRenderer;
        directionsDisplay.setMap($scope.map);
        calculateAndDisplayRoute(directionsService, directionsDisplay);
    };  
   
});
function calculateAndDisplayRoute(directionsService, directionsDisplay) {
  directionsService.route({
   origin: latLng,
    destination: "Delhi",
    travelMode: google.maps.TravelMode.DRIVING
  }, function(response, status) {
    if (status === google.maps.DirectionsStatus.OK) {
      directionsDisplay.setDirections(response);
    } else {
      window.alert('Directions request failed due to ' + status);
    }
     });
} 

No comments:

Post a Comment