webmandman
webmandman

Reputation: 317

angularjs google maps $location.search does not change after autocomplete place_change

The initial request url is http://localhost/#/map?lat=33.73060000952102&lng=-117.12635126323244 In my project I'm using Google Maps Autocomplete Service which autopopulates the text field with address predictions and upon select an address the map is centered to that location. My place_changed event listener is fired successfully and my controllers setLocation function is called successfully. However, the URL in the address bar is NOT updated with the new lat and lng param values.

If I call $scope.getProjectsByCenter() from an ng-click in the html it works. Somehow event chain in place_changed conflicts with $location.search.

Anyone have any thoughts as to why?

angular: app.js

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

app.controller('MainMapController', function($scope,$location){

   $scope.setLocation = function(lat,lng){
      $location.search('lat',lat);
      $location.search('lng',lng);
      console.log($location.search()); //This logs an object with the new lat and lng
   };

   $scope.getProjectsByCenter = function(){
      var center = getProjectsByCenter();
      $scope.setLocation(center.lat(),center.lng());
   };

});

vanilla: map.js

function initializeMap() {
   var map = new google.maps.Map(document.getElementById("map-canvas"), {
      center: {lat: 33.868670, lng: -117.796783}
   });
   var input = document.getElementById('place-search');
   var autocomplete = new google.maps.places.Autocomplete(input);

   autocomplete.addListener('place_changed', function() {
      var place = autocomplete.getPlace();
      if (!place.geometry) {
         return;
      }
      var lat = place.geometry.location.lat();
      var lng = place.geometry.location.lng();

      angular.element('#MainMapController').scope().setLocation(lat,lng);

   };
};

Upvotes: 1

Views: 1021

Answers (1)

webmandman
webmandman

Reputation: 317

Found the answer. $apply()

My setLocation now looks like this:

$scope.setLocation = function(lat,lng){
   $location.search('lat',lat);
   $location.search('lng',lng);
   $scope.$apply();
};

Great article here: http://jimhoskins.com/2012/12/17/angularjs-and-apply.html

Upvotes: 1

Related Questions