javascript - Remove elements from Drawing manager overlay array -
i working on map-based service. there user can select items on map drawing rectangles , polygons using drawingmanager. push these shapes global array after created keep control on them this:
google.maps.event.addlistener(drawingmanager, 'overlaycomplete', function(e) { if (e.type != google.maps.drawing.overlaytype.marker) { // switch non-drawing mode after drawing shape. drawingmanager.setdrawingmode(null); var newshape = e.overlay; all_overlays.push(newshape); newshape.type = e.type; newshape.id = all_overlays.length-1; all_overlays[newshape.id].id = all_overlays.length-1; }
the user has option delete single shape. implemented deletion this:
function deleteselectedshape() { if (selectedshape) { all_overlays.splice(selectedshape.id,1); while(jquery.inarray(selectedshape.id, selected_shapes) != -1) { var shape_index = jquery.inarray(selectedshape.id, selected_shapes); selected_shapes.splice(shape_index,1); selected_buoys.splice(shape_index,1); } selectedshape.setmap(null); selectedshape = ''; buildlist(); highlightselectedbuoys(); }
unfortunatly not working. if e.g. got array 4 shapes (ids:0,1,2,3) , delete array id=0, all_overlays array not change it's size, messes whole thing in next step. mistake?
forget newshape.id
, the index of shape change after splice.
use indexof instead:
all_overlays.splice(all_overlays.indexof(selectedshape),1);
the indexof() method returns first index @ given element can found in array, or -1 if not present. indexof compares searchelement elements of array using strict equality (the same method used ===, or triple-equals, operator). note splice nothing if pass -1 parameter.
complete example:
google.maps.event.addlistener(drawingmanager, 'overlaycomplete', function(e) { if (e.type != google.maps.drawing.overlaytype.marker) { // switch non-drawing mode after drawing shape. drawingmanager.setdrawingmode(null); var newshape = e.overlay; all_overlays.push(newshape); newshape.type = e.type; } } function deleteselectedshape() { if (selectedshape) { // here difference all_overlays.splice(all_overlays.indexof(selectedshape),1); // here maybe need same fix. selected_shapes.splice(selected_shapes.indexof(selectedshape),1); selected_buoys.splice(selected_buoys.indexof(selectedshape),1); // remove map. selectedshape.setmap(null); selectedshape = ''; // maybe should undefined. // stuffs buildlist(); highlightselectedbuoys(); } }
note: not cross-browser due indexof
not supported natively browsers. but can implement yourself. read this post support old browsers.
Comments
Post a Comment