Search code examples
leafletmapsopenlayerspython-sphinxrestructuredtext

Embedding an OpenLayers slippy map into Sphinx reStructuredText page


I want to embed a slippy map into my sphinx page.

I'm trying this simple example: https://wiki.openstreetmap.org/wiki/OpenLayers_Marker_Example

So my rst document is:

.. raw:: html

   <body>
      <div id="mapdiv"></div>
      <script src="http://www.openlayers.org/api/OpenLayers.js"></script>
      <script>
         map = new OpenLayers.Map("mapdiv");
         map.addLayer(new OpenLayers.Layer.OSM());

         var lonLat = new OpenLayers.LonLat( -0.1279688 ,51.5077286 )
               .transform(
                  new OpenLayers.Projection("EPSG:4326"), // transform from WGS 1984
                  map.getProjectionObject() // to Spherical Mercator Projection
               );
               
         var zoom=16;

         var markers = new OpenLayers.Layer.Markers( "Markers" );
         map.addLayer(markers);
         
         markers.addMarker(new OpenLayers.Marker(lonLat));
         
         map.setCenter (lonLat, zoom);
      </script>
   </body>

But nothing appears on the page.

I have tried and failed trying to use other javascript mapping api's such as leaflet but with no luck. I'm new to using sphinx/reStructuredText so maybe there's something obivous I am missing?


Solution

    1. <body> already exists on your page, so you need to remove it from your rst.

    2. You also need to specify height and width for the mapdiv element, for instance, something like this:

      .. raw:: html
      
           <div id="mapdiv" style="height: 200px; width: 100%"></div>
           <script src="http://www.openlayers.org/api/OpenLayers.js"></script>
           <script>
           map = new OpenLayers.Map("mapdiv");
           map.addLayer(new OpenLayers.Layer.OSM());
      
           var lonLat = new OpenLayers.LonLat( -0.1279688 ,51.5077286 )
             .transform(
               new OpenLayers.Projection("EPSG:4326"), // transform from WGS 1984
               map.getProjectionObject() // to Spherical Mercator Projection
             );
      
           var zoom=16;
      
           var markers = new OpenLayers.Layer.Markers( "Markers" );
           map.addLayer(markers);
      
           markers.addMarker(new OpenLayers.Marker(lonLat));
      
           map.setCenter (lonLat, zoom);
           </script>