openlayers 显示标记好的坐标点
今天由于特殊情况接触到这个新的 javascript 地图库,openlayers官网英文文档(脑袋疼)
废话不多说开搞!
我标注好的经纬度坐标为北京 ([116.3, 39.9])
- 首先要引入两个资源文件
<link
rel="stylesheet"
href="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v6.3.1/css/ol.css"
type="text/css"
/>
<script src="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v6.3.1/build/ol.js"></script>
- 创建一个有 id 属性的 div 存放地图 DOM 节点。(我后面发现好像一定要另外给一个 class 属性,添加一个样式,不然好像显示空白)
<div id="map" class="map"></div>
<style>
body {
margin: 0;
}
.map {
height: 100vh;
width: 100%;
}
</style>
- 接下来就是主体部分了,相当的复杂
<script type="text/javascript">
// 先 new 一个向量层
var layer = new ol.layer.Vector({
source: new ol.source.Vector(),
});
var map = new ol.Map({
layers: [
new ol.layer.Tile({
source: new ol.source.OSM(),
}),
// 把层放进 layers 数组中
layer,
],
target: "map",
view: new ol.View({
projection: "EPSG:4326",
center: [116.3, 39.9],
zoom: 4,
}),
});
// 创建和绘制一个 canvas 图案
var canvas = document.createElement("canvas");
canvas.width = 20;
canvas.height = 20;
var context = canvas.getContext("2d");
context.strokeStyle = "red";
context.lineWidth = 1;
context.beginPath();
context.moveTo(0, 0);
context.lineTo(20, 20);
context.lineTo(20, 0);
context.lineTo(0, 20);
context.lineTo(0, 0);
context.stroke();
// new style 样式
var style = new ol.style.Style({
image: new ol.style.Icon({
img: canvas,
imgSize: [canvas.width, canvas.height],
rotation: (90 * Math.PI) / 180,
}),
});
// new 一个功能,里面有一个点(北京的坐标点)
var shape = new ol.Feature({
geometry: new ol.geom.Point([116.3, 39.9]),
});
// 给这个点赋值上前面 new 的样式
shape.setStyle(style);
// 最后把加了样式之后的点(北京的坐标点)添加给 layer 层
layer.getSource().addFeature(shape);
</script>
- 显示结构如下: