Reputation: 4102
Please have a look at this demo I am trying to figure out how to highlight ng-repeat element when corresponding google map marker on the map is clicked. As you can see, it works when you click the ng-repeat element but not when you click the marker.
HTML structure:
<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 code:
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');
}
});
Data object:
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
}
];
Upvotes: 1
Views: 1188
Reputation: 196002
Since the click handler is outside the angular scope you need to manually tell it to check for changes. So you must call $scope.$digest()
on you own.
But your code triggering of the click will cause a loop of digests.
So you should gather all your infobox code in your $scope.openInfoWindow
method
$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);
}
and change your click handler to call this method
google.maps.event.addListener(marker, 'click', function(){
$scope.openInfoWindow(null, marker);
$scope.$digest();
});
Demo at http://jsfiddle.net/gaby/19hfoxh8/
Upvotes: 3