KML 图像来自没有 Access_Control_Allow_Origin header 的来源

KML with image that from source that does not have Access_Control_Allow_Origin header

我正在使用 openlayers 并尝试在 IIS 托管的 Web 应用程序上的地图中显示 KML。我使用的 KML 示例是:

<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://www.opengis.net/kml/2.2">
   <Document>
      <name>Test CORS KML</name> 
      <Style id="badCors">
         <IconStyle>
            <color>ff589d0f</color>
            <scale>1</scale>
            <Icon><href>https://www.gstatic.com/mapspro/images/stock/1415-rec-winter-snow.png</href>
            </Icon>
         </IconStyle>
      </Style>
      <Placemark>
         <name>Bad Mark</name>
         <styleUrl>#badCors</styleUrl>
         <Point>
            <coordinates>4.3849582,50.9757646,0</coordinates>
         </Point>
      </Placemark>
   </Document>
</kml>

但是这不起作用,我收到错误消息:

Access to image at 'https://www.gstatic.com/mapspro/images/stock/1415-rec-winter-snow.png' from origin 'http://localhost' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

如果我更改 kml 以便图像使用 url https://maps.google.com/mapfiles/kml/shapes/snowflake_simple.png ,它显示正常,没有任何问题。

我正在尝试了解如何使用 url 重写将 'Access-Control-Allow-Origin' 添加到 first/bad link,但我正在尝试的任何方法都不起作用. https://kamranicus.com/posts/2016-03-06-cors-multiple-origins-iis seemed promising, but it hasn't worked for me. if i use an extension like https://mybrowseraddon.com/access-control-allow-origin.html,这解决了问题,但这并不是我的情况的真正解决方案。

在 openlayers 中显示未针对 CORS 设置的 KML 图像的最佳方式是什么?

您可能需要在您的服务器上使用一个简单的代理来绕过 CORS,并且您的 OpenLayers 源设置将需要一个加载器(没有 bbox 策略,因此是 https://openlayers.org/en/latest/apidoc/module-ol_source_Vector-VectorSource.html 中的一个简化版本)在 href url 前加上您的代理

var vectorSource = new Vector({
  format: new KML(),
  loader: function() {
     var url = 'your-kml.kml;
     var xhr = new XMLHttpRequest();
     xhr.open('GET', url);
     xhr.onload = function(extent, resolution, projection) {
       if (xhr.status == 200) {
         var text = xhr.responseText.replace(
           /\<href\>http/gi,
           '<href>yourproxy?http'
         );
         vectorSource.addFeatures(
           vectorSource.getFormat().readFeatures(text, {
             dataProjection: 'EPSG:4326',
             featureProjection: projection
           })
         );
       }
     }
     xhr.send();
   },
 });