【Day11】Openlayers从入门到微精通 - Show出你喜爱的咖啡厅位置

如果上一篇有了解的话,此篇只是单纯加上取得额外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();

成果如下图:
http://img2.58codes.com/2024/201654872mQY3uhaRw.png

参考资料

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


关于作者: 网站小编

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

热门文章