Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Easy AngularJS Directive for Google Places Autocomplete
var myApp = angular.module('myApp', []);
myApp.directive('googleplace', function() {
return {
require: 'ngModel',
link: function(scope, element, attrs, model) {
var options = {
types: [],
componentRestrictions: {}
};
scope.gPlace = new google.maps.places.Autocomplete(element[0], options);
google.maps.event.addListener(scope.gPlace, 'place_changed', function() {
scope.$apply(function() {
model.$setViewValue(element.val());
});
});
}
};
});
//myApp.factory('myService', function() {});
function MyCtrl($scope) {
$scope.gPlace;
}
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?libraries=places&sensor=false"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
<div>Google Places Autocomplte integration in Angular</div>
<div>To Test, start typing the name of any Indian city</div>
<div>selection is: {{chosenPlace}}</div>
<div><input ng-model="chosenPlace" googleplace/></div>
</div>
@erea

This comment has been minimized.

Copy link

@erea erea commented Jul 19, 2014

Will this also return place data like name, address, phone, openNow, etc?

@asankaumesh

This comment has been minimized.

Copy link

@asankaumesh asankaumesh commented Sep 16, 2014

awesome work man :)

@CaudronAnthony

This comment has been minimized.

Copy link

@CaudronAnthony CaudronAnthony commented Sep 23, 2014

Nice work

@kirschbaum

This comment has been minimized.

Copy link

@kirschbaum kirschbaum commented Sep 28, 2014

@erea - check out this fork: http://goo.gl/2ouIR0. This would allow you to define a separate scope model where the detailed results of the google response will be stored. You can then further process them, either in this directive or in your controller.

@rioll

This comment has been minimized.

Copy link

@rioll rioll commented May 18, 2015

HI, with the same code I have this issue :
Uncaught TypeError: a[wG] is not a function
do you know why ?

@zakariaDM

This comment has been minimized.

Copy link

@zakariaDM zakariaDM commented Jun 19, 2015

Perfect thanks

@wallawe

This comment has been minimized.

Copy link

@wallawe wallawe commented Jul 2, 2015

Thanks for this! I expanded the use for cities to grab the city, state, country, lat and long as well. Here it is in case anyone is looking for the same:
edit: as @svdgraaf pointed out, use lat() and lng()

angular.module('app').directive('googleplace', [ function() {
    return {
        require: 'ngModel',
        scope: {
            ngModel: '=',
            details: '=?'
        },
        link: function(scope, element, attrs, model) {
            var options = {
                types: ['(cities)'],
                componentRestrictions: {}
            };

            scope.gPlace = new google.maps.places.Autocomplete(element[0], options);

            google.maps.event.addListener(scope.gPlace, 'place_changed', function() {
                var geoComponents = scope.gPlace.getPlace();
                var latitude = geoComponents.geometry.location.lat();
                var longitude = geoComponents.geometry.location.lng();
                var addressComponents = geoComponents.address_components;

                addressComponents = addressComponents.filter(function(component){
                    switch (component.types[0]) {
                        case "locality": // city
                            return true;
                        case "administrative_area_level_1": // state
                            return true;
                        case "country": // country
                            return true;
                        default:
                            return false;
                    }
                }).map(function(obj) {
                    return obj.long_name;
                });

                addressComponents.push(latitude, longitude);

                scope.$apply(function() {
                    scope.details = addressComponents; // array containing each location component
                    model.$setViewValue(element.val());
                });
            });
        }
    };
}]);
@svdgraaf

This comment has been minimized.

Copy link

@svdgraaf svdgraaf commented Jul 6, 2015

@wallawe: awsome! I would recommend changing:

var latitude = geoComponents.geometry.location.A;
var longitude = geoComponents.geometry.location.F

into

var latitude = geoComponents.geometry.location.lat();
var longitude = geoComponents.geometry.location.lng();

As the the letters will change every new build by Google.

@FDIM

This comment has been minimized.

Copy link

@FDIM FDIM commented Jul 24, 2015

Thanks guys, it was a good starting point, but I am not too fond of structure in the details, so I refactored a bit to get this:

{
   street:'',
   number:'',
   city:'',
   zip:'',
   country:'',
   latitude:'',
   longitude:'',
   formatted:'',
   placeId:''
}

If someone else is looking for a complete directive, you can use mine. It will also load maps api if needed.

