Logo

Google map with ionic

avatar justin 02 Jul 2015

Google map with ionic

本文介绍如何在ionic添加google map.

初始化ionic项目

  ionic start map blank --sass --id com.beansmile.maps
  cd map
  npm install
  gulp sass

添加以下代码到ionic.project

  "gulpStartupTasks": ["sass", "watch"]

个人建议在初始化ionic项目的时候,id参数是必须的,生成的id将做为ios app 的bundle id和android app的package name
–sass 参数默认启动sass功能,也可以在以后添加,详见Using Sass

添加定位插件geolocation

  ionic plugin add cordova-plugin-geolocation

查看Google Maps Javascript SKD并到Google API Console创建一个Google Maps application.

当你拿到你的google api key后,添加到www/index.html

<!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>

<!--     <link href="lib/ionic/css/ionic.css" rel="stylesheet">
    <link href="css/style.css" rel="stylesheet">
 -->
    <!-- IF using Sass (run gulp sass first), then uncomment below and remove the CSS includes above -->
    <link href="css/ionic.app.css" rel="stylesheet">

    <!-- ionic/angularjs js -->
    <script src="lib/ionic/js/ionic.bundle.js"></script>

    <script src="https://maps.googleapis.com/maps/api/js?key=[YOU KEY HERE]&sensor=true"></script>

    <!-- cordova script (this will be a 404 during development) -->
    <script src="cordova.js"></script>

    <!-- your app's js -->
    <script src="js/app.js"></script>
    <script src="js/controllers.js"></script>
    <script src="js/directives.js"></script>
  </head>

  <body ng-app="starter" ng-controller="MapCtrl">
    <ion-header-bar class="bar-stable">
      <h1 class="title">Map</h1>
    </ion-header-bar>

    <ion-content scroll="false">
      <a class="button button-icon icon ion-location map-icon-location active" ng-click="centerOnMe()"></a>
      <a class="button button-icon icon ion-navicon map-icon-menu" ng-click="direction()"></a>
      <map on-create="mapCreated(map)"></map>
    </ion-content>

    <ion-footer-bar class="bar-stable">
        <a class="button button-icon icon ion-woman item-button-left"></a>
        <!-- <p>SANSOME STREET</p> -->
        <a class="button button-icon icon ion-chevron-right item-button-right"></a>
      </a>
<!--       <div class="list">

          <a class="item item-thumbnail-left" href="#">
            ![](https://blog.beansmile.com/cover.jpg)
            <h2>Pretty Hate Machine</h2>
            <p>Nine Inch Nails</p>
          </a>

          ...

      </div>
 -->      <!-- <a ng-click="centerOnMe()" class="button button-icon icon ion-navigate"></a> -->
    </ion-footer-bar>
  </body>
</html>

添加样式

map {
  display: block;
  width: 100%;
  height: 100%;
}
.scroll {
  height: 100%;
}

.map-icon-location{
  background-color: #fff;
  width: 47px;
  border-radius: 47px;
  margin-top: 50px;
  margin-left: 10px;
  position: fixed;
  z-index: 10000;
  box-shadow: 1px 1px 3px 2px #C2BDBD;
}
.map-icon-location.active, .map-icon-menu.active {
  background-color: #49AEF8 !important;
  opacity: 1 !important;
  color: #fff;
}

.map-icon-menu {
  background-color: #fff;
  width: 47px;
  border-radius: 47px;
  margin-top: 100px;
  margin-left: 10px;
  position: fixed;
  z-index: 10000;
  box-shadow: 1px 1px 3px 2px #C2BDBD;
}

添加map的directives

angular.module('starter.directives', [])

.directive('map', function() {
  return {
    restrict: 'E',
    scope: {
      onCreate: '&'
    },
    link: function ($scope, $element, $attr) {
      function initialize() {
        var mapOptions = {
          center: new google.maps.LatLng(43.07493, -89.381388),
          zoom: 16,
          mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        var map = new google.maps.Map($element[0], mapOptions);
        $scope.onCreate({map: map});

        // Stop the side bar from dragging when mousedown/tapdown on the map
        google.maps.event.addDomListener($element[0], 'mousedown', function (e) {
          e.preventDefault();
          return false;
        });
      }

      if (document.readyState === "complete") {
        initialize();
      } else {
        google.maps.event.addDomListener(window, 'load', initialize);
      }
    }
  }
});

添加对于的controller.js

angular.module('starter.controllers', [])

.controller('MapCtrl', function($scope, $ionicLoading) {
  $scope.mapCreated = function(map) {
    $scope.map = map;
  };

  $scope.direction = function(){
    if (!$scope.map) {
      return;
    }

    $scope.loading = $ionicLoading.show({
      template: 'Getting current location...',
      showBackdrop: false
    });

    navigator.geolocation.getCurrentPosition(function (pos) {
      console.log('Got pos', pos);
      center = new google.maps.LatLng(37.772323, -122.214897);
      target = new google.maps.LatLng(37.771923, -122.219339);

      $scope.map.setCenter(center);

      var directionsDisplay = new google.maps.DirectionsRenderer();
      var directionsService = new google.maps.DirectionsService();

      directionsDisplay.setMap($scope.map);


      var request = {
          origin:center,
          destination:target,
          travelMode: google.maps.TravelMode.DRIVING
      };
      directionsService.route(request, function(response, status) {
        if (status == google.maps.DirectionsStatus.OK) {
          directionsDisplay.setDirections(response);
        }
      });

      $ionicLoading.hide();
    }, function (error) {
      alert('Unable to get location: ' + error.message);
    });
  }

  $scope.centerOnMe = function () {
    console.log("Centering");
    if (!$scope.map) {
      return;
    }

    $scope.loading = $ionicLoading.show({
      template: 'Getting current location...',
      showBackdrop: false
    });

    navigator.geolocation.getCurrentPosition(function (pos) {
      console.log('Got pos', pos);
      center = new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude);
      $scope.map.setCenter(center);
      var marker = new google.maps.Marker({
        position: center,
        map: $scope.map,
        title: 'Hello World!'
      });
      $ionicLoading.hide();
    }, function (error) {
      alert('Unable to get location: ' + error.message);
    });
  };
});

打开app.js,注入controllers directives

  angular.module('starter', ['ionic','starter.controllers', 'starter.directives'])

以上根据google api, 添加了定位功能;两个地点的路线规划功能,为了演示方便,A地点和B地点的经纬度是固定的,可以随意更改。

最后,执行以下命令,即可在你的手机使用这个app了。

  ionic build ios
  ionic run ios --devise

更多google map api,请看 example