循环函数

Function in a loop

本文关键字:函数 循环      更新时间:2023-09-26

我有一个(谷歌)地图,上面有几个标记。这些标记的坐标和描述存储在对象中,标记在循环中创建。现在,我想以"key"值作为链接目标向每个标记添加一个单击事件。这是我的代码片段:

对象:

$localstorage.setObject('lsStations', {
    "STA": {lat: '50.93358', lng: '6.57', name: 'Station A'},
    "STB": {lat: '50.9332', lng: '6.56690', name: 'Station B'},
    "STC": {lat: '50.934', lng: '6.566', name: 'Station C'}
});

创建地图和标记:

.controller('GMapsCtrl', function ($scope, $localstorage) {
    'use strict';
    // initialize variables
    var map,
        myLatLng = new google.maps.LatLng(50.93358, 6.56692),
        stationCoords = $localstorage.getObject('lsStations');
    $scope.init = function () {
        var mapOptions = {
            zoom: 16,
            // default center
            center: myLatLng,
            // disable google maps ui
            disableDefaultUI: 1
        },
            map = new google.maps.Map(document.getElementById('map'), mapOptions),
            marker = [],
            index,
            key;
        for (key in stationCoords) {
            if (stationCoords.hasOwnProperty(key)) {
                // add marker for station
                marker[key] = new google.maps.Marker({
                    position: new google.maps.LatLng(stationCoords[key].lat, stationCoords[key].lng),
                    map: map,
                    title: stationCoords[key].name
                });
                // add click event for each marker
                google.maps.event.addListener(marker[key], 'click', function () {
                    $scope.startStation = key;
                    alert(key);
                }
            )}
        }
    };   
    $scope.init();
});

当我单击任何标记时,警报文本是"STC"而不是第一个标记的"STA",第二个标记的"STB"和第三个标记的"STC"。因此,我试图将函数代码放在循环之外:

.controller('GMapsCtrl', function ($scope, $localstorage) {
    'use strict';
    // initialize variables
    var map,
        myLatLng = new google.maps.LatLng(50.93358, 6.56692),
        stationCoords = $localstorage.getObject('lsStations');
    $scope.init = function () {
        var mapOptions = {
            zoom: 16,
            // default center
            center: myLatLng,
            // disable google maps ui
            disableDefaultUI: 1
        },
            map = new google.maps.Map(document.getElementById('map'), mapOptions),
            marker = [],
            index,
            key;
        function createMarker() {
            $scope.startStation = key;
            alert(key);
            //window.location.href = '#/station/' + key;
        }
        for (key in stationCoords) {
            if (stationCoords.hasOwnProperty(key)) {
                // add marker for station
                marker[key] = new google.maps.Marker({
                    position: new google.maps.LatLng(stationCoords[key].lat, stationCoords[key].lng),
                    map: map,
                    title: stationCoords[key].name
                });
                // add click event for each marker
                google.maps.event.addListener(marker[key], 'click', createMarker(key));
            }
        }
    };    
    $scope.init();  
});

使用此代码,警报对话框获得正确的文本("STA"、"STB"和"STC")。但是它们在加载页面时都会被触发,如果我单击标记,则没有任何反应。

如何为每个标记分配一个点击事件,为每个标记分配不同的键值?

谢谢!

你可以

使用闭包(这是基于发布建议然后删除它的人的想法)

createMarkersForRecommendations = function() {
  return stationCoords.forEach(function(rec, idx) {
    var thisPoint;
    thisPoint = new google.maps.LatLng(rec.lat, rec.lng);
    map.markers[idx] = new google.maps.Marker({
      title: rec.rname,
      position: thisPoint,
      icon: rec.icon,
    });
    map.markers[idx].setMap(map);
    google.maps.event.addListener(map.markers[idx], "click", (function(ix) {
      if (Restos.debug) {
        console.log(ix + 1, map.markers[ix].getTitle());
      }
      return $scope.$apply();     // as a google maps click event does not trigger an angluar digest
    }).bind(null, idx));
  });
};

我稍微更改了 Aqib Mapari 的代码片段,现在它正在工作:

google.maps.event.addListener(marker[key], 'click', function () {
    var thisMarker;
    for (thisMarker in marker) {
        if (marker[thisMarker] === this) {
            // link to detail page for selected marker
            window.location.href = '#/station/' + thisMarker;
        }
    }                
});

实际上我认为

可能有一种更简单的方法 - 我认为您已经有了闭包,但只是没有正确使用它

   function createMarker(key) {
                  //     ^^^
        $scope.startStation = key;
        alert(key);
        //window.location.href = '#/station/' + key;
    }

尝试在单击功能中进行此更改。它对我有用。

google.maps.event.addListener(marker[key], 'click', function () {
for(var j=0; j<marker.length; j++){
    if(marker[j] == this){
        $scope.startStation = key;
        alert(key);
    }
}                    
});

谢谢。