map does not expand to full size on load when usin

2019-08-02 21:35发布

问题:

I have a Leaflet map on a page that uses jQuery mobile. I experience a similar problem if I swap in a Google Map instead of Leaflet, so I don't believe this to be specific to Leaflet but rather to jQuery mobile.

The problem is that when it first loads, the background imagery of the map does not expand to fit the size of the div that contains it.

See http://jsfiddle.net/Lxotwbrk/2/

See that the red border is the correct size, but the map imagery is missing in the grey area. Note that as soon as you adjust the height or width of the result window on the jsfiddle page (or the full browser window if running on localhost), the background imagery immediately fills the canvas.

I have perused and tried suggestions from similar threads but haven't had luck. If I put the map on a page without JQM, I don't have this issue.

Here is the code. Thanks in advance.

<!DOCTYPE html>
<html>
  <head>
    <title>no title needed</title>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"
      type="text/javascript">
    </script>

    <link rel="stylesheet"
      href="//ajax.googleapis.com/ajax/libs/jquerymobile/1.4.3/jquery.mobile.min.css" />
    <script src="//ajax.googleapis.com/ajax/libs/jquerymobile/1.4.3/jquery.mobile.min.js"></script>

   <link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.css" />
    <script src="http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.js"></script>   

    <style>
      html, body {
        height: 100%;
        margin: 0px;
        padding: 0px
      }

      /*this holds the map canvas*/
      .ui-content {
        position: absolute;
        top: 20px;
        left: 0px;
        right: 0px;
        bottom: 20px;
        width: 100%;
        padding: 0px;
        border: 1px solid red;
      }

      #map-canvas {
        height: 100%;
      }

    </style>

    <script type="text/javascript">
      $(document).on("pagecontainershow", function(event, ui) {
        var map = new L.Map('map-canvas', {
          center: [42.3, -71],
          zoom: 7
        });

        L.tileLayer('http://tiles1-4001b3692e229e3215c9b7a73e528198.skobblermaps.com/TileService/tiles/2.0/00021210101/0/{z}/{x}/{y}.png', {
          attribution: 'Skobbler'
        }).addTo(map);


      });

    </script>
  </head>
  <body>
    <div data-url="map-page" data-role="page" id="map-page" data-title="JQM's title">      
      <div role="main" class="ui-content">
        <div id="map-canvas"></div>
      </div><!-- /content -->
    </div>
  </body>
</html>

回答1:

Your #map-canvas is wrapped with div's. They must all allow to expand the height to 100%.

Correct your JSFiddle with this ...

html, body, #map-page, #map-canvas {
    height: 100%;
    margin: 0px;
    padding: 0px
}