/**
 * Each module has a <moduleName>.module.js file.  This file contains the angular module declaration -
 * angular.module("moduleName", []);
 * The build system ensures that all the *.module.js files get included prior to any other .js files, which
 * ensures that all module declarations occur before any module references.
 */
(function (module) {
    var mapsLoaded = false;
    var pending = [];
    module.run(function ($window) {
        if (!mapsLoaded || !$window.google || !window.google.maps || !window.google.maps.places) {
            //http://maps.googleapis.com/maps/api/js?v=3.exp&libraries=places&sensor=false&callback=googleMapsLoaded
            $window.googleMapsLoaded = function () {
                delete $window.googleMapsLoaded;
                mapsLoaded = true;
            };
            var script = document.createElement('script');
            script.type = 'text/javascript';
            script.src = 'https://maps.googleapis.com/maps/api/js?v=3.exp&libraries=places&sensor=false&callback=googleMapsLoaded&language=en';
            document.body.appendChild(script);
        }
    });
    module.directive('googlePlace', function () {
        var componentForm = {
            street_number: 'short_name',
            route: 'long_name',
            locality: 'long_name',
            administrative_area_level_1: 'short_name',
            country: 'long_name',
            postal_code: 'short_name'
        };
        var mapping = {
            street_number: 'number',
            route: 'street',
            locality: 'city',
            administrative_area_level_1: 'state',
            country: 'country',
            postal_code: 'zip'
        };
        // https://gist.github.com/VictorBjelkholm/6687484 
        // modified to have better structure for details
        return {
            require: 'ngModel',
            scope: {
                ngModel: '=',
                details: '=?'
            },
            link: function (scope, element, attrs, model) {
                var options = {
                    types: attrs.googlePlace !== "" ? attrs.googlePlace.split(',') : [],
                    componentRestrictions: {}
                };

                scope.gPlace = new google.maps.places.Autocomplete(element[0], options);

                google.maps.event.addListener(scope.gPlace, 'place_changed', function () {
                    var place = scope.gPlace.getPlace();
                    var details = place.geometry && place.geometry.location ? {
                        latitude: place.geometry.location.lat(),
                        longitude: place.geometry.location.lng()
                    } : {};
                    // Get each component of the address from the place details
                    // and fill the corresponding field on the form.
                    for (var i = 0; i < place.address_components.length; i++) {
                        var addressType = place.address_components[i].types[0];
                        if (componentForm[addressType]) {
                            var val = place.address_components[i][componentForm[addressType]];
                            details[mapping[addressType]] = val;
                        }
                    }
                    details.formatted = place.formatted_address;
                    details.placeId = place.place_id;
                    scope.$apply(function () {
                        scope.details = details; // array containing each location component
                        model.$setViewValue(element.val());
                    });
                });
            }
        };
    });
    // The name of the module, followed by its dependencies (at the bottom to facilitate enclosure)
}(angular.module("google.places", [])));
@FDIM

This comment has been minimized.

Copy link

@FDIM FDIM commented Jul 24, 2015

oh... and some less if you want to get rid of placeholder: (I do as I am using angular material)

input[google-place]::-webkit-input-placeholder {
    opacity: 0;
}

input[google-place]:-moz-placeholder {
    /* Firefox 18- */

    opacity: 0;
}

input[google-place]::-moz-placeholder {
    /* Firefox 19+ */

    opacity: 0;
}

input[google-place]:-ms-input-placeholder {
    opacity: 0;
}
@lubiluk

This comment has been minimized.

Copy link

@lubiluk lubiluk commented Aug 7, 2015

Here's my iteration on this. It performs a cleanup on the '$destroy' event and hides gPlace from the $scope.

.directive('googleplaceAutocomplete', function () {
    return {
      restrict: 'A',
      require: 'ngModel',
      scope: {
        googleplaceAutocompletePlace: '=?',
        googleplaceAutocomplete: '=',
      },
      link: function postLink(scope, element, attrs, model) {
        var options = scope.googleplaceAutocomplete;
        var autocomplete = new google.maps.places.Autocomplete(element[0], options);

        google.maps.event.addListener(autocomplete, 'place_changed', function () {
          scope.$apply(function () {
            scope.googleplaceAutocompletePlace = autocomplete.getPlace();
            model.$setViewValue(element.val());
          });
        });

        scope.$on('$destroy', function () {
          google.maps.event.clearInstanceListeners(element[0]);
        });
      }
    };
  });

Also here: https://gist.github.com/lubiluk/7f3a187041e6797aefb1

