Search code examples
javascriptopenlayerskmlopenlayers-6

I can't display the KML


I am taking my first steps in openlayers, I find it quite interesting, but based on a simple example to show OSM it has been impossible for me to add a layer with a KML file and show it together.

I understand that I am close to achieving it and that is why I go to you, thanks in advance for any help.

My code is the following:

import 'ol/ol.css';
import { Map, View } from 'ol';
import TileLayer from 'ol/layer/Tile';
import VectorLayer from 'ol/layer/Vector';
import OSM from 'ol/source/OSM';
import KML from 'ol/format/KML';
import VectorSource from 'ol/source/Vector';



var openstreet = new TileLayer({
    source: new OSM()
})

var geomapa = new VectorLayer({
    source: new VectorSource({
        url: 'maps/kml/doc.kml',
        format: new KML()
    })
});


const map = new Map({
    target: 'map',
    layers: [openstreet, geomapa],
    view: new View({
        center: [0, 0],
        zoom: 0
    })
});

Solution

  • Solved!

    Although I am taking my first steps in openlayers using parcel, as the official documentation indicates, I must state that:

    1) If a kml file is published to an external server, the web server must be configured to tell the client that the resource is a KML file, therefore, these directives must be added to the server:

    Apache configuration

    2) Thinking that there was a bug in openlayers + parcel, I ran into the error

        Access to XMLHttpRequest at 'https://geo.anantara.cl/maps/kml/2012-02-10.kml' 
        from origin 'http://localhost:1234' has been blocked by CORS policy: 
        No 'Access-Control-Allow-Origin' header is present on the requested resource. 
    
    [http://localhost:1234/]
    Failed to load resource: net::ERR_FAILED [https://geo.anantara.cl/maps/kml/2012-02-10.kml]
    

    What means?, well it's necessary on my Apache server add the following code

     Header set Access-Control-Allow-Origin "http://127.0.0.1:1234"
    

    And now works.., I suggest that parcel document the posting of a kml file to an external server and how the CORS setting is enabled.