0

I am trying to make a map with shiftzoom.js

I have the following code snippet:

function selectall() {
    for (i in geodata['world']) {
        var q = getGeoPosition('world', i.toUpperCase(), 1654, 496, 1350, 407);
        shiftzoom.construct($('world'), [{
            x: q.l,
            y: q.t,
            w: 40,
            h: 40,
            id: geodata['world'][i].lc,
            pos: 0,
            title: '',
            href: "javascript:get_lake(i); ",
            target: 'graphFrame',
            src: 'images/bullet.gif'
        }]);
        cvi_tip.add(cvi_tip.$(geodata['world'][i].lc), '<small>Province:</small><br/><big><b><u>' + geodata['world'][i].ln + '</u></b></big><br/><small>LAT/LONG:</small><br/><big><b>' + geodata['world'][i].coord + '</b></big><br/><small>PROVINCE:</small><br/><big><b><i>' + geodata['world'][i].pr + '</i></b></big>');
    }
}

I am positioning dots to represent lakes on the map and I would like it to zoom in when the dot is clicked. This is what the function get_lake does, but every dot I click shows zooms in to the last value of "i". I have tried using closures like so:

 href:"javascript:function(num){return function(){get_lake(num);};}(i);"

but I might not be using it properly since this code doesn't run. Does anyone know how to code it so that the function calls the current variable instead of the last one?

Thanks

casperOne
  • 73,706
  • 19
  • 184
  • 253
LostLin
  • 7,762
  • 12
  • 51
  • 73
  • The `href` code won’t get evaluated until the moment you click on the link. The variable `i` will, by then, have a completely different value — if it’s available in that context at all... Much to learn, you have, young Padawan... :-D – Martijn Feb 24 '11 at 20:36
  • Is there a workaround for this problem? – LostLin Feb 24 '11 at 21:21

2 Answers2

2

I'll be honest, I am not familiar with the library you are using, and I find the code you've posted to be an absolute MESS! Indenting would help readability a lot. Anyway, try this:

href:"javascript:get_lake("+i+"); ",

A closure is not going to work here because you aren't creating a function there: you're making a string. Thus, concatenating the value of i into the string.

Chris Baker
  • 49,926
  • 12
  • 96
  • 115
  • I tried putting this in my code but my code doesn't run. Sorry for the messy code. Is there another workaround? – LostLin Feb 24 '11 at 21:34
0

It's unclear to me from your code what to change, but this answer may be of some help:

JavaScript closure inside loops – simple practical example

Community
  • 1
  • 1
James Sulak
  • 31,389
  • 11
  • 53
  • 57