这几天我一直在尝试让Openlayers和我的Django网站一起工作。我对Web完全是个新手,所以我可能会错过一些我还不能理解的直接的东西。
据我所知,我需要加载Openlayers,因此在我的 index.html
,我已经加入了 <head>
这个..:
<script src="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v6.3.1/build/ol.js"></script>
然后在 <body>
我已经加了 index.js
我想用openlayers工作。
<script src="{% static 'index.js'%}"></script>
我把一个简单的例子复制粘贴到了 index.js
而它一直在正常工作。
var map = new ol.Map({
target: 'map',
layers: [
new ol.layer.Tile({
source: new ol.source.OSM()
})
],
view: new ol.View({
center: ol.proj.fromLonLat([2.333333, 48.866667]),
zoom: 10
})
});
所以我有一张以巴黎为中心的地图。现在我想加载一个 GeoJson
文件,因此我需要添加一个包含GeoJon的Layer。为此,我按照一个例子 此处.
这是我的第一个问题,我试着像这样导入。import GeoJSON from 'ol/format/GeoJSON';
或者像这样 import Style from ol.style.Style
位,我得到了这个错误。Uncaught SyntaxError: Cannot use import statement outside a module
我找到的唯一解决办法是 new ol.style.Style(...)
当我需要使用它。很丑,但能用。
所以我已经删除了所有的导入,并使用每个类的完整路径来调用构造函数。直到其中一个类无法工作。
var vectorLayer = new ol.layer.Vector.VectorLayer({
source: new ol.source.Vector.VectorSource({
url: 'data/geojson/countries.geojson',
format: new ol.format.GeoJSON()
}),
style: function(feature) {
style.getText().setText(feature.get('name'));
return style;
}
});
未捕获的TypeError:ol.source.Vector.VectorSource不是构造函数。
https:/openlayers.orgenlatestapidocmodule-ol_source_Vector-VectorSource.html。
所以我在问我自己,为什么不能用,怎么可能让它不那么丑陋(用Imports)?
var vectorLayer = new ol.layer.Vector({
source: new ol.source.Vector({
你可以查看OpenLayers 4的例子。https:/openlayers.orgenv4.6.5examples。 以获得完整的构建语法