【Day10】Openlayers从入门到微精通 - 换上喜欢的样式(点)

官网範例
https://openlayers.org/en/latest/examples/icon.html

範例中我们可以很清楚的看到openlayers的阶层,如果我们要加入一个点(feature),需要放到source里面

layersourcefeature (阵列)

如同上面的层级,把需要放入的feature放到对的地方,同时注意它放入的物件,如此一来就可以有点在地图上面显示,但此範例中还特别展示了另一个功能,就是我们可以自定义ICON样式,透过url的方式去指定。

JS

注意阶层、顺序、物件格式

const map = new ol.Map({    layers: [        new ol.layer.Tile({            source: new ol.source.OSM()        })    ],    target: 'map',    view: new ol.View({        projection: "EPSG:3857",        center: ol.proj.fromLonLat([120.846642, 23.488793]),        zoom: 7.5,        maxZoom: 20,        minZoom: 5,        enableRotation: false,    }),    controls: []});// 新增feature物件const iconFeature = new ol.Feature({    geometry: new ol.geom.Point(ol.proj.fromLonLat([121, 23.5])),    name: 'Null Island',    population: 4000,    rainfall: 500,});// 设定点的样式const iconStyle = new ol.style.Style({    image: new ol.style.Icon({        // 注意,如果你想要让图案尖尖的点在正确位置的话可以依据下方设定,Unit设定成fraction与anchor设定为0.5, 1        // https://openlayers.org/en/latest/apidoc/module-ol_style_Icon-Icon.html        anchor: [0.5, 1],        anchorXUnits: 'fraction',        anchorYUnits: 'fraction',        src: 'http://img2.58codes.com/2024/icon.png',    }),});// 设定style到指定的featureiconFeature.setStyle(iconStyle);// 建立一个source物件且放入点(feature)const vectorSource = new ol.source.Vector({    features: [iconFeature],});// 建立一个layer物件且放入对应的sourceconst vectorLayer = new ol.layer.Vector({    source: vectorSource,});// 最终,把此layer加入到地图中map.addLayer(vectorLayer);

参考

https://github.com/weijung0923/learning-openlayers-micromastery/tree/day10


关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章