Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google places autocomplete with angular js

I am trying to make google places autocomplete work with angular js. Here is jsfiddle - Model is not getting updated after'place_change' event. It is getting updated on change of input.

Below is html code - HTML

<body ng-app="mapApp">
    <div ng-controller="MapController">
        <input id="from" type="text" ng-model="user.from" placeholder="Type Address" class="ng-pristine ng-valid" autocomplete="off">
        <input type="hidden" ng-model="user.fromLat">
        <input type="hidden" ng-model="user.fromLng">
            <p>{{user.from}} <br> {{'Latitude : ' + user.fromLat + ', Longitutde : ' + user.fromLng}}</p>
    </div>
</body> 

Java Script

var mapApp = angular.module('mapApp', []);

mapApp.controller('MapController', function ($scope) {
    $scope.user = {'from': '', 'fromLat': '', 'fromLng' : ''};
    var options = {
        componentRestrictions: {country: "in"}
    };
    var inputFrom = document.getElementById('from');
    var autocompleteFrom = new google.maps.places.Autocomplete(inputFrom, options);
    google.maps.event.addListener(autocompleteFrom, 'place_changed', function() {
        var place = autocompleteFrom.getPlace();
        $scope.user.fromLat = place.geometry.location.lat();
        $scope.user.fromLng = place.geometry.location.lng();
        $scope.user.from = place.formatted_address;
    });
});
like image 237
Puja Avatar asked Jul 08 '14 16:07

Puja


1 Answers

You need to tell angular when the place_change event gets fired so it knows when to update the DOM. You can do that by calling $scope.$apply(). e.g.:

google.maps.event.addListener(autocompleteFrom, 'place_changed', function() {
        var place = autocompleteFrom.getPlace();
        $scope.user.fromLat = place.geometry.location.lat();
        $scope.user.fromLng = place.geometry.location.lng();
        $scope.user.from = place.formatted_address;
        $scope.$apply();
    });
like image 76
rob Avatar answered Sep 30 '22 05:09

rob