如果上一篇有了解的话,此篇只是单纯加上取得额外json后再进行地图点标注,未来可以依照需求更换想要的展示图案。
上一篇是用新增的方式慢慢加入style和layer,本篇是直接将layer和style都设定好,这样当我们加入feature到source中的时候,就可以直接渲染出来显示图案。
补充:新增feature的方式也有不同方法,可以透过geojson直接加入或是像这篇一个一个加入feature都是可以的。
// 建立空layerlet coffeeLayer = new ol.layer.Vector({ // 设定空source source: new ol.source.Vector(), // 设定此layer feature style style: new ol.style.Style({ image: new ol.style.Icon({ anchor: [0.5, 1], anchorXUnits: 'fraction', anchorYUnits: 'fraction', src: 'coffee.png', scale: 0.1 }), })});const map = new ol.Map({ layers: [ new ol.layer.Tile({ source: new ol.source.OSM() }), coffeeLayer // layer在这 ], 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: []});function getCoffeeData() { axios.get("coffee.json") .then((res) => { // 解构资料 let { data } = res; // 加入资料变成feature,注意座标转换 for (let i = 0; i < data.length; i++) { coffeeLayer.getSource().addFeature( new ol.Feature({ geometry: new ol.geom.Point( ol.proj.fromLonLat([ data[i]['longitude'], data[i]['latitude'] ]) ) }) ) } }) .catch((err) => { console.log(err) })}// 执行抓取API的function getCoffeeData();
成果如下图:
参考资料
https://github.com/weijung0923/learning-openlayers-micromastery/tree/day11