The last Info Window is showing for all the polygons in the array
I want to show infowindow with each polygon having their own different contents from excel sheet but my code is showing same infowindow having contents of the last row of excel with all polygons
Please can anyone solve this? Thanks in advance.
for(m=0; m < array.le开发者_如何学编程ngth; m++)
{
var lat = array[m][1];
var lon = array[m][2];
var latOffset = 0.5;
var lonOffset = 2;
var latOffset2 = 0.5;
var lonOffset2 = 2;
var polygon = new GPolygon([
new GLatLng(lat , lon ),
new GLatLng(lat - latOffset2, lon + (lonOffset-1)),
new GLatLng(lat - latOffset2, lon - (lonOffset-1)),
new GLatLng(lat , lon ),
], "#ff0000", 0.1 , 0.9, "#ff0000", 0.9);
a=array[m][1];
b=array[m][2];
c=array[m][0];
f=array[m][3];
h=array[m][4];
s=array[m][6];
bsc=array[m][5];
GEvent.addListener(polygon, "click", function(overlay,lat,lon)
{
map.openInfoWindowHtml(overlay,"Site"+ s +"<br>"+"BSC"+ bsc +"<br>"+"Cell"+ c +"<br>"+"Cell lattitude"+ lat +"<br>"+"Cell longitude" + lon + "<br>"+"Freq"+ f +"<br>"+"Height"+ h );});
map.addOverlay(polygon);
}
}
You are having a very common closure problem in the addListener
method.
Variables enclosed in a closure share the same single environment, so by the time the click
callback from the addListener
method is called, the loop will have run its course and the variables s
, bsc
, c
, f
, h
, lat
and lon
will be left pointing to the values of the last element in array
.
You can solve it with even more closures, using a function factory:
function makeInfoWindowEvent(map, overlay, s, bsc, c, lat, lon, f, h) {
return function() {
map.openInfoWindowHtml(overlay,
"Site"+ s +"<br>"+"BSC"+ bsc +"<br>"+
"Cell"+ c +"<br>"+"Cell lattitude"+ lat +"<br>"+
"Cell longitude" + lon + "<br>"+"Freq"+ f +"<br>"+
"Height"+ h );
};
}
// ...
for(m = 0; m < array.length; m++) {
// ...
GEvent.addListener(polygon, "click",
makeInfoWindowEvent(map, polygon, s, bsc, c, lat, lon, f, h)
);
}
This can be quite a tricky topic, if you are not familiar with how closures work. You may to check out the following Mozilla article for a brief introduction:
- Working with Closures
精彩评论