我使用GMap和Angular时遇到了问题,但首先,让我解释一下我的问题:
现在,让我与您分享一些代码:
地图初始化(以法国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:不要期待我的快速回答,因为我会离开几天答案 0 :(得分:0)
你的问题在这里:
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);
});