官术网_书友最值得收藏!

  • Mastering OpenLayers 3
  • Gábor Farkas
  • 410字
  • 2021-07-16 09:33:50

Styling vector layers

You might or you might not be familiar with vector styling at this point. If you know about the concept, however, a little revision won't hurt. In this example, we will change the default vector style of the example dataset to green stars. As vector data is drawn directly to the canvas by the library, their styles can be changed only by inner methods with a limited set of values.

You can see a js file named ch02_vector in the code appendix. You can use this file with the previous example or extend the original one with the following rules:

var vectorLayer = new ol.layer.Vector({
    source: new ol.source.Vector({
        format: new ol.format.GeoJSON({
            defaultDataProjection: 'EPSG:4326'
        }),
        url: '../../res/world_capitals.geojson',
        attributions: [
            new ol.Attribution({
                html: 'World Capitals ? Natural Earth'
            })
        ]
    }),
    style: new ol.style.Style({
        image: new ol.style.RegularShape({
            stroke: new ol.style.Stroke({
                width: 2,
                color: [6, 125, 34, 1]
            }),
            fill: new ol.style.Fill({
                color: [25, 235, 75, 0.3]
            }),
            points: 5,
            radius1: 5,
            radius2: 8,
            rotation: Math.PI
        })
    })
});

In this simple style object, we define only a point symbolizer. It is a regular shape, which can be a simple, regular polygon. The polygon can be convex if it has only one radius value, and concave if it has two. Our star has five points and an outer radius of 8 pixels. The colors of its stroke, and fill, are expressed in RGBA values, which can be done by passing an array to their color parameter with four values. As the star will be upside down by default, we rotate it by 180 degrees The library only accepts radian values; thus, we have to rotate the star by π.

Tip

Using RGBA values is the only way to express opacity in vector styling. For regular styling with CSS, it is also a good practice as it takes fewer lines and all the major browsers support it.

Save the updated code, link it to the previous example, and open it up in your favorite browser. You should see the capitals represented by green stars:

Tip

We have only defined a symbolizer for point geometries in our style object. This means that the line and polygon symbolizers are set to null. If you use this style object on line, or polygon features, they would simply not render. To make general style objects for multiple geometry types, you have to provide at least a stroke style and a fill style besides image.

主站蜘蛛池模板: 赤城县| 涟水县| 保定市| 木兰县| 通化县| 永年县| 荃湾区| 嘉义市| 伊川县| 大余县| 定日县| 武隆县| 蕲春县| 集安市| 景泰县| 余江县| 肃南| 尖扎县| 正阳县| 建昌县| 汉源县| 文水县| 桂东县| 吉木乃县| 蕉岭县| 奇台县| 阿坝| 怀远县| 和平县| 西安市| 左权县| 阳朔县| 封开县| 望谟县| 中西区| 乌恰县| 香港 | 土默特右旗| 新建县| 武穴市| 漯河市|