I’ve been tinkering with Google Maps trying to plot some points and info from an XML file recently and have been getting a weird error that I cannot figure out. The page will load all right, displaying each marker from each one identified in the XML file just fine.
for (var i = 0; i < markers.length; i++)
{
var point = new GPoint(parseFloat(markers*.getAttribute(“lng”)), parseFloat(markers*.getAttribute(“lat”)));
var location = new GMarker(point);
var html = markers*.getAttribute("cptn");
GEvent.addListener(location, "click", function() { location.openInfoWindowHtml(html); });
map.addOverlay(location);
}
The problem I’m having is that it will place all the points and add only a single listener. Basically when you click on any of the points the info window for the last entry in the XML file opens up. If C was the last for example and I click on A or B, C will pop up its info window. If you need any more info other than what I provided just let me know. I looked at the Google API examples for doing this Google API Info Window and it looks like the only difference is their use of a function to make the markers. I don’t see why that would be the issue though. Thanks in advance for your help!
In my completely uneducated opinion, it looks like Java is reusing the same function pointer for all 3 functions. Try declaring the functions explictly in a variable and then passing the variable across.
Your completely uneducated opinion was 100% correct. I’m not really sure why it would use new points and markers everytime but refuse to use new events. Oh well. I functionalized the add marker portion and it worked perfectly. Thanks!
Grr… this is why I advocate a broad education for all CS students. Theoretically, this shouldn’t be your fault as the Java language should be smart enough not to destroy objects if there is a valid pointer to them but it isn’t.
The difference between functions, points and markers is that points and markers are both objects so they get created on the heap and have indefinate lifetimes until they get garbage collected. By calling the function, all you are doing is passing the object pointer along to the function so any variable stored on the stack can then safely be deleted. The entire listener function appears to be created on the stack so every time the parent function ends, the stack gets wiped and the function disappears. However, the function pointer is still live and pointing to the old address. This doesn’t become a problem until you re fill that bit of memory with new data, in this case, a new function.
Come to think of it, that may be a rather serious security flaw in Java if it allows you to jump to an arbitrary bit of executable in data space.