将不同的infowindows附加到多边形谷地图组

时间:2015-06-11 21:08:32

标签: javascript arrays google-maps google-maps-api-3 polygons

现在我的代码看起来像这样:

   // create a LatLng array out of given coordinates string
  for (var i = 0; i < coordinateString.length; i++) {
    var polygonCoords = new Array();
    var j = 0;
    var z = j + 1;
    while (z < coordinate.length) 
    {
      if ((j%2) === 0) 
      {
        var coord1 = parseFloat(coord[z]);
        var coord2 = parseFloat(coord[j]);
        var newLatLng = new google.maps.LatLng(coord1,coord2);
        polygonCoords.push(newLatLng);
        } else 
        {
            var coord1 = parseFloat(coord[j]);
            var coord2 = parseFloat(coord[z]);
            var newLatLng = new google.maps.LatLng(coord1,coord2);
            polygonCoords.push(newLatLng);
        }
    z++;
    j++;
    }

    /** Adds the polygon to a polygon array
    * and maps it onto the map
    */

         var newPoly = new google.maps.Polygon(
          {
            paths: polygonCoords,
            strokeColor: objArray[i].borderColor,
            strokeOpacity: 0.8,
            strokeWeight: 2,
            fillColor: objArray[i].fillColor,
            fillOpacity: 0.35
            })
          newPoly.setMap(map);
          newPoly.set("eventNum",objArray[i].eventID)
          newPoly.set("offTime", objArray[i].offTime)

           function attachInfoWindow(event) 
            {
              var infowindowPoly = new google.maps.InfoWindow();
              var eventNo = newPoly.get("eventNum");
              var outTime = newPoly.get("offTime");
              var resTime = objArray[i].restoreTime;
              var contentString = "Event Number: " + eventNo + "<br> Outage Time: " + outTime + "<br> Estimated Restoration Time: " + resTime;
              infowindowPoly.setContent(contentString);
              infowindowPoly.setPosition(event.latLng);
              infowindowPoly.open(map);
              google.maps.event.addListener(map, 'click', function() 
                {
                  infowindowPoly.close();
                });
            }
          google.maps.event.addListener(newPoly, 'click', attachInfoWindow); 
         }
       }

在不同的位置创建一个多边形数组(它的循环,因此每次创建一个新的多边形并设置为地图时),当点击时,会弹出一个信息窗并显示一些内容,但它是相同的内容。但是我想为每个多边形显示不同的信息窗口。我已经阅读了所有其他类似的问题和答案,并修改了我的代码。

请注意,我已将存储我想要的内容的对象存储到数组中,并使用索引和其他方法来获取对象的属性,然后将其显示为我的infowindow内容。

2 个答案:

答案 0 :(得分:3)

这里的一个问题是你有一个变量i,每次循环都会更新,你在异步回调中使用该变量。但是在循环完成后很久就会调用该回调函数,因此i没有您期望的值。

您可以通过为循环体创建函数并在每次循环时调用该函数来解决此问题。这样,函数内定义的每个函数参数和变量都是函数特定调用的局部函数 - 因此它具有与您正在使用的单个多边形匹配的值。

它可能看起来像这样:

      for (var i = 0; i<numOfPolygons; i++) {
          addPoly( objArray[i] );
      }

      function addPoly( source ) {
         var newPoly = new google.maps.Polygon(
          {
            paths: polygonCoords,
            strokeColor: source.borderCol,
            strokeOpacity: 0.8,
            strokeWeight: 2,
            fillColor: source.fill,
            fillOpacity: 0.35
            })
          newPoly.setMap(map);
          newPoly.set("eventNum",source.eventID)
          newPoly.set("offTime", source.offTime)
           function attachInfoWindow(event) 
            {
              var infowindowPoly = new google.maps.InfoWindow();
              var eventNo = newPoly.get("eventNum");
              var outTime = newPoly.get("offTime");
              var resTime = source.restoreTime;
              var contentString = "Event Number: " + eventNo + "<br> Outage Time: " + outTime + "<br> Estimated Restoration Time: " + resTime;
              infowindowPoly.setContent(contentString);
              infowindowPoly.setPosition(event.latLng);
              infowindowPoly.open(map);
              google.maps.event.addListener(map, 'click', function() 
                {
                  infowindowPoly.close();
                });
            }
          google.maps.event.addListener(newPoly, 'click', attachInfoWindow); 
         }
       }

答案 1 :(得分:2)

创建一个函数以返回单击侦听器函数。将索引和多边形传递给该函数,以便对它们进行函数闭包以使它们保持关联:

function attachInfoWindow(newPoly, i) {
    return function (event) {
        var eventNo = newPoly.get("eventNum");
        var outTime = newPoly.get("offTime");
        var resTime = objArray[i].restoreTime;
        var contentString = "Event Number: " + eventNo + "<br> Outage Time: " + outTime + "<br> Estimated Restoration Time: " + resTime;
        infowindowPoly.setContent(contentString);
        infowindowPoly.setPosition(event.latLng);
        infowindowPoly.open(map);
        google.maps.event.addListener(map, 'click', function () {
            infowindowPoly.close();
        });
    };
}

像这样调用函数:

for (var i = 0; i < numOfPolygons; i++) {
    var newPoly = new google.maps.Polygon({
        paths: polygons[i],
        strokeColor: objArray[i].borderCol,
        strokeOpacity: 0.8,
        strokeWeight: 2,
        fillColor: objArray[i].fill,
        fillOpacity: 0.35
    });
    newPoly.setMap(map);
    newPoly.set("eventNum", objArray[i].eventID);
    newPoly.set("offTime", objArray[i].offTime);

    google.maps.event.addListener(newPoly, 'click', attachInfoWindow(newPoly, i));
}

proof of concept fiddle

代码段

&#13;
&#13;
function attachInfoWindow(newPoly, i) {
  return function(event) {
    var eventNo = newPoly.get("eventNum");
    var outTime = newPoly.get("offTime");
    var resTime = objArray[i].restoreTime;
    var contentString = "Event Number: " + eventNo + "<br> Outage Time: " + outTime + "<br> Estimated Restoration Time: " + resTime;
    infowindowPoly.setContent(contentString);
    infowindowPoly.setPosition(event.latLng);
    infowindowPoly.open(map);
    google.maps.event.addListener(map, 'click', function() {
      infowindowPoly.close();
    });
  };
}

function initialize() {
  map = new google.maps.Map(
    document.getElementById("map_canvas"), {
      center: new google.maps.LatLng(37.4419, -122.1419),
      zoom: 13,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });
  var bounds = new google.maps.LatLngBounds();
  var polygons = [];

  for (var j = 0; j < coordinateStrings.length; j++) {
    var coordinates = coordinateStrings[j].split(" ");
    var polygonCoords = [];
    for (var i = 0; i < coordinates.length; i++) {
      var point = coordinates[i].split(",");
      var latlng = new google.maps.LatLng(parseFloat(point[1]), parseFloat(point[0]));
      bounds.extend(latlng);
      polygonCoords.push(latlng);
    }
    polygons.push(polygonCoords);
  }

  /** Adds the polygon to a polygon array
   * and maps it onto the map
   */
  var numOfPolygons = objArray.length;

  for (var i = 0; i < numOfPolygons; i++) {
    var newPoly = new google.maps.Polygon({
      paths: polygons[i],
      strokeColor: objArray[i].borderCol,
      strokeOpacity: 0.8,
      strokeWeight: 2,
      fillColor: objArray[i].fill,
      fillOpacity: 0.35
    });
    newPoly.setMap(map);
    newPoly.set("eventNum", objArray[i].eventID);
    newPoly.set("offTime", objArray[i].offTime);


    google.maps.event.addListener(newPoly, 'click', attachInfoWindow(newPoly, i));
  }
  map.fitBounds(bounds);
}

google.maps.event.addDomListener(window, "load", initialize);
var geocoder;
var map;
var infowindowPoly = new google.maps.InfoWindow();
var objArray = [{
  borderCol: "#FF0000",
  fill: "#FF0000",
  eventID: 1,
  offTime: "12:10"
}, {
  borderCol: "#0000FF",
  fill: "#0000FF",
  eventID: 2,
  offTime: "12:00"
}, {
  borderCol: "#00FF00",
  fill: "#00FF00",
  eventID: 3,
  offTime: "12:20"
}];
var coordinateStrings = ["-82.4908447265625,42.99058552185121,0 -82.52174377441406,43.013182961445914,0 -82.42286682128906,43.02573350308799,0 -82.38578796386719,42.98958099829517,0 -82.452392578125,42.96596996868038,0 -82.45857238769531,42.99359899401497,0",
  "-82.33840942382812,42.96094517567432,0 -82.33016967773438,43.014689161895184,0 -82.23129272460938,43.04079076668198,0 -82.23197937011719,42.954412331213284,0",
  "-82.4139404296875,43.062868070571454,0 -82.38372802734375,43.014689161895184,0 -82.22442626953125,43.06387139555526,0 -82.276611328125,43.15209968803547,0 -82.37411499023438,43.141078106345844,0"
];
&#13;
html,
body,
#map_canvas {
  height: 500px;
  width: 500px;
  margin: 0px;
  padding: 0px
}
&#13;
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map_canvas" style="border: 2px solid #3872ac;"></div>
&#13;
&#13;
&#13;