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

  • 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.

主站蜘蛛池模板: 宜阳县| 莒南县| 江安县| 陆丰市| 新竹市| 安龙县| 安岳县| 胶州市| 诸城市| 叙永县| 平山县| 丹寨县| 双鸭山市| 昌邑市| 遂宁市| 诸暨市| 随州市| 黄龙县| 衢州市| 赤壁市| 武定县| 普陀区| 浦江县| 景德镇市| 绍兴县| 东阿县| 龙陵县| 延边| 香港 | 喜德县| 辽阳县| 诏安县| 山东省| 将乐县| 克什克腾旗| 民县| 安溪县| 秀山| 贵南县| 城市| 乡宁县|