谷歌地图 - 插入地图类型选择到div

时间:2015-07-22 02:37:57

标签: javascript google-maps google-maps-api-3

我有一张自适应地图,右侧有过滤器布局。

当地图采用移动设备尺寸时,此侧边栏会隐藏,并且所有过滤器都会被压缩。只需一个简单的按钮,我就可以显示和隐藏过滤器。

Maps

但我有一个问题。地图类型选择在我的过滤器div之外,我想把它隐藏起来。

我该怎么做?

1 个答案:

答案 0 :(得分:1)

基本上没有对DOMNode的基于API的访问,这些访问代表了内置控件。

但您可以尝试在文档中找到它们,目前此控件确实具有className gm-style-mtc,使用querySelector来查找它,并appendChild将其放在您想要的位置:

    //wait for the idle-event, it takes some time until the control
    //has been added to the document
    google.maps.event.addListenerOnce(mapInstance,'idle',function(){
      targetNode.appendChild(this.getDiv().querySelector('div.gm-style-mtc'));
    });

示例(您还需要为控件调整一些CSS设置):

      function initialize() {
        var map = new google.maps.Map(document.getElementById('map_canvas'), {
            zoom: 14,
            center: new google.maps.LatLng(52.549, 13.425),
            noClear: true,
            mapTypeControlOptions: {
              style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
            }
          }),
          bar = document.getElementById('sidebar');

        map.controls[google.maps.ControlPosition.RIGHT_TOP].push(bar);

        google.maps.event.addListenerOnce(map, 'idle', function() {
          document.getElementById('mtc')
            .appendChild(this.getDiv().querySelector('div.gm-style-mtc'));
        });
      }

      google.maps.event.addDomListener(window, 'load', initialize);
       html,
       body,
       #map_canvas {
         height: 100%;
         margin: 0;
         padding: 0
       }
       #sidebar {
         background: blue;
         padding: 6px;
         border-radius: 6px;
         color: #fff;
         position: absolute;
         top:40px !important;
       }
       #sidebar>* {
         display: none;
         font-size: 1.2em;
       }
       #sidebar.expanded>* {
         display: block !important;
       }
       #sidebar h3 {
         font-weight: bold;
         text-align: center;
         font-size: 1.5em;
         cursor: pointer;
         display: block !important;
         padding: 2px;
         margin: 2px;
       }
       #sidebar.expanded>h3:first-child {
         border-bottom: 1px solid #fff;
       }
       #sidebar #mtc {
         min-width: 120px;
         text-align: center;
         padding-bottom: 10px;
       }
       #sidebar #mtc>div {
         position: relative !important;
         display: inline-block !important;
       }
<script src="https://maps.googleapis.com/maps/api/js?v=3"></script>
<div id="map_canvas">
  <div id="sidebar">
    <h3 onclick="this.parentNode.className=(this.parentNode.className=='expanded')?'':'expanded'">☰&nbsp; Menú</h3>

    <strong>Filter#1</strong>
    <strong>Filter#2</strong>
    <strong>Filter#3</strong>
    <div id="mtc"></div>

  </div>
</div>

但我不建议,因为控件的标记不能保证稳定,当它们改变它时(例如修改className)它不再起作用。

您最好隐藏内置的MapTypeControl并创建自己的。