Openlayer: remove multiple popups

I am trying to create a spatial study using OpenLayers 2.11, but you have some problems with the function of closing multiple pop-ups.

The following code is great for a single popup, but the function cannot close multiple popups and post content.

Is there an OpenLayers method to destroy old popups when creating a new popup?

function submitform() { document.myform.submit(); loop_popups(); } 

-

 function loop_popups() { for( var i = 0; i < map.popups.length; ++i ) { map.removePopup(map.popups[i]); }; } 

-

 <form name="myform" action="sqlinsert.php" method="post" target="_blank"> <a href="javascript: submitform()">Save/close</a> 
+4
source share
2 answers

Using i to count the array when deleting members from it, only half of the markers are deleted. Try instead:

 while( map.popups.length ) { map.removePopup( map.popups[0] ); } 

If you want to absolutely make sure that the loop does not repeat forever:

 /** * Closes all the popups. */ function closePopups() { // Make sure the loop terminates... var maxIterations = 100; while( map.popups.length && --maxIterations ) { var popup = map.popups[0]; map.removePopup( popup ); popup.destroy(); } } 

This type of limited cycle technology is used in nuclear power plants.

Suppose you have 5 pop-ups.

  • popups = 5, i = 0, max.popups.length = 5
  • popups = 4, i = 1, max.popups.length = 4
  • popups = 3, i = 2, max.popups.length = 3
  • popups = 2, i = 3, max.popups.length = 2

The value of i now exceeds max.popups.length . The loop ends, but some pop-ups are not closed. (When trying to access the array of pop-ups, there may even have been an error outside the borders ...)

You could write your loop like:

 function loop_popups() { for( var i = map.popups.length - 1; i >= 0; i-- ) { map.removePopup(map.popups[i]); }; } 

This is no longer compared to a moving target and will run faster than the original loop, because comparisons with zero are faster than comparisons with case (on most computer architectures).

+6
source

You can pass exclusive: true to addPopup to automatically close all other popups, for example:

 map.addPopup(popup, true) 

See http://dev.openlayers.org/docs/files/OpenLayers/Map-js.html#OpenLayers.Map.addPopup

I found this to be useful for solving the problem of OpenLayers itself. I am not sure if another user was trying to make a comparison with nuclear power plants; it was completely optional.

0
source

Source: https://habr.com/ru/post/1384878/


All Articles