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;
});
});
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();
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With