Skip to content

Commit

Permalink
feat(autocomplete): handle async loading of google maps API
Browse files Browse the repository at this point in the history
  • Loading branch information
mebibou committed Apr 4, 2016
1 parent b916c7b commit 807b379
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 6 deletions.
2 changes: 1 addition & 1 deletion dist/autocomplete.min.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

20 changes: 15 additions & 5 deletions src/autocomplete.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,9 @@ angular.module('google.places', [])
* Note: requires the Google Places API to already be loaded on the page.
*/
.factory('googlePlacesApi', ['$window', function ($window) {
if (!$window.google) throw 'Global `google` var missing. Did you forget to include the places API script?';
if (!$window.google) {
console.info('Global `google` var missing. Did you forget to include the places API script?');
}

return $window.google;
}])
Expand Down Expand Up @@ -48,8 +50,8 @@ angular.module('google.places', [])
down: 40
},
hotkeys = [keymap.tab, keymap.enter, keymap.esc, keymap.up, keymap.down],
autocompleteService = new google.maps.places.AutocompleteService(),
placesService = new google.maps.places.PlacesService(element[0]);
_autocompleteService = null,
_placesService = null;

(function init() {
$scope.query = '';
Expand All @@ -62,6 +64,14 @@ angular.module('google.places', [])
initNgModelController();
}());

function autocompleteService() {
return _autocompleteService || new google.maps.places.AutocompleteService();
}

function placesService() {
return _placesService || new google.maps.places.PlacesService(element[0]);
}

function initEvents() {
element.bind('keydown', onKeydown);
element.bind('blur', onBlur);
Expand Down Expand Up @@ -164,7 +174,7 @@ angular.module('google.places', [])
});
});
} else {
placesService.getDetails({ placeId: prediction.place_id }, function (place, status) {
placesService().getDetails({ placeId: prediction.place_id }, function (place, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
$scope.$apply(function () {
$scope.model = place;
Expand All @@ -188,7 +198,7 @@ angular.module('google.places', [])
$scope.query = viewValue;

request = angular.extend({ input: viewValue }, $scope.options);
autocompleteService.getPlacePredictions(request, function (predictions, status) {
autocompleteService().getPlacePredictions(request, function (predictions, status) {
$scope.$apply(function () {
var customPlacePredictions;

Expand Down

0 comments on commit 807b379

Please sign in to comment.