Tom Tom - 1 month ago 10
AngularJS Question

AngularJS change variable outside of function

I have a function in Angular that changes the center value for Google Maps when a user clicks on the map. The correct center value is then alerted to the screen but the marker does not change to that position like it should.

Web page: http://alainwebdesign.ca/pl2/#/getLocation

Controller:

.controller('GetlocationCtrl', ['$scope', "uiGmapLogger", "uiGmapGoogleMapApi", "$state", "$stateParams",
function ($scope, $log, GoogleMapApi, $state, $stateParams) {
$log.currentLevel = $log.LEVELS.debug;
center = { latitude: 49.22, longitude: -122.66 }; //default center
alert(JSON.stringify(center));

console.log($stateParams);

$scope.map = {
center: center,
pan: false,
zoom: 16,
refresh: false,
events:
{ click: function newCenter(mapModel, eventName, originalEventArgs)
{
$scope.$apply(function(){
var e = originalEventArgs[0];
center = { latitude: e.latLng.lat(), longitude: e.latLng.lng() };
alert(JSON.stringify(center));
return center;
});
}
}

}


HTML partial/view:

<!--Add ability to input location as address-->

<div style="height: 100%">
<h1>TEST</h1> <!--NOT SHOWING ON PAGE WHICH MEANS THIS IS NOT BEING INVOKED WHEN
URL IS: '/getLocation' like it should-->
<ui-gmap-google-map
center='map.center'
zoom='map.zoom'
draggable='map.draggable'
dragging='map.dragging'
refresh='map.refresh'
options='map.options'
events='map.events'
pan='map.pan'>


<ui-gmap-marker
idKey='1'
events='map.events'
coords='map.center'
>
</ui-gmap-marker>

</ui-gmap-google-map>

<script src='//maps.googleapis.com/maps/api/js?key=AIzaSyD4_0KuPivZyV-1EwNGmBCgLc_Z0o8Dyw8'></script>
</div>

Answer

You can directly set $scope.map.center instead of center variable and it will be ok. Here is working click function example:

   click: function newCenter(mapModel, eventName, originalEventArgs)
          {
            $scope.$apply(function(){
              var e = originalEventArgs[0];
              $scope.map.center = { latitude: e.latLng.lat(), longitude: e.latLng.lng() };

            });
          }