Openlayers+GeoServer导出地图图片及跨域问题

别说谁变了你拦得住时间么 提交于 2020-04-28 08:11:23

问题描述:

想用ol5.3实现地图的导出,Openlayers官网有实例,在这里就不写代码了。我自己的代码是加载了geoserver发布的图层,在导出时html页面后台提示错误:

SecurityError: The operation is insecure.

原因是:canvas导出图片时,涉及到跨域的问题,需将图层的crossOrigins设置为“anonymous”

例如:

var wmsSourceLucc = new ol.source.TileWMS({
    crossOrigin:'anonymous', //解决错误:SecurityError: The operation is insecure.
    url: mapWmsURL,
    params: {'LAYERS': luccLayerParams,tiled: true},
    serverType: 'geoserver'
});

这样能解决像引入的天地图、谷歌地图、百度地图、OSM地图等的SecurityError: The operation is insecure问题,但是新的问题又来了:自己用geoserver发布的图层又出现了下面的错误

CORS 头缺少 'Access-Control-Allow-Origin'

还是跨域的问题,查了很多技术文档,最终的解决方法是让用于发布geoserver的tomcat支持跨域。具体解决办法:
1、下载jar包
https://mvnrepository.com/artifact/com.thetransactioncompany/cors-filter/2.6
https://mvnrepository.com/artifact/com.thetransactioncompany/java-property-utils/1.9.1
2、将两个jar包拷贝至tomcat的lib文件夹中
3、配置tomcat的web.xml
<filter>
        <filter-name>CORS</filter-name>
        <filter-class>com.thetransactioncompany.cors.CORSFilter</filter-class>
        <init-param>
            <param-name>cors.allowOrigin</param-name>
            <param-value>*</param-value>
        </init-param>
        <init-param>
            <param-name>cors.supportedMethods</param-name>
            <param-value>GET, POST, HEAD, PUT, DELETE</param-value>
        </init-param>
        <init-param>
            <param-name>cors.supportedHeaders</param-name>
            <param-value>Accept, Origin, X-Requested-With, Content-Type, Last-Modified</param-value>
        </init-param>
        <init-param>
            <param-name>cors.exposedHeaders</param-name>
            <param-value>Set-Cookie</param-value>
        </init-param>
        <init-param>
            <param-name>cors.supportsCredentials</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>CORS</filter-name>
        <url-pattern>/*</url-pattern>
   </filter-mapping>

 

  
上面的代码放在welcome-file-list之前即可
  <
welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> </welcome-file-list>
4、重启tomcat
问题完美解决!
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!