Published: February 15 2014

AngularJS - Reverse Geocoding Directive

This is a little custom AngularJS directive that converts GPS coordinates (latitude/longitude) into an address, otherwise known as reverse geocoding, using the Google Maps API.

Here it is in action: (See on Plunker at https://plnkr.co/edit/n67DFe?p=preview)

Installation

  • Install using Bower: bower install angular-reverse-geocode
  • Or download the code from GitHub and include the angular-reverse-geocode.js file in your page, it's available on GitHub at https://github.com/cornflourblue/angular-reverse-geocode
  • Or copy the AngularJS Directive Code below and add to your application

Add the 'angularReverseGeocode' directive as a dependency of your AngularJS application:

angular.module('myApp', ['angularReverseGeocode']);

 

Usage

To display the physical address / location of GPS coordinates, add the reverse-geocode tag to your AngularJS view with attributes containing lat and long coordinates, e.g:

<reverse-geocode lat="40.730885" lng="-73.997383" />

If the GPS coordinates are coming from scope variables set in your AngularJS controller you need to use curly-brace expression bindings, e.g:

<reverse-geocode lat="{{model.latitude}}" lng="{{model.longitude}}" />

 

AngularJS Directive Code

angular.module('[YourAppName]', [])
    .directive('reverseGeocode', function () {
        return {
            restrict: 'E',
            template: '<div></div>',
            link: function (scope, element, attrs) {
                var geocoder = new google.maps.Geocoder();
                var latlng = new google.maps.LatLng(attrs.lat, attrs.lng);
                geocoder.geocode({ 'latLng': latlng }, function (results, status) {
                    if (status == google.maps.GeocoderStatus.OK) {
                        if (results[1]) {
                            element.text(results[1].formatted_address);
                        } else {
                            element.text('Location not found');
                        }
                    } else {
                        element.text('Geocoder failed due to: ' + status);
                    }
                });
            },
            replace: true
        }
    });

 

Directive Dependencies

To get this custom angular directive working you'll need to include the google maps api script (//maps.googleapis.com/maps/api/js?v=3.exp&sensor=false) and of course the angularjs script (//ajax.googleapis.com/ajax/libs/angularjs/1.2.12/angular.min.js)

 


Need Some AngularJS Help?

Search fiverr for freelance AngularJS developers.


Follow me for updates

On Twitter or RSS.


When I'm not coding...

Me and Tina are on a motorcycle adventure around Australia.
Come along for the ride!


Comments


Supported by