@IvanStone

This comment has been minimized.

Copy link

@IvanStone IvanStone commented Aug 19, 2015

I thought I would add my update to the convo. Thanks for all your help guys.

var googlePlacesDirective = function() {
  var componentForm = {
        premise: 'long_name',
        street_number: 'short_name',
        route: 'long_name',
        sublocality_level_1: 'long_name',
        locality: 'long_name',
        administrative_area_level_1: 'short_name',
        country: 'long_name',
        postal_code: 'short_name'
    };
    var mapping = {
        premise: 'BuildingName',
        street_number: 'Unit',
        route: 'Street',
        sublocality_level_1: 'Suburb',
        locality: 'City',
        administrative_area_level_1: 'State',
        country: 'Country',
        postal_code: 'PostCode'
        //Region, District, Level
    };

  return {
    require: 'ngModel',
    restrict: 'E',
    replace: true,
    // transclude:true,
    scope: {
      ngModel: '=',
      address: '=?'
    },
    template: '<input id="google_places_ac" name="google_places_ac" type="text" class="input-block-level"/>',
    link: function(scope, element, attrs, model) {

      var options = {
        // componentRestrictions: { country: 'nz' },
        types: ['geocode']
      };

      var autocomplete = new google.maps.places.Autocomplete($("#google_places_ac")[0], options);

      google.maps.event.addListener(autocomplete, 'place_changed', function() {
        var place = autocomplete.getPlace();
        var location = place.geometry && place.geometry.location ? {
            Latitude: place.geometry.location.lat(),
            Longitude: place.geometry.location.lng()
        } : {};

        // Get each component of the address from the place location
        // and fill the corresponding field on the form.
        for (var i = 0; i < place.address_components.length; i++) {
            var addressType = place.address_components[i].types[0];
            if (componentForm[addressType]) {
                var val = place.address_components[i][componentForm[addressType]];
                location[mapping[addressType]] = val;
            }
        }
        location.FormattedAddress = place.formatted_address;
        location.PlaceId = place.place_id;

        scope.$apply(function () {
            scope.address = location; // array containing each location component
            model.$setViewValue(location);
            element.val(location[attrs.value]);
            // console.log(model);
        });
      });
    }
  };
};

module.exports = function(appName) {
  angular.module(appName)
    .directive('googlePlaces', [googlePlacesDirective]) ;

html

<google-places address=address ng-model="address.Street" required="" class="form-control" placeholder="Street" value="Street"/>
@tapan-p

This comment has been minimized.

Copy link

@tapan-p tapan-p commented Sep 23, 2015

I am not sure what exactly I am missing here but i tried modifying the code little bit as below and it is not displaying any data. Can someone please help?

<! DOCTYPE html>
<html> 
<head>

<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?libraries=places&sensor=false"></script>
</head>
<body>
<script type="text/javascript" src="angular.min.js"></script>
<script type="text/javascript" src="app.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
    <div>Google Places Autocomplte integration in Angular</div>
    <div>To Test, start typing the name of any Indian city</div>
    <div>selection is: {{chosenPlace}}</div>
    <div><input ng-model="chosenPlace" googleplace/></div>
</div>
</body>
</html>
@ghost

This comment has been minimized.

Copy link

@ghost ghost commented Oct 1, 2015

Every time the directive is used, google injects a css (inside head).
If the user remains in the website and visited this component several time, he will have several injected css.
Anyone found a solution for this ? is possible to avoid the CSS injection ?
Thanks

@chaitz24

This comment has been minimized.

Copy link

@chaitz24 chaitz24 commented Oct 17, 2015

Thanks it worked smooth.

@medindm

This comment has been minimized.

Copy link

@medindm medindm commented Nov 3, 2015

Thanks @FDIM! Great help!

@hussaino

This comment has been minimized.

Copy link

@hussaino hussaino commented Dec 28, 2015

Wow, thanks a bunch :)

@gadjetboi

This comment has been minimized.

Copy link

@gadjetboi gadjetboi commented Dec 31, 2015

awesome. thanks man.

@kpnigalye

This comment has been minimized.

Copy link

@kpnigalye kpnigalye commented Feb 5, 2016

Thanks @wallawe that was really helpful. Also I replaced 'cities' with 'geocode' in options to get other information.
var options = { types: ['geocode'] };

@vkilmore

This comment has been minimized.

Copy link

@vkilmore vkilmore commented Feb 7, 2016

