Create an AngularJS Google Maps directive

It is really easy to create a Google Maps directive for AngularJS. In this post I’ll show how to create a Google Maps directive that shows a map containing a few markers. If you have no idea what directives are, I suggest to read this page.


I have used JSFiddle to create an example. As you can see the link() function initializes the map together with some markers with info windows:

The main drawback of this code example are the hard-coded markers. It’s a lot nicer when these values are fetched from the controller as a json object. To make things more complicated, this json object can be dynamically updated by the controller using a HTTP call to an API. Luckily we can use the $watch() function (which is part of the scope) of AngularJS in this situation.

The following code is used in the link() function in the JSFiddle example. If you want to use this code you can replace the initMap(); and the hard-coded markers at the end of the link() function (from line 50). In this code-snippet the myLocations variable (which is an array of json objects) of the controller using this directive is watched.


Leave a Reply

Your email address will not be published. Required fields are marked *