AngularJs Google Maps Directive

Google maps directive that supports both postcode and longitude/latitude

Posted on March 31, 2016

Here’s a simple Google Maps directive using Google’s Geocoding API so that you can pass either a postcode or explicit longitude and latitude to a Google Map.

First things first – You’ll need to include the Google Maps api code and don’t forget to add your Google Maps API Key (

<script type="text/javascript" src="">

Create and include the directive. You’ll need to updated MY_APP_NAME with your app’s name.

'use strict';
    .directive('googleMap', function () {
        return {
            template: '<div id="map" class="gmap"></div>',
            restrict: 'E',
            link: function postLink(scope, element, attrs){

	            var geocoder = new google.maps.Geocoder();

	            // Get longitude and latitude values from Google and render the map, or use longitude and latitude from position attribute
		            geocoder.geocode({'address': attrs.postcode}, function(results, status){
			            if(status == google.maps.GeocoderStatus.OK){
				            renderMap({lat: results[0], lng: results[0].geometry.location.lng()})

	            function renderMap(pos){
		            var mapOptions = {
			            zoom: 10,
			            center: {lat:, lng: pos.lng}

		            var map = new google.maps.Map(document.getElementById('map'), mapOptions);

		            var marker = new google.maps.Marker({
			            map: map

Add some basic styling. You’ll need to add a height or the map won’t show.


You can then include the Google Map within your app using the following element code. If you pass both a postcode and Lng/Lat then the postcode will take precedence.

<google-map postcode="{{thePostcode}}" ng-if="thePostcode">


<google-map position="{lat:, lng: pos.lng}" ng-if="pos">

You’ll notice that I’ve also added the ng-if directive. This is to make sure that the postcode or position data has resolved before rendering the Google Map directive.