1

I am trying to display my KML file with OpenLayers and I cannot get it to work...

I just want to simply display my KML layer on the basic map.

Here is the code I came up with:

<!doctype html>
<html lang="en">
  <head>
    <link rel="stylesheet" href="https://openlayers.org/en/v4.6.4/css/ol.css" type="text/css">
    <style>
      .map {
        height: 500px;
        width: 70%;
      }
    </style>
    <script src="https://openlayers.org/en/v4.6.4/build/ol.js" type="text/javascript"></script>
    <title>OpenLayers example</title>
  </head>
  <body>
    <b>Mountains</b>
    <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()
          })
        ],
      });

      var vector = new ol.layer.Vector({
        source: new ol.source.Vector({
          url: 'https://gis6370.com/woznick/MountainPeaks.kml',
          format: new ol.format.KML()
        })
      });
        view: new ol.View({
          center: ol.proj.fromLonLat([-73.9235, 44.1126]),
          zoom: 1
        })
      });
    </script>
  </body>
</html>
2
  • Does the map show for you? but the KMl not?. Did you get an error when debugging your code?
    – Moh
    Feb 25, 2018 at 1:32
  • @Kelly5432, Do you solve the problem of opening local KML file?
    – Cloud Cho
    Oct 11, 2019 at 19:00

1 Answer 1

1

Your javascript side should be

    var map = new ol.Map({
    target: 'map',
    layers: [
      new ol.layer.Tile({
        source: new ol.source.OSM()
      }),
      new ol.layer.Vector({
    source: new ol.source.Vector({
      url: 'http://gis6370.com/woznick/MountainPeaks.kml',
      format: new ol.format.KML()
    })
  })
    ],
    view: new ol.View({
      center: ol.proj.fromLonLat([-73.9235, 44.1126]),
      zoom: 1
    })
  });

and put your kml file in project, because it does not pass the cross-origin policy.

1
  • I tried the same option but ya It's giving the cross-origin policy issue. Kindly you kindly explain how can I put kml file in project. As the data is directly coming from local drive i.e. F or D drive etc. Jul 22, 2020 at 8:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.