The community behind AngularJS is fantastic. When you’re facing a problem the chance is high that you’ll find a solution on the web. Sometimes you’ll even find a clean Angular directive. And that was the case when I was looking for a solution for combining AngularJS with Google Maps.

There are multiple libraries that integrates the Google Maps API with AngularJS. Some are:

  • Google Maps for AngularJS makes the integration of more advanced features of the Google Maps API (v3) possible. The demo shows what’s possible with this collection of directives.
  • Angular UI Maps is another set of directives that has less advanced possibilities then Google Maps for AngularJS but enough for a basic usage of the Google Maps API.

For the purpose of this simple demo, I’ll use the second library. This one is sufficient for what we need for this demo: display a Google Map based on a text location.

First of all you’ll have to load the Google Maps API. This can be done by adding this script at the bottom of your HTML file (before the closing <body> tag).

1
2
3
4
<script type="text/javascript" src="bower_components/angular/angular.js"></script>
<script type="text/javascript" src="bower_components/angular-ui-utils/modules/event/event.js"></script>
<script type="text/javascript" src="bower_components/angular-ui-map/src/map.js"></script>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&callback=onGoogleReady"></script>

You can also load the API aynchronously if you want, but then make sure to compile the Angular templates with Maps UI directives in it after the Google Maps API has been loaded.

Read more on how to install Angular UI Maps on the GitHub repository, and try to display a hardcoded Google Map with this plugin.

Geocode an address

If you have an address (user input), you’ll have to “geocode” this string to have the GPS coordinates of the given location (longitude & latitude). You can do this easily via Javascript with the Geocodor Google Maps API.

1
2
3
4
5
6
7
var geocoder = new google.maps.Geocoder();
geocoder.geocode( { "address": $scope.textfield }, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK && results.length > 0) {
        var location = results[0].geometry.location;
        $scope.myMap.panTo(location);
    }
});

The above code will geocode the address that the user has filled in ($scope.textfield) and will then pan to the geocoded location ($scope.myMap.panTo(location)).

(see this pen on CodePen.io for a working example)