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 (https://developers.google.com)

<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=YOUR-API-KEY">

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

'use strict';
angular.module('MY_APP_NAME')
    .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
	            if(attrs.postcode){
		            geocoder.geocode({'address': attrs.postcode}, function(results, status){
			            if(status == google.maps.GeocoderStatus.OK){
				            renderMap({lat: results[0].geometry.location.lat(), lng: results[0].geometry.location.lng()})
			            }
		            });
	            }else{
		            renderMap(attrs.position);
	            }

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

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

		            var marker = new google.maps.Marker({
			            position: mapOptions.center,
			            map: map
		            });
	            }
            }
        };
    });

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

.gmap{
	height:400px;
	width:100%;
}

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

or

<google-map position="{lat: pos.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.