首页 > 其他分享 >[openlayers07]——加载天地图为底图并展示GeoJSON

[openlayers07]——加载天地图为底图并展示GeoJSON

时间:2023-02-07 20:12:39浏览次数:51  
标签:map 底图 const openlayers07 img GeoJSON ol new

[openlayers07]_加载天地图为底图并展示GeoJSON

1. 加载底图(得申请key)

天地图

image-20230207195245905

2. 创建地图、设置center和投影

// 创建地图
const center = [114.1692, 30.494]; //EPSG:4326
const view = new View({
  center: center, //EPSG:4326
   projection: 'EPSG:4326',
  zoom: 10
})
const map =new Map({
  target: 'map-container',
  view: view,
});

3. 以天地图为底图——影像底图(图层:img_w)

// 以天地图为底图——影像底图(地图瓦片获取)
let img_w_url = "http://t0.tianditu.gov.cn/img_w/wmts?" +
    "SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=img&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles" +
    "&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk=你的key";
let img_w = new TileLayer({
    source: new XYZ({
        url: img_w_url
    }) 
});
  • 记得替换key

4. 展示GeoJSON数据(图层:layerGeoJson)

// ---------------------------------
// 矢量源
const sourceGeoJson = new VectorSource({
  format: new GeoJSON(),
  url:'./data/hubei.geojson'
});
// 根据矢量源构建图层  layerGeoJson
const layerGeoJson = new VectorLayer({
  source:sourceGeoJson,
});

5. 将两个图层加入map

map.addLayer(img_w); //底图
map.addLayer(layerGeoJson); //由geojson数据构建的图层
  • 注意顺序

6. 效果

image-20230207195742375

完整代码:

main.js

import OSM from 'ol/source/OSM';
import XYZ from 'ol/source/XYZ';
import TileLayer from 'ol/layer/Tile';
import {Map, View} from 'ol';
import VectorLayer from 'ol/layer/vector';
import VectorSource from 'ol/source/Vector';
import GeoJSON from 'ol/format/GeoJSON.js';

// 创建地图
const center = [114.1692, 30.494]; //EPSG:4326
const view = new View({
  center: center, //EPSG:4326
   projection: 'EPSG:4326',
  zoom: 10
})
const map =new Map({
  target: 'map-container',
  view: view,
});

// 以天地图为底图——影像底图(地图瓦片获取)
let img_w_url = "http://t0.tianditu.gov.cn/img_w/wmts?" +
    "SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=img&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles" +
    "&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk=xxxx";
let img_w = new TileLayer({
    source: new XYZ({
        url: img_w_url
    }) //
});
// ---------------------------------
// 矢量源
const sourceGeoJson = new VectorSource({
  format: new GeoJSON(),
  url:'./data/hubei.geojson'
});
// 根据矢量源构建图层  layerGeoJson
const layerGeoJson = new VectorLayer({
  source:sourceGeoJson,
});


map.addLayer(img_w); //底图
map.addLayer(layerGeoJson); //由geojson数据构建的图层

index.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>OpenLayers</title>
    <style>
      @import "node_modules/ol/ol.css";
    </style>
    <style>
      html, body, #map-container {
        margin: 0;
        height: 100%;
        width: 100%;
        font-family: sans-serif;
      }
    </style>
  </head>
  <body>
    <div id="map-container"></div>
    <script src="./main.js" type="module"></script>
  </body>
</html>

标签:map,底图,const,openlayers07,img,GeoJSON,ol,new
From: https://www.cnblogs.com/aleza/p/17099655.html

相关文章