GeoJSON
OpenLayers 支持加载和显示 GeoJSON 格式的地理数据。GeoJSON 是一种基于 JSON 的地理数据格式,可以表示点、线、面等几何要素。
示例
代码实现
vue
<template>
<div id="map" class="w-full h-96"></div>
</template>
<script setup>
import { onMounted } from "vue";
import "ol/ol.css";
import Map from "ol/Map";
import View from "ol/View";
import TileLayer from "ol/layer/Tile";
import XYZ from "ol/source/XYZ";
import VectorLayer from "ol/layer/Vector";
import VectorSource from "ol/source/Vector";
import Feature from "ol/Feature";
import Point from "ol/geom/Point";
import GeoJSON from "ol/format/GeoJSON";
import { fromLonLat } from "ol/proj";
import { Style, Fill, Stroke, Circle } from "ol/style";
onMounted(() => {
// 创建地图
const map = new Map({
target: "map",
view: new View({
center: fromLonLat([117.33083, 39.094899]), // 天津
zoom: 4,
}),
});
// 添加天地图图层
const tdtLayer = new TileLayer({
source: new XYZ({
url: "http://t0.tianditu.gov.cn/vec_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=vec&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk=d32c6748c80f81a44acd8633cea41dfd",
}),
});
map.addLayer(tdtLayer);
// GeoJSON 数据
const geojsonFeature = {
type: "Feature",
properties: {
name: "Point",
},
geometry: {
type: "Point",
coordinates: [117.33083, 39.094899],
},
};
// 添加 GeoJSON 点要素
const pointSource = new VectorSource({
features: [
new Feature({
geometry: new Point(fromLonLat(geojsonFeature.geometry.coordinates)),
}),
],
});
const pointLayer = new VectorLayer({
source: pointSource,
style: new Style({
image: new Circle({
radius: 10,
fill: new Fill({
color: "rgba(255, 0, 0, 0.5)",
}),
stroke: new Stroke({
color: "red",
width: 2,
}),
}),
}),
});
map.addLayer(pointLayer);
// 添加 FeatureCollection 多边形
const featureCollections = {
type: "FeatureCollection",
features: [
{
type: "Feature",
properties: { name: "polygon1" },
geometry: {
type: "Polygon",
coordinates: [
[
[117.32248306274415, 39.107827920205374],
[117.31578826904298, 39.09291571258751],
[117.33707427978517, 39.083593981163304],
[117.35578536987306, 39.09584514515822],
[117.34857559204103, 39.11022423079904],
[117.32248306274415, 39.107827920205374],
],
],
},
},
],
};
const polygonSource = new VectorSource({
features: new GeoJSON().readFeatures(featureCollections, {
featureProjection: "EPSG:3857",
dataProjection: "EPSG:4326",
}),
});
const polygonLayer = new VectorLayer({
source: polygonSource,
style: new Style({
stroke: new Stroke({
color: "blue",
width: 2,
}),
fill: new Fill({
color: "rgba(0, 0, 255, 0.1)",
}),
}),
});
map.addLayer(polygonLayer);
// 定位到多边形区域
map.getView().fit(polygonSource.getExtent(), {
padding: [50, 50, 50, 50],
});
});
</script>
<style scoped>
.w-full {
width: 100%;
}
.h-96 {
height: 24rem;
}
</style>