单击Google地图标记时突出显示ng-repeat元素

时间:2014-10-23 16:56:39

标签: angularjs google-maps-api-3 angularjs-ng-repeat

请查看此demo 我想弄清楚如何在点击地图上相应的谷歌地图标记时突出显示ng-repeat元素。如您所见,当您单击ng-repeat元素时它会起作用,但是当您单击标记时则不起作用。

HTML结构:

<div ng-app="mapsApp" ng-controller="MapCtrl">
<div id="map"></div>
<div ng-repeat="marker in markers"
                ng-class="{active: $index == markerId}"     >
     <a href="#" ng-click="openInfoWindow($event, marker)">{{marker.title}}</a>
</div>

角度代码:

angular.module('mapsApp', []).controller('MapCtrl', function ($scope) {

var mapOptions = {
    zoom: 4,
    center: new google.maps.LatLng(40.0000, -98.0000),
    mapTypeId: google.maps.MapTypeId.TERRAIN
}

$scope.map = new google.maps.Map(document.getElementById('map'), mapOptions);

$scope.markers = [];

var infoWindow = new google.maps.InfoWindow();

var createMarker = function (info){

    var marker = new google.maps.Marker({
        map: $scope.map,
        position: new google.maps.LatLng(info.lat, info.long),
        title: info.city
    });
    marker.content = '<div class="infoWindowContent">' + info.desc + '</div>';


    google.maps.event.addListener(marker, 'click', function(){
        infoWindow.setContent('<h2>' + marker.title + '</h2>' + marker.content);
        infoWindow.open($scope.map, marker);

        $scope.markerId = $scope.markers.indexOf(marker);
    });

    $scope.markers.push(marker);

}  

for (i = 0; i < cities.length; i++){
    createMarker(cities[i]);
}

$scope.openInfoWindow = function(e, selectedMarker){
    e.preventDefault();
    google.maps.event.trigger(selectedMarker, 'click');
}

});

数据对象:

var cities = [
{
    city : 'Toronto',
    desc : 'This is the best city in the world!',
    lat : 43.7000,
    long : -79.4000
},
{
    city : 'New York',
    desc : 'This city is aiiiiite!',
    lat : 40.6700,
    long : -73.9400
},
{
    city : 'Chicago',
    desc : 'This is the second best city in the world!',
    lat : 41.8819,
    long : -87.6278
},
{
    city : 'Los Angeles',
    desc : 'This city is live!',
    lat : 34.0500,
    long : -118.2500
},
{
    city : 'Las Vegas',
    desc : 'Sin City...\'nuff said!',
    lat : 36.0800,
    long : -115.1522
}
];

1 个答案:

答案 0 :(得分:3)

由于点击处理程序在角度范围之外,您需要手动告诉它检查更改。因此,您必须自己致电$scope.$digest()

但是你的代码触发点击会导致一个摘要循环。

因此,您应该在$scope.openInfoWindow方法

中收集所有信息框代码
$scope.openInfoWindow = function(e, selectedMarker){
    e && e.preventDefault();

    infoWindow.setContent('<h2>' + selectedMarker.title + '</h2>' + selectedMarker.content);
    infoWindow.open($scope.map, selectedMarker);
    $scope.markerId = $scope.markers.indexOf(selectedMarker);        
}

并更改您的点击处理程序以调用此方法

google.maps.event.addListener(marker, 'click', function(){
        $scope.openInfoWindow(null, marker);
        $scope.$digest();
    });

http://jsfiddle.net/gaby/19hfoxh8/

演示