Skip to content

Instantly share code, notes, and snippets.

@elmahdim
Created July 5, 2015 12:03
Show Gist options
  • Save elmahdim/c1a0e467eb1dac17b196 to your computer and use it in GitHub Desktop.
Save elmahdim/c1a0e467eb1dac17b196 to your computer and use it in GitHub Desktop.
Google Maps Geocoding Directive - Angularjs
(function() {
/*
* Google Maps Geocoding Directive - Angularjs
* -----------
* @restrict : 'E' = element, 'A' = attribute
* @example : <google-map class="gmap" id="gmap" zipcode="{{obj.zipcode}}"></google-map>
* @link : https://developers.google.com/maps/documentation/geocoding/
* @version : 1.0
* @author : @ElmahdiMahmoud
*/
'use strict';
angular
.module('app.widgets')
.directive('googleMap', googleMap);
function googleMap() {
var directive = {
restrict: 'EA',
replace: true,
template: '<div />',
scope: {
zipcode: "@"
},
link: linkFunc
};
return directive;
function linkFunc(scope, element, attrs) {
var geocoder,
map;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(-34.397, 150.644);
var mapOptions = {
zoom: 8,
zoomControl: true,
scrollwheel: false,
scaleControl: true,
mapTypeControl: false,
disableDefaultUI: true,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
},
mapStyles = [
{
"featureType": "administrative",
"elementType": "labels.text.fill",
"stylers": [
{ "color": "#737373" }
]
},
{
"featureType": "landscape",
"elementType": "all",
"stylers": [
{ "color": "#f2f2f2" }
]
},
{
"featureType": "poi",
"elementType": "all",
"stylers": [
{ "visibility": "off" }
]
},
{
"featureType": "road",
"elementType": "all",
"stylers": [
{ "saturation": -100 },
{ "lightness": 45 }
]
},
{
"featureType": "road.highway",
"elementType": "all",
"stylers": [
{ "visibility": "simplified" }
]
},
{
"featureType": "road.arterial",
"elementType": "labels.icon",
"stylers": [
{ "visibility": "off" }
]
},
{
"featureType": "transit",
"elementType": "all",
"stylers": [
{ "visibility": "off" }
]
},
{
"featureType": "water",
"elementType": "all",
"stylers": [
{ "color": "#efefef" },
{ "visibility": "on" }
]
}
];
map = new google.maps.Map(document.getElementById(attrs.id), mapOptions);
map.setOptions({styles: mapStyles});
} // end initialize()
function codeAddress(address) {
initialize();
geocoder.geocode({
'address': address
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
} else {
//console.log('Geocode was not successful for the following reason: ' + status);
}
});
} // end codeAddress()
attrs.$observe('zipcode', function(value){
if(value){ codeAddress(value); }
});
} // end linkFunc()
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment