简体   繁体   中英

Rendering same Google Map twice on one page

I'm working on a Rails app that uses CSS 'tabs' to separate a form. I need to render the same google map in two of the tabs, but the map is only being appended to the first #map_canvas div. What I have currently:

# form.html.erb

<div class='tabs'>
  <div id='tab1'>
    <div class="map container">
      <div id="map_canvas"></div>
    </div>
  </div>
  <div id='tab2'>
    <div class="map container">
      <div id="map_canvas"></div>
    </div>
  </div>
</div>

# map.js

map = new google.maps.Map(document.getElementById("map_canvas"),mapOptions);

My first attempt was to render the map in a partial, and reference that twice, but it had the same effect.

Is there a way to do this properly?

An id should be unique within a page, you have used 'map_canvas' twice in the page. Instead of using Id you can try with class

 <div class='tabs'>
  <div id='tab1'>
    <div class="map container">
      <div class="map_canvas"></div>
    </div>
  </div>
  <div id='tab2'>
    <div class="map container">
      <div class="map_canvas"></div>
    </div>
  </div>
</div>

#js
 map = new google.maps.Map(document.getElementsByClassName("map_canvas"),mapOptions);
<div class='tabs'>
  <div id='tab1'>
    <div class="map container">
      <div class="map_canvas"></div>
    </div>
  </div>
  <div id='tab2'>
    <div class="map container">
      <div class="map_canvas"></div>
    </div>
  </div>
</div>

map.js

map1 = new google.maps.Map(document.getElementsByClassName("map_canvas")[0],mapOptions);
map2 = new google.maps.Map(document.getElementsByClassName("map_canvas")[1],mapOptions);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM