directive.js 2.77 KB
(function(angular) {
    var app = angular.module('batmanDelivers');
    app.directive("addressSearch", addressSearch);
    addressSearch.$inject = ['$parse', '$rootScope', '$http', '$timeout', '$sce']

    function addressSearch($parse, $rootScope, $http, $timeout, $sce) {
        return {
            templateUrl: '/src/js/directives/address-search/partial.html',
            replace: true, //study
            transclude: true, //study
            link: function(scope, elm, attrs) {

                scope.placeholder = attrs["placeholder"];

                scope.$watchCollection('googleSearch', function() {
                    scope.show = true;
                    if (scope.googleSearch == undefined) {
                        console.log("No value");
                    } else {
                        scope.searching = true;
                        setTimeout(function() {
                            $http({
                                method: "GET",
                                url: "https://maps.googleapis.com/maps/api/place/autocomplete/json?input=" + scope.googleSearch + "&key=AIzaSyAPYatPrCcmNcVdAO_MF0YhO3c1mgdLvuQ"

                            }).then(function mySuccess(response) {
                                scope.searching = false;
                                scope.res = response.data.predictions;
                            }, function myError(response) {
                                scope.searching = false;
                                scope.error = response.statusText;
                            });
                        }, 500)
                    }
                });

                scope.selectAddress = function(place) {
                    $http({
                        method: "GET",
                        url: "https://maps.googleapis.com/maps/api/place/details/json?placeid=" + place.place_id + "&fields=geometry,adr_address,address_component,formatted_address&key=AIzaSyAPYatPrCcmNcVdAO_MF0YhO3c1mgdLvuQ"
                    }).then(function mySuccess(response) {
                        scope.show = false;
                        scope.res = response.data;

                        scope.googleSearch = place.description;

                        myLatLng.lat = JSON.parse(scope.res.result.geometry.location.lat);
                        myLatLng.lng = JSON.parse(scope.res.result.geometry.location.lng);

                        draw(place);
                        displayRoute();

                    }, function myError(response) {
                        scope.error = response.statusText;
                    });
                }

                scope.blur = function() {
                    setTimeout(function() {
                        scope.show = false;
                    }, 500)
                }
            }
        }
    }
})(angular);