原文链接及内容
WMS支持getLegendGraphic请求 。此示例演示了getLegendUrl
方法的使用。
由于图例可以响应比例(尺),因此每当分辨率变化时都会更新图例。
main.js
代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 import ImageWMS from 'ol/source/ImageWMS.js' ;import Map from 'ol/Map.js' ;import OSM from 'ol/source/OSM.js' ;import View from 'ol/View.js' ;import {Image as ImageLayer , Tile as TileLayer } from 'ol/layer.js' ;const wmsSource = new ImageWMS ({ url : 'https://ahocevar.com/geoserver/wms' , params : {'LAYERS' : 'topp:states' }, ratio : 1 , serverType : 'geoserver' , }); const updateLegend = function (resolution ) { const graphicUrl = wmsSource.getLegendUrl (resolution); const img = document .getElementById ('legend' ); img.src = graphicUrl; }; const layers = [ new TileLayer ({ source : new OSM (), }), new ImageLayer ({ extent : [-13884991 , 2870341 , -7455066 , 6338219 ], source : wmsSource, }), ]; const map = new Map ({ layers : layers, target : 'map' , view : new View ({ center : [-10997148 , 4569099 ], zoom : 4 , }), }); const resolution = map.getView ().getResolution ();updateLegend (resolution);map.getView ().on ('change:resolution' , function (event ) { const resolution = event.target .getResolution (); updateLegend (resolution); });
界面布局文件index.html
代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 <!DOCTYPE html > <html lang ="en" > <head > <meta charset ="UTF-8" > <title > WMS GetLegendGraphic</title > <link rel ="stylesheet" href ="node_modules/ol/ol.css" > <style > .map { width : 100% ; height : 400px ; } </style > </head > <body > <div id ="map" class ="map" > </div > Legend: <div > <img id ="legend" /> </div > <script src ="https://cdn.jsdelivr.net/npm/elm-pep@1.0.6/dist/elm-pep.js" > </script > <script type ="module" src ="main.js" > </script > </body > </html >