Published:

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)

 


Subscribe or Follow Me For Updates

Subscribe to my YouTube channel or follow me on Twitter, Facebook or GitHub to be notified when I post new content.

Other than coding...

I'm currently attempting to travel around Australia by motorcycle with my wife Tina on a pair of Royal Enfield Himalayans. You can follow our adventures on YouTube, Instagram and Facebook.


Need Some AngularJS Help?

Search fiverr to find help quickly from experienced AngularJS developers.



Supported by