Saturday, October 22, 2016

[IONIC] Using Google Maps in Ionic App

In upcoming multi-series part, I'll write about how to create an ionic app with google maps. In this 1st part, I'll write about the basic of getting Google Map into app ionic app.

Prerequisites

  • Basic ionic knowledge.
  • Basic angular V1 knowledge.
  • Sass knowledge.
Now that we've get this out of the way, let's get this started.

 

Let's start with the finished product

Let's cut to the chase and show the finished product. Below is the all the codes, which I've post to CodePen. It's a basic app which just shows google map with a text box and a button.

See the Pen Ionic Google Map by Old School Koder (@oldschoolcoder) on CodePen.

Google Map Javascript

Add this into index.html. After cordova.js but before app.js. For production use, you may need to get the API key from google. Check out here on how to get the api key. However if you just want to test it out you can omit the param. It's optional to include async defer.



The Template

It's a simple template with a placeholder for the map, a text box and a button. For beginner, I highly recommend that you check out ionic creator. I find it the easiest way to setup an ionic project even if you are just using the free tier.


    
        

There are two non-ionic CSS classes which is top-container and bottom-form. You can add those to ionic.app.scss file.
.bottom-form {
  position: absolute;
  bottom: 0px;
  display: block;
  width: 100%;
  background-color: white;
  button {
    margin: 0px !important;
  }
}

.top-container {
  height: calc(100% - 96px);
  overflow: hidden;
}

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

That's all for the template. Let's check out the javascipts codes where the magic happens.


The Controller

It's pretty simple and straight forward. Create a mapOptions Object and pass in to the Map object. You can check out all the possible options on Google's Developer Page.
  .controller('locationCtrl', function($scope, $state) {
    var mapOptions = {
      disableDefaultUI: true,
      center: new google.maps.LatLng(40.8091926, -73.9586085),
      zoom: 15,
      mapTypeId: google.maps.MapTypeId.ROADMAP,
      zoomControl: true,
      zoomControlOptions: {
        style: google.maps.ZoomControlStyle.LARGE
      }

    }

    $scope.map = new google.maps.Map(document.getElementById("map"), mapOptions);

  })


That's it. Pretty simple and straight forward. In the next blog post, I'll write about some other feature that I find useful to add into an app. Stay tune and happy coding

1 comment: