循环中的函数

时间:2014-12-17 09:40:35

标签: javascript angularjs google-maps

我有一张带有几个标记的(谷歌)地图。这些标记的坐标和描述存储在对象中,标记在循环中创建。现在,我想为每个标记添加一个click事件,并将“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”)。但是当页面加载时它们都会被触发,如果我点击标记就没有任何反应。

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

谢谢!

4 个答案:

答案 0 :(得分:0)

你可以使用一个闭包(这是基于发布建议然后将其删除的人的想法)

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));
  });
};

答案 1 :(得分:0)

我稍微更改了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;
        }
    }                
});

答案 2 :(得分:0)

实际上我认为可能有一种更简单的方法 - 我认为你已经有了封闭,但是没有正确使用它

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

答案 3 :(得分:-1)

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



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);
    }
}                    
});
&#13;
&#13;
&#13;

感谢。