问题描述
我在使用GMap和Angular时遇到问题,但首先让我解释一下我的问题:
- 我的标记已在地图上正确设置
- 当我点击一个标记时,我想推送$ scope.details数组以在我的视图中使用它(见下文)
- 基本上,我正在编写自己的信息窗口,以在右侧的边栏中显示合作伙伴详细信息(而不是在地图上显示)
- 我的问题是,每当我单击一个标记时,它只会推至$ scope.details循环中的最后一个索引
现在,让我与您分享一些代码:
地图初始化(以法国FYI为中心):
var map = null,
markers = [];
$scope.details = [];
function initializeMap() {
var mapOptions = {
center: { lat: 46.52863469527167, lng: 2.43896484375},
zoom: 5
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
setMarkers(map, partners);
}
合作伙伴信息将被放置在地图上
var partners = [
{
'title' : 'Partenaire 1',
'lat' : 46.52863469527167,
'lng' : 2.43896484375,
'type' : 'Distributeur'
},
{
'title' : 'Partenaire 2',
'lat' : 47.52863469527167,
'lng' : 3.43896484375,
'type' : 'Fabricant'
},
{
'title' : 'Partenaire 3',
'lat' : 46,
'lng' : 5,
'type' : 'Fabricant'
}
];
在地图上设置标记
function setMarkers(map, locations) {
for (var i in locations) { // Looping through given locations (ie through partners array)
var location = locations[i];
var myLatLng = new google.maps.LatLng(location.lat, location.lng);
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
title: location.title
});
markers.push(marker); // Pushing markers in their own array for later purpose
marker.setMap(map); // Setting the marker on the map
google.maps.event.addListener(marker, 'click', function() { // Adding click listener on the marker
$scope.details.push(location); // Pushing the clicked marker details
// The line above is only pushing the last index in the loop
$scope.$apply(); // Applying changes (needed in my case)
});
}
};
查看代码:
<div class="row">
<div class="col-md-9">
<div style="height:500px; width: 100%; position: relative">
<div id="map-canvas"></div>
</div>
</div>
<div class="col-md-3">
<pre>{{details}}</pre>
<div class="well" ng-repeat="d in details track by $index">
<span class="glyphicon glyphicon-remove" ng-click="removeDetail($index)"></span>
<p>{{d.title}}</p>
<button class="btn btn-default" ng-click="localize(details[$index])">Localiser</button>
</div>
</div>
</div>
我找不到我做错的任何事情,希望你们对此有所帮助! 提前谢谢了。
PS:别指望我能尽快给我答复,因为我待了几天
1楼
您的问题在这里:
for (var i in locations) { // Looping through given locations (ie through partners array)
var location = locations[i];
...
google.maps.event.addListener(marker, 'click', function() {
$scope.details.push(location);
});
}
您遍历所有标记,更新名为location
的变量。
每个标记都有其自己的事件侦听器,然后使用location
...但是,这不是在每次迭代的for循环内创建的版本,而是用户单击标记时location
,即该标记在结尾处具有的值。您的for循环。
一种快速的解决方法是将该位置作为自定义属性添加到每个标记,然后可以在事件侦听器中引用它,例如
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
title: location.title,
location: location
});
google.maps.event.addListener(marker, 'click', function() {
$scope.details.push(this.location);
});