4

I've been messing around with jQuery-UI's widget factory to create a google map widget.

The widget factory includes pre-built destroy capabilities to remove a widget from an element. I'm interested to know whether there's a way to detach the original element from a Google Map without removing the element from the DOM.

Most of the searching I've done leads to how to remove markers and other layers from a Google Map, rather than removing the map from the DOM.

zzzzBov
  • 174,988
  • 54
  • 320
  • 367

2 Answers2

6

I think the simplest way is to create inner div inside the original div and initialize the map for the inner div. When destroying the map, just remove the inner div and that's it.

var $inner = $('<div style="width: 100%; height: 100%"></div>').appendTo('#map_div');
// creation:
var map = new google.maps.Map($inner[0], { ... });
// removal:
$inner.remove();

Without jquery:

document.getElementById('map_div').innerHTML = '<div id="inner_map_div" style="width: 100%; height: 100%"></div>';

// creation:
var map = new google.maps.Map(document.getElementById('inner_map_div'), { ... });

document.getElementById('map_div').innerHTML = ''; // removal
Tomas
  • 57,621
  • 49
  • 238
  • 373
  • clever. I'll need to make sure the width and height are 100%, but otherwise that just might work. – zzzzBov Dec 01 '11 at 18:50
  • @zzzzBov, it should work regardless of width/height being 100%, why shouldn't it? – Tomas Dec 01 '11 at 22:30
  • It would still work *technically*, but for the google maps api to work correctly, the DOM node needs an explicit height & width of some sort. – zzzzBov Dec 01 '11 at 22:33
  • @zzzzBov Yes you're right, the #inner_map_div should get dimensions too. I updated the post. – Tomas Dec 01 '11 at 22:41
  • I've updated your answer to better incorporate jQuery, if you don't like it, feel free to revert. – zzzzBov Dec 01 '11 at 23:18
2

Instead of .remove(), you can also use the jQuery function .empty() on the div which contains the map. This function deletes everything, but the div. So you don't need to have an outer and an inner div.

Ragunath Jawahar
  • 19,513
  • 22
  • 110
  • 155
Harald
  • 526
  • 4
  • 26