Saturday, 15 May 2010

angularjs - Highlight ng-repeat element when Google Maps marker is clicked -



angularjs - Highlight ng-repeat element when Google Maps marker is clicked -

please have @ demo trying figure out how highlight ng-repeat element when corresponding google map marker on map clicked. can see, works when click ng-repeat element not when click 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); } (i = 0; < 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 best city in world!', lat : 43.7000, long : -79.4000 }, { city : 'new york', desc : 'this city aiiiiite!', lat : 40.6700, long : -73.9400 }, { city : 'chicago', desc : 'this sec best city in world!', lat : 41.8819, long : -87.6278 }, { city : 'los angeles', desc : 'this city live!', lat : 34.0500, long : -118.2500 }, { city : 'las vegas', desc : 'sin city...\'nuff said!', lat : 36.0800, long : -115.1522 } ];

since click handler outside angular scope need manually tell check changes. must phone call $scope.$digest() on own.

but code triggering of click cause loop of digests.

so should gather infobox code in $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 alter click handler phone call method

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

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

angularjs google-maps-api-3 angularjs-ng-repeat

No comments:

Post a Comment