angular.module('myApp', [])
.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
}
});
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<meta charset="utf-8" />
<title>AngularJS Reverse Geocoding Directive</title>
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" />
<script src="//maps.googleapis.com/maps/api/js?v=3.exp"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.17/angular.min.js"></script>
<script src="app.js"></script>
</head>
<body>
<div class="jumbotron">
<h1>
<reverse-geocode lat="40.730885" lng="-73.997383"></reverse-geocode>
</h1>
</div>
<div class="credits text-center">
<p>
<a href="http://jasonwatmore.com/post/2014/02/15/AngularJS-Reverse-Geocoding-Directive.aspx">AngularJS reverse geocoding directive</a>
</p>
<p>
<a href="http://jasonwatmore.com">jasonwatmore.com</a>
</p>
</div>
</body>
</html>