Search code examples
javascriptopenlayers

Map is not showing


I have a map with openlayers with OSM. I can not see the map. It worked before, but suddenly it do not work. When I use the simplest setup for just showing a map it works.

I have tried some different things like destructure and look over the code. I use CDN for CSS and js.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://cdn.rawgit.com/openlayers     /openlayers.github.io/master/en/v5.3.0/css/ol.css" type="text/css">
<script src="https://cdn.rawgit.com/openlayers/openlayers.github.io/master/en/v5.3.0/build/ol.js"></script>
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<style>
        .map {
          height: 400px;
          width: 100%;
        }
        
        #header {
            text-align: center;
        }
      </style>
  <title>Open Layers testing</title>
</head>
<body>
<h2>My Map</h2>
<header>
    <div id="header">
    <button id="flyttkanpp" onclick="flytt()">Flytt 300 meter</button>
    </div>
</header>
<div id="map" class="map"></div>
<script type="text/javascript">

    
    var baseMapLayer = new ol.layer.Tile({
        source: new ol.source.OSM()
    });
    var map = new ol.Map({
        target: 'map',
        view: view,
        layer: [layer]
    });
    var view = new ol.View({
      center: center,
      zoom: 6
    });
    var center = ol.proj.fromLonLat([37.41, 8.82]);
    var layer = new ol.layer.Tile({
      source: new ol.source.OSM()
    });
    var featureMarker = new ol.Feature({
        geometry: new ol.geom.Point(
        ol.proj.fromLonLat([10.7461, 59.9127])
        )  // Cordinates of Netsense Skien
    });
    function flytt() {
        featureMarker.getGeometry().translate(0, 100);
    };

    var vectorSource = new ol.source.Vector({
        features: [featureMarker]
    });

    var markerVectorLayer = new ol.layer.Vector({
        source: vectorSource,
    });

    map.addLayer(markerVectorLayer);

    //Set custom marker

    featureMarker.setStyle(new ol.style.Style({
        image: new ol.style.Icon(({
            scale: 0.5,
            opacity: 0.75,
            crossOrigin: 'anonymous',
            src: 'location.png'
        }))
    }));
    
  </script>
</body>
</html>

I have a onclick function too. Which has been working, but now the map is not showing.


Solution

  • You should reorder your code. map uses layer and view (which uses center) so they need to be declared before it.

    Also: layer needs to be layers.

    var center = ol.proj.fromLonLat([37.41, 8.82]);
    
    var view = new ol.View({
      center: center,
      zoom: 6
    });
    
    var layer = new ol.layer.Tile({
      source: new ol.source.OSM()
    });
    
    var map = new ol.Map({
      target: 'map',
      layers: [layer],
      view: view
    });
    

    Working copy