Reputation: 19839
I'm not sure the correct lingo for this, so feel free to edit the title of this post if necessary.
Basically, I'm creating a Google map object and adding a bunch of overlays, markers, etc. This is how I create the map:
map = new google.maps.Map(document.getElementById("map"), mapOptions)
But then, navigating through the side, I may land on a url where the map DOM element is destroyed, but the map object still exists in my web app. When I go back to the url that displays the map, I'd like to reattach the map to the DOM element as opposed to recreating the map.
Any ideas how to do this?
EDIT:
To be more specific, I have a bunch of markers and overlays on the map
Map =
map: null
markers:[]
icons: {}
init: ->
mapOptions =
center: new google.maps.LatLng(34.0500, -118.2500)
zoom: 9
@map = new google.maps.Map(document.getElementById("map"), mapOptions)
@icons.default =
path: google.maps.SymbolPath.CIRCLE
strokeColor: '#DD0000'
fillColor: '#DD0000'
fillOpacity: 0.6
scale:8
strokeWeight: 2
addMarker: (post) ->
gLatLng = new google.maps.LatLng post.location.lat, post.location.lng
gMarker = new google.maps.Marker
position: gLatLng
map: @map
icon: @icons.default
animation: google.maps.Animation.DROP
marker =
post: post
gMarker: gMarker
@markers.push marker
I suppose I could create a new map and attach all the markers to the new map, but this seems unnecessary because I may have many other overlays on the map
Upvotes: 1
Views: 1671
Reputation: 1236
It is not possible to attach the Map
object to another DOM element after the Map
object has been created. As you can see in the Google Maps Javascript API v3 Reference there is only a getDiv()
method available on the Map
, not a setDiv()
.
I think you could hold on to the other objects like Marker
and MapOptions
to recreate the Map
, but the Map
object itself is useless without the corresponding DOM element.
Upvotes: 2
Reputation: 2576
You can create a global variable, mapOptions, where you can store the options of the map. Whenever some interaction is done with the map, you can update the mapOptions objects, and save it to localstorage.
var mapOptions = {
...
};
localStorage.setItem("mapOptions", JSON.stringify(mapOptions));
map = new google.maps.Map(document.getElementById("map"), localStorage.getItem("mapOptions"));
Hope this helps!
Upvotes: 1