迭代数组并向每个数组添加google maps事件?

时间:2017-10-14 20:40:00

标签: javascript google-maps knockout.js

所以我有一个使用KnockoutJS的Google地图项目。我像这样定义标记:

for (i = 0; i < markerData.length; i++) {
  // Grab marker data so we only have to call it once
  var m = markerData[i];
  // Define everything
  var position = new google.maps.LatLng(m.location.lat, m.location.lng);
  var title = m.title;
  // etc etc

  // Push all this info to the google maps marker
  var marker = new google.maps.Marker({
    map: map,
    position: position,
    title: title
    // etc with rest 
  });

然后在同一个for循环中,我尝试定义一个信息窗口,简化为阅读:

  google.maps.event.addListener(marker, 'click', function() {
    infoWindow.setContent(this.title + '<br>' + this.address + '<br><a target="_blank" href="' + this.directions + '">Get Directions</a>');
    infoWindow.open(map, this);
    map.setCenter(this);
  });

虽然它完全按照我喜欢的方式工作,但是linters说不要在for循环中创建一个函数。话虽如此 - 有没有办法可以将它移到for循环之外并仍然能够有效地工作?到目前为止,我尝试过的所有东西都已经以某种方式转变为另一种循环,这仍然会引发麻木。

我觉得我错过了一些在这里显而易见的东西。有关如何正确应用此内容的任何想法或想法?

作为旁注 - 所有标记都在KO vm viewModel.gMarkers()中。非常感谢任何帮助,谢谢!

1 个答案:

答案 0 :(得分:1)

特别是linter抱怨for循环中的匿名函数google.maps.event.addListener(marker, 'click', function() {};。您可以尝试将其放入自己的函数中,并在传入标记的循环中调用它。

var m, position, title, marker;

for (i = 0; i < markerData.length; i++) {
  // Grab marker data so we only have to call it once
  m = markerData[i];
  // Define everything
  position = new google.maps.LatLng(m.location.lat, m.location.lng);
  title = m.title;
  // etc etc

  // Push all this info to the google maps marker
  marker = new google.maps.Marker({
    map: map,
    position: position,
    title: title
    // etc with rest 
  });

  doThis(marker);
}

function doThis(marker) {
  google.maps.event.addListener(marker, 'click', function() {
    infoWindow.setContent(this.title + '<br>' + this.address + '<br><a 
    target="_blank" href="' + this.directions + '">Get Directions</a>');
    infoWindow.open(map, this);  // Not sure where map is coming from
    map.setCenter(this);
 });
}