[GIS] OpenLayers Display KML Layer

kmlopenlayers

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>

Best Answer

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.

Related Question