TransWikia.com

Loading GeoJSON in OpenLayers?

Geographic Information Systems Asked by MatixCraft MatixCraft on June 14, 2021

I am trying to load GeoJSON in OpenLayers, however, the polygon isn’t visible on the map. What am I doing wrong?

<!doctype html>
<html lang="en">
  <head>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v6.3.1/css/ol.css" type="text/css">
    <style>
      .map {
        height: 100%;
        width: 100%;
        position: fixed;
      }
    </style>
    <script src="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v6.3.1/build/ol.js"></script>
    <title>Gminy</title>
  </head>
  <body>
    <div id="map" class="map"></div>
    <script type="text/javascript">
      var map = new ol.Map({
        target: 'map',
        layers: [
          new ol.layer.Tile({
            source: new ol.source.OSM()
          })
        ],
        view: new ol.View({
          center: ol.proj.fromLonLat([18, 53]),
          zoom: 10
        })
      });
      var urlGminy = 'map.geojson';
      var warstwaGminy = new ol.layer.Vector({
          source: new ol.source.Vector({
              url: urlGminy,
              format: new ol.format.GeoJSON()
          })
      });
      map.addLayer(warstwaGminy);
    </script>
  </body>
</html>

One Answer

You aren't doing it wrong, your code is correct. The only problem is that you are trying to access your webpage this way: file:///C:/.....

As said in the comments, most browsers don't allow xhr requests to your local file system. One solution is to install a web server and access your webpage from there, like this: http://localhost/....

The other thing you can do, is to use a browser which allows xhr requests, like Edge.

Answered by imre on June 14, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP