在JavaScript中访问AngularJS范围变量以填充谷歌地图

时间:2017-04-11 07:43:33

标签: javascript angularjs json google-maps heatmap

我使用AngularJS从MongoDB服务器获取了一个JSON数组,如下所示:

我的controller.js:

var app = angular.module('myApp', []);
app.controller('myCtrl',function($scope, $http) {
$scope.stack=[];


$scope.loadData = function(){ 

    var request =$http({
      method: "post",
      url: "my_api",


      headers:{'Content-Type':'application/x-www-form-urlencoded' },
      transformRequest: function() {
            var str = [];
            str.push(encodeURIComponent("collection") + "=" + encodeURIComponent("emergencyalerts"));
            return str.join("&");
        }

    });
    request.success(function(response){
        console.log("success");

    for(var i = 0; i < response.length; i++) {
            $scope.stack.push('new google.maps.LatLng('+response[i].location+')');
        }

        console.log($scope.stack);

    });

};
});

在控制台中:

 $scope.stack= Array ["new google.maps.LatLng(33.75218,-118.29082)",
                     "new google.maps.LatLng(33.77276,-118.20692)",
                     "new google.maps.LatLng(33.90358,-118.18547)",
                     "new google.maps.LatLng(33.80297,-118.08174)"
]

我想在Google HeatMap中绘制这些点。

我的html页面:

<body ng-app='myApp' ng-controller='myCtrl' ng-init="loadData()">
<div id="map"></div>
<script>
  var map, heatmap;

  function initMap(getNum) {
    map = new google.maps.Map(document.getElementById('map'), {
      zoom: 10,

      center: {lat: 34.022352, lng: -118.285117},
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });

     var gradients = {
      color: [
      'rgba(0, 0, 0, 0)',
      'rgba(0, 0, 0, 0)',
      'rgba(0, 0, 0, 0)',
      'rgba(0, 0, 159, 1)',
      'rgba(255, 0, 0, 1)',
      'rgba(255, 0, 0, 1)'
      ]
    };

    heatmap = new google.maps.visualization.HeatmapLayer({
      data: $scope.stack,
      radius: 13,
      opacity: 100,
      map: map
    });
     heatmap.set('gradient', gradients['color']);

  }
</script>

错误:ReferenceError:$ scope未定义

如何通过从Mongo DB获取数据来实时解析并显示lat lng点?

2 个答案:

答案 0 :(得分:2)

改述上述解决方案:

var $element = $('#div1');
var scope = angular.element($element).scope();
heatmap = new google.maps.visualization.HeatmapLayer({
   data: scope.stack,
   radius: 13,
   opacity: 100,
   map: map
});

这里div1是最上面的div(即正文)的id。

示例:

<body ng-app='myApp' ng-controller='myCtrl' ng-init="loadData()" id="div1">

答案 1 :(得分:1)

引用错误是因为$ scope在angular app之外不可用。为此,您必须使用angular.element访问范围以访问角度应用程序外的$ scope。做这样的事情:

var scope = angular.element($("pointerToUppermostDivOfPage").scope();
heatmap = new google.maps.visualization.HeatmapLayer({
  data: scope.stack,
  radius: 13,
  opacity: 100,
  map: map
});