I’m creating a list of markers for a map, which – when they are dragged onto the map (via jquery draggable) – the image is replaced with a map marker.
The problem I am having, is that when creating my marker controllers – they each have a specific type – extracted from a list. As I iterate through the list, each dragable element gets given its ‘stop’ function, which uses the variable ‘type’… now when each element is dragged on – they all act as though they are the ‘type’ of the last element, rather than their own.
Can anyone suggest how I might restructure this so that each marker maintains its specific type?
var createMarkerControl = function(){
var markerTypes = ['custom', 'exit', 'food', 'medical', 'shelter', 'video'];
var control = document.createElement('div');
control.setAttribute('id', 'markerInput');
for (var i = 0; i < markerTypes.length; i++){
var image = document.createElement('img');
image.setAttribute('id', 'draggable-' + markerTypes[i]);
image.setAttribute('src', 'images/gui/' + markerTypes[i] + '.png');
image.style.width = '30px';
//Set type
var type = markerTypes[i];
//Make elements dragable/dropable
control.appendChild(image);
$(image).draggable({
helper: 'clone',
stop: function(e){
//Add marker to map
var point = new google.maps.Point(e.pageX, e.pageY);
customMap.addPlacemark(point, type);
},
cursorAt: {left: 15, top: 0}
});
}
map.controls[google.maps.ControlPosition.RIGHT_CENTER].push(control);
}
This is because JavaScript does not have block-level scope, only function-level scope. The
imageandtypevariables are scoped tocreateMarkerControl, not to the loop. More importantly, they are scoped outside your draggable closure, so every closure will share thetypevariable.I think you want your inner loop to look more like this:
By placing the logic in a subfunction, you ensure that references to
typeandimageare unique to the inner closures.