使用Openlayers 3
实现调用本地json
数据在地图上添加点、文字标注以及连线。
首先得有一个地图作为底图,代码如下:
let vectorSource = new ol.source.Vector({ wrapX: false }); const rootLayer = new ol.layer.Tile({ source: new ol.source.TileImage({ url: 'http://mt2.google.cn/vt/lyrs=y&hl=zh-CN&gl=CN&src=app&x={x}&y={y}&z={z}&s=G' }) //加载谷歌影像地图 }); const vectorLayer = new ol.layer.Vector({ source: vectorSource }) const center = ol.proj.fromLonLat([91.29638423, 28.90222228], 'EPSG:3857'); const map = new ol.Map({ target: 'map', renderer: 'canvas', layers: [rootLayer, vectorLayer], view: new ol.View({ center: center, zoom: 9 }) })
使用ajax
加载本地json
数据
const url = './data/data.json'; window.onload = () => { $.ajax({ url: url, dataType: 'json', success: res => { let features = res.features; let coordsArray = features.map(obj => { let pointTransform = ol.proj.transform([obj[0][0], obj[0][1]], 'EPSG:4326', 'EPSG:3857'); return pointTransform; }) console.log(coordsArray); for(let i = 0; i < features.length; i++) { let coords = features[i][0]; // 坐标 let mark = features[i][1]; let pointId = mark + 'pointId'; //文字 let point = ol.proj.fromLonLat(coords); // 多边形封闭 let plygonfeature = new ol.Feature({ geometry: new ol.geom.Polygon([coordsArray]) }); plygonfeature.setStyle(new ol.style.Style({ fill: new ol.style.Fill({ color: 'transparent' }), stroke: new ol.style.Stroke({ 2, color: [255, 255, 0, 0.8] }), })) vectorLayer.getSource().addFeature(plygonfeature); // 文字标注 let anchorValue = new ol.Feature({ geometry: new ol.geom.Point(point) }) anchorValue.setStyle(new ol.style.Style({ text: new ol.style.Text({ font: '15px Microsoft YaHei', text: mark, offset: [30, 0], fill: new ol.style.Fill({ color: '#fff' }) }), image: new ol.style.Circle({ radius: 2, snapToPixel: false, fill: new ol.style.Fill({ color:'#333' }), stroke: new ol.style.Stroke({ color: '#333' }) }) })) vectorLayer.getSource().addFeature(anchorValue); } } }) }