This is a great directive, I have a question though, when I click on the dropdown list to select one of the suggestions it appears that the dropdown does take the click and instead whatever is behind the dropdown gets selected. Any ideas?

@stormdragon

This comment has been minimized.

Copy link

@stormdragon stormdragon commented Feb 22, 2016

Thanks @FDIM!
I have got Great help!
Then, i have a problem on mobile. i cant click the dropdown items. Do you have any good idea?

@bialesdaniel

This comment has been minimized.

Copy link

@bialesdaniel bialesdaniel commented Mar 22, 2016

I have the same issue as @stormdragon. Any suggestions?

@apapatp

This comment has been minimized.

Copy link

@apapatp apapatp commented Mar 29, 2016

Dude awesome sauce!!

@udarapathmin

This comment has been minimized.

Copy link

@udarapathmin udarapathmin commented Mar 30, 2016

Awesome work..Thanks

@japharr

This comment has been minimized.

Copy link

@japharr japharr commented May 26, 2016

Thanks @IvanStone

@NateJBeck

This comment has been minimized.

Copy link

@NateJBeck NateJBeck commented Jul 13, 2016

Awesome job! I use this in many forms to set important address info after address selection - no parsing required - might be useful if you want to do the same:

<myApp-google-autocomplete ng-model="fullAddress" zip="vm.model.zipcode"
    country="vm.model.country" state="vm.model.state" city="vm.model.city"
    address1="vm.model.address_1">
</myApp-google-autocomplete>

.directive('myAppGoogleAutocomplete', function() {
    return {
        require: 'ngModel',
        replace: true,
        scope: {
            ngModel: '=',
            address1: "=",
            city: "=",
            state: "=",
            country: "=",
            zip: '=',
        },
        template: '<input class="form-control" type="text">',
        link: function(scope, element, attrs, model) {
            var options = {
                types: [],
                componentRestrictions: {}
            };    

            var autocomplete = new google.maps.places.Autocomplete(element[0], options);

            google.maps.event.addListener(autocomplete, 'place_changed', function() {
                scope.$apply(function() {
                    var place = autocomplete.getPlace();
                    var components = place.address_components;  // from Google API place object   

                    scope.address1 = components[0].short_name + " " + components[1].short_name;
                    scope.city = components[3].short_name;
                    scope.state = components[5].short_name;
                    scope.country = components[6].long_name;
                    scope.zip = components[7].short_name;

                    model.$setViewValue(element.val());   
                });
            });
        }
    }
})
@code-storm

This comment has been minimized.

Copy link

@code-storm code-storm commented Aug 10, 2016

You saved the day.
<pre>Thanks</pre>

@nirajbothra

This comment has been minimized.

Copy link

@nirajbothra nirajbothra commented Aug 17, 2016

the original solution worked like a charm..

Thanks

@Henryisthebest

This comment has been minimized.

Copy link

@Henryisthebest Henryisthebest commented Sep 3, 2016

Hi,
I'm using ionic - and I am trying to pass the lat long to a function when I click a button on the page. How do I access the lat long? my ng-model variable is 'chosenPlace', and in my controller I have defined $scope.chosenPlace, however when I try retrieve the value it is undefined?

@exaland

This comment has been minimized.

Copy link

@exaland exaland commented Oct 19, 2016

Hi , Please help me i want use this script with 2 Input text box -> Pickup Location and Destination

here my script :

angular.module('app.directives', [])
.directive('googleplace', function() {
    return {
        require : 'ngModel',
        link : function(scope, element, attrs, model) {
            var options = {
                types :  [],
                 componentRestrictions: {country: "fr"}

            };
            scope.gPlace = new google.maps.places.Autocomplete(element[0],
                    options);

            google.maps.event.addListener(scope.gPlace, 'place_changed',
                    function() {
                          var geoComponents = scope.gPlace.getPlace();
                            var latitude = geoComponents.geometry.location.lat();
                        var longitude = geoComponents.geometry.location.lng();
                        var addressComponents = geoComponents.address_components;
                        scope.$apply(function() {
                            model.$setViewValue(element.val());
                            console.log(element.val());
                            console.log("Latitude : "  + latitude +"  Longitude : " + longitude);
                        });
                    });
        }

    };

})

thanks for ur help

@degaray

This comment has been minimized.

Copy link

@degaray degaray commented Mar 14, 2017

I am trying to add this directive into an ionic project and use it for two different fields: from, to. It works great with from, but if I start writing from, then delete it, type it again and select it, 'to' becomes un selectable. Any ideas how I can make it work?

@mukeshshahi

This comment has been minimized.

Copy link

@mukeshshahi mukeshshahi commented Mar 17, 2017

hi please suggest how to select multiple location

@Teaumate

This comment has been minimized.

Copy link

@Teaumate Teaumate commented Apr 26, 2017

added google sample code in order to implement proximity autocomplete.

            // Bias the autocomplete object to the user's geographical location,
            // as supplied by the browser's 'navigator.geolocation' object.
            if (navigator.geolocation) {
                navigator.geolocation.getCurrentPosition(function(position) {
                    var geolocation = {
                        lat: position.coords.latitude,
                        lng: position.coords.longitude
                    };
                    var circle = new google.maps.Circle({
                        center: geolocation,
                        radius: position.coords.accuracy
                    });
                    scope.gPlace.setBounds(circle.getBounds());
                });
            }
            scope.gPlace = new google.maps.places.Autocomplete(element[0], options);
@droidthings

This comment has been minimized.

Copy link

@droidthings droidthings commented May 12, 2017

Hi i am trying to implement this in ionic project, selection from the dropdown works fine on android devices, but on ios devices the dropdown values are un selectable, any ideas how to make it work ? or are there any other directives which i can use in an ionic project ?.

@gpcaretti

This comment has been minimized.

Copy link

@gpcaretti gpcaretti commented May 31, 2017

This is my improve of the solution from @NateJBeck.

Improvements:

  1. aggreated returned value into a unique json
  2. Enforced the research of zip, city, etc. (see $scope.extract)
  3. Added long. e lat.
  4. added a callback on found place
<my-google-autocomplete id="address" name="address"
			ng-model="vm.formValues.address"
			google-model="vm.formValues.googleAddress"
			on-select="vm.onSelectGoogleAddress($item)"
			autocomplete="off"
			required>
</my-google-autocomplete>

The directive:

angular.module('google-place-autocomplete', [])	// Gp renamed and add []
.directive('myGoogleAutocomplete', function () {
	return {
		replace: true,
		require: 'ngModel',
		scope: {
			ngModel: '=',
			googleModel: '=',
			onSelect: '&?',	// optional callback on selected successfully: 'onPostedBid(googleModel)'
		},
		template: '<input class="form-control" type="text" autocomplete="off">',
		link: function ($scope, element, attrs, model) {
			var googleOptions = {
				types: ['address'],  // change or empty it, if you want no restrictions 
				componentRestrictions: { country: 'it' }  // change or empty it, if you want no restrictions
			};

			var autocomplete = new google.maps.places.Autocomplete(element[0], googleOptions);

			google.maps.event.addListener(autocomplete, 'place_changed', function () {

				/**
				 * Search gor the passed 'type' of info into the google place component
				 * @param {type} components
				 * @param {type} type
				 * @returns {type} 
				 */
				$scope.extract = function (components, type) {
					for (var i = 0; i < components.length; i++)
						for (var j = 0; j < components[i].types.length; j++)
							if (components[i].types[j] == type) return components[i].short_name;
					return '';
				};


				$scope.$apply(function () {
					var place = autocomplete.getPlace();
					if (!place.geometry) {
						// User entered the name of a Place that was not suggested and pressed the Enter key, or the Place Details request failed.
						model.$setValidity('place', false);
						//console.log("No details available for input: '" + place.name + "'");
						return;
					}

					$scope.googleModel = {};
					$scope.googleModel.placeId = place.place_id;
					$scope.googleModel.latitude = place.geometry.location.lat();
					$scope.googleModel.longitude = place.geometry.location.lng();
					$scope.googleModel.formattedAddress = place.formatted_address;
					if (place.address_components) {
						$scope.googleModel.address = [
							$scope.extract(place.address_components, 'route'),
							$scope.extract(place.address_components, 'street_number')
						].join(' ');
						$scope.googleModel.cityName = $scope.extract(place.address_components, 'locality');
						$scope.googleModel.provName = $scope.extract(place.address_components, 'administrative_area_level_2');
						$scope.googleModel.regionName = $scope.extract(place.address_components, 'administrative_area_level_1');
						$scope.googleModel.zipCodeId = $scope.extract(place.address_components, 'postal_code');
						$scope.googleModel.countryCode = $scope.extract(place.address_components, 'country');
					}

					model.$setViewValue(element.val());
					model.$setValidity('place', true);
					if (attrs.onSelect) $scope.onSelect({ $item: $scope.googleModel });
				});
			});
		}
	}
});
@fractalocity

This comment has been minimized.

Copy link

@fractalocity fractalocity commented Jun 30, 2017

I don't think the code in this project is valid any longer.
the following page seems to work and has a plunker example
https://github.com/vskosp/vsGoogleAutocomplete
http://plnkr.co/edit/sdcIaQ?p=preview

@yogesh61990

This comment has been minimized.

Copy link

@yogesh61990 yogesh61990 commented Aug 1, 2017

i am trying to same code but grtting angular.js:14525 Error: [$controller:ctrlreg] error .

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script> <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?libraries=places&key=api-key"></script> <script src="app.js"></script>
<div>Google Places Autocomplte integration in Angular</div>

<div>To Test, start typing the name of any Indian city</div>

<div>selection is: {{chosenPlace}}</div>

<div><input ng-model="chosenPlace" googleplace/></div>
@usman10scorpio

This comment has been minimized.

Copy link

@usman10scorpio usman10scorpio commented Sep 7, 2017

How can I use make this directive useful if i have multiple middle points in ionic ?

This is my code

<label class="item item-input">
          <input type="text" id="location" placeholder="Your Currunt Location" ng-model="location.address" googleplace="" class="ng-pristine ng-valid" autocomplete="on"><!-- googleplace -->
       </label>
     <label class="item item-input">
          <input type="text" id="middle" placeholder="Pick up point" ng-model="middle.address" googleplace="" class="ng-pristine ng-valid" autocomplete="on"><!-- googleplace -->
       </label>
     <label class="item item-input">
          <input type="text" id="end" placeholder="Exit point" ng-model="end.address" googleplace="" class="ng-pristine ng-valid" autocomplete="on"><!-- googleplace -->
       </label>

what if i have multiple middle points and i am making a route between them? How would i do that ?

@Dhaval4241

This comment has been minimized.

Copy link

@Dhaval4241 Dhaval4241 commented Oct 2, 2017

when i am using this directive i getting error ReferenceError: google is not defined please give solution for that

@baruchvlz

This comment has been minimized.

Copy link

@baruchvlz baruchvlz commented Oct 18, 2017

@Dhaval4241 You need to add the Google script to your index.html

<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?key={YOUR_API_KEY}&libraries=places&sensor=false"></script>

google should now be avaiable in the window scope.

@bindi11

This comment has been minimized.

Copy link

@bindi11 bindi11 commented Mar 30, 2018

Helped me a lot. Thanks!

Can you help me out in binding places for specific 1 city only?

My current directive code is,

angular.module('testApp').directive('googlePlace', function () {
       return {
           require: 'ngModel',
           link: function (scope, element, attrs, model) {

               var southWest = new google.maps.LatLng(36.970298, -87.01993499999998);
               var northEast = new google.maps.LatLng(42.5083379, -91.51307889999998);

               var SyracruiseBounds = new google.maps.LatLngBounds(southWest, northEast);

              var options = {
                   bounds: SyracruiseBounds,
                   types: ['address']
               };
               scope.gPlace = new google.maps.places.Autocomplete(element[0], options);
               scope.gPlace.bindTo('bounds', map);
               scope.gPlace.setOptions({ strictBounds: true });

               google.maps.event.addListener(scope.gPlace, 'place_changed', function () {

                   var geoComponents = scope.gPlace.getPlace();

                   var latitude = geoComponents.geometry.location.lat();
                   var longitude = geoComponents.geometry.location.lng();
                   var addressComponents = geoComponents.address_components;

                   addressComponents = addressComponents.filter(function (component) {
                       switch (component.types[0].locality) {
                           case "Syracruse": // city
                               return true;
                           default:
                               return false;
                       }
                   }).map(function (obj) {
                       return obj.long_name;
                   });

                   addressComponents.push(latitude, longitude);

                   scope.$apply(function () {
                       scope.details = addressComponents; // array containing each location component
                       model.$setViewValue(element.val());
                   });
               });
          }
       };
   });
@sarangpat

This comment has been minimized.

Copy link

@sarangpat sarangpat commented Jun 15, 2018

Hi, this helped me a lot. Thank you for sharing this. Just to get some more information on this, is it possible that using this directive, i can have two places in a form which has this directive defined? I tried attaching this directive to two input elements and it only works for one. Anything on this would be a great help. Thanks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment