问题描述
在我复制的以下代码中:
https://openlayers.org/workshop/en/vector/geojson.html
如下图,需要url:
url: './data/countries.json'
当我运行代码时,没有地图只出现加号和减号,用于放大和缩小深蓝色背景 请让我知道如何找到国家/地区 .json
代码:
const map = new Map({
target: 'map-container',layers: [
new VectorLayer({
source: new VectorSource({
format: new GeoJSON(),url: './data/countries.json'
})
})
],view: new View({
projection: 'epsg:4326',center: [13.063561,52.391842],zoom: 2
})
});
尝试:
const vectorLayer = new VectorLayer({
source: new VectorSource({
url: './data/countries.geojson',format: new GeoJSON(),defaultProjection :'epsg:4326',projection: 'epsg:3857'
})
})
const map = new Map({
target: 'map-container',layers: [vectorLayer],center: [0,0],zoom: 2
})
});
sync(map)
也试过了
countries.json
.geojson
.geo.json
但什么都没有显示
解决方法
为了使此代码正常工作,我已完成以下操作:
我在 ubuntu 上工作并且我按照说明操作 https://openlayers.org/workshop/en/ .
我从研讨会下载了文件夹 https://github.com/openlayers/workshop/releases/download/v6.0.0-beta.en.4/openlayers-workshop-en.zip 并将其解压缩。
我进入解压后的文件夹并运行“npm install”。
我在 index.html 文件中写了
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>OpenLayers</title>
<style>
html,body,#map-container {
margin: 0;
height: 100%;
width: 100%;
font-family: sans-serif;
background-color: #04041b;
}
</style>
</head>
<body>
<div id="map-container"></div>
</body>
</html>
main.js
import 'ol/ol.css';
import GeoJSON from 'ol/format/GeoJSON';
import Map from 'ol/Map';
import VectorLayer from 'ol/layer/Vector';
import VectorSource from 'ol/source/Vector';
import View from 'ol/View';
new Map({
target: 'map-container',layers: [
new VectorLayer({
source: new VectorSource({
format: new GeoJSON(),url: './data/countries.json'
})
})
],view: new View({
center: [0,0],zoom: 2
})
});
您可以在根目录下运行“npm start”,它就会起作用。
对于完整的教程,我完成了以下操作
在目录的根目录我运行命令'npm install ol-hashed'。
我替换了 main.js 中的代码
import 'ol/ol.css';
import GeoJSON from 'ol/format/GeoJSON';
import Map from 'ol/Map';
import VectorLayer from 'ol/layer/Vector';
import VectorSource from 'ol/source/Vector';
import View from 'ol/View';
import sync from 'ol-hashed';
const map = new Map({
target: 'map-container',zoom: 2
})
});
sync(map);
运行“npm start”,它就会工作。
现在如果您想使用 geojson 的 url,您需要原始数据的链接。
在这种情况下,我使用了 https://raw.githubusercontent.com/openlayers/workshop/master/src/en/data/countries.json
和更改我在 main.js 中的代码
import 'ol/ol.css';
import GeoJSON from 'ol/format/GeoJSON';
import Map from 'ol/Map';
import VectorLayer from 'ol/layer/Vector';
import VectorSource from 'ol/source/Vector';
import View from 'ol/View';
import sync from 'ol-hashed';
const map = new Map({
target: 'map-container',url: 'https://raw.githubusercontent.com/openlayers/workshop/master/src/en/data/countries.json' // here is the link
})
})
],zoom: 2
})
});
sync(map);
如果地图没有显示,则表示 'url' 中的参数是错误的。 如果有错误,您可以在浏览器控制台中检查。