Skip to content

Instantly share code, notes, and snippets.

@wholypantalones
Last active October 31, 2015 16:53
Show Gist options
  • Select an option

  • Save wholypantalones/09a302e7bcc10069ece9 to your computer and use it in GitHub Desktop.

Select an option

Save wholypantalones/09a302e7bcc10069ece9 to your computer and use it in GitHub Desktop.
Angular Google Places AutoComplete
/* Usage:
<input type="text" id="address" name="address" placeholder="Start Typing An Address" ng-model="address" details="placeDetails" googleplace />
Fiddle: http://jsfiddle.net/wholypantalones/5qtt1f8g/
*/
//controller
$scope.$watch('placeDetails', function() {
angular.forEach($scope.placeDetails.address_components,function(val,key) {
if(val.types[0] == "locality") {
$scope.city = val.short_name;
}
if(val.types[0] == "administrative_area_level_1") {
$scope.stateProv = val.short_name;
}
}); // use place details
if($scope.placeDetails.geometry) {
$scope.latitude = $scope.placeDetails.geometry.location.lat();
$scope.longitude = $scope.placeDetails.geometry.location.lng();
}
});
//directive
app.directive('googleplace', function () {
return {
require: 'ngModel',
scope: {
ngModel: '=',
details: '=?'
},
link: function (scope, element, attrs, model) {
var options = {
types: ['address'],
componentRestrictions: {}
};
scope.gPlace = new google.maps.places.Autocomplete(element[0], options);
google.maps.event.addListener(scope.gPlace, 'place_changed', function () {
scope.$apply(function () {
scope.details = scope.gPlace.getPlace();
if(scope.details.name){
element.val(scope.details.name);
model.$setViewValue(scope.details.name);
element.bind('blur', function (value) {
if(value.currentTarget.value !== "") {
element.val(scope.details.name);
} // make sure the model value isn't blank
}); // this keeps the input value instead of replaceing it with the places complete address
}
});
});
}
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment