0

I have a number of elements that I need to add to a page using javascript with data pulled from the server with their position information. I want to arrange them so that there is no overlap. For example, element 5 would be moved to where the thin green box is, so that it doesn't overlap element 3.

I have successfully created a function which decides whether two boxes overlap. For example, if I ran overlaps($('#element5')[0],$('#element3')[0]) it would return true.

However, with this function I would have to loop through each element and compare it with every other element. So for 50 elements I would need to do run the overlays function 1275 times which would take a long time to load.

I decided I would best creating an rtree to organise the elements first so that I could easily work out which 2 elements I would need to run the overlay function with, significantly reducing the number of runs of the overlay function. However, I am extremely confused on how this would work. How would I organise them so that I would only have to run the function with a small number? Wouldn't 2 of the rtree's bounding boxes overlap and make this technique redundant? What would be the best way to do this?

enter image description here

Cameron
  • 1,011
  • 1
  • 10
  • 20

1 Answers1

0

In an R-tree, rectangular pages can indeed overlap.

When searching for overlaps, you would have to explore both groups then.

But the number of overlapping pages in the r-tree shouldn't be too big (unless the tree was built very badly), so this will still yield a good speedup. Assuming you have 50 elements in 5 pages of 10 elements each, you will first have to test the 5 top level pages, then maybe test the 10 elements in 0-2 of these pages, so maybe just 15 overlap tests instead of 50. The exact numbers will of course vary a lot.

For a HTML solution, however, I would consider a grid based approximation instead. Divide your surface in 10x10 cells. Each cell contains references of the rectangles that overlap with this grid cell.

When testing for overlap, you look at the grid cells the query rectangle touches, collect all referenced existing rectangles, and then overlap test only those. If you store two lists in each cell - "overlaps partially" and "overlaps completely", you can even skip many of the overlap tests: if any grid cell touched by one is overlapped completely by the other, they will overlap somewhere.

Yet another approach would be to sort the rectangles by X axis, to quickly narrow down the number of rectangles that can actually overlap with a binary search. This also should drastically reduce the number of intersection calls.

Oh, and last but not least: 1275 overlap tests should not take a lot of time anyway. This is by any means a tiny data set that you are talking about. R-trees and similar approaches are meant for data sets with millions of items.

Has QUIT--Anony-Mousse
  • 76,138
  • 12
  • 138
  • 194