【问题标题】:Error importing OpenLayers modules when run from HTML从 HTML 运行时导入 OpenLayers 模块时出错
【发布时间】:2021-02-13 16:00:34
【问题描述】:

我正在尝试复制 this small tutorial 来学习 Openlayers,但即使我直接复制并粘贴代码,也会遇到问题。

我遇到的第一个问题是 index.html。浏览器返回“Uncaught SyntaxError: Cannot use import statement outside a module”。所以,我在 index.html 中添加了“type='module'”,解决了这个问题。

但是,然后我收到一条错误消息,指出“Uncaught TypeError: Failed to resolve module specifier 'ol/ol.css'. Relative references must start with either "/'...”。我在 ./ol 中解压了 OpenLayers 文件,所以我只是将该路径添加到导入中,所以它们看起来像 import './ol/ol.css'import './ol/ol/Map'

现在,我收到“GET http://{myserverip}/Map/ol/ol/Map net::ERR_ABORTED 404 (Not Found)”的错误提示

当从 html 文件运行 javascript 时,如何正确导入 javascript 模块?我是不是完全走错了路?

javascript 导入:

import './ol/ol.css';
import Map from './ol/ol/Map';
import OSM from './ol/ol/source/OSM';
import TileLayer from './ol/ol/layer/Tile';
import TileWMS from './ol/ol/source/TileWMS';
import View from './ol/ol/View';

index.html 文件:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>Tiled WMS</title>
    <!-- Pointer events polyfill for old browsers, see https://caniuse.com/#feat=pointer -->
    <script src="https://unpkg.com/elm-pep"></script>
    <style>
      .map {
        width: 100%;
        height:400px;
      }
    </style>
  </head>
  <body>
    <div id="map" class="map"></div>
    <script type="module" src="main.js"></script>
  </body>
</html>

需要注意的是,ol目录只包含ol.css、ol.css.map、ol.js、ol.js.map。 JavaScript 可以像那样从 ol/layer/Tile 导入 TileLayer(ol 是 ol.js 文件吗?)。

【问题讨论】:

  • 你在使用一些构建系统吗?从示例链接中,他们有一个 package.json 将捆绑 javascript。
  • 我不是。我刚刚从他们的网站下载了文件。
  • 可能与this有关。您可能需要一些捆绑程序来解决您的导入问题。 Try these steps.
  • 就是这样!谢谢!我不习惯这种发展,所以我做错了。

标签: javascript html openlayers


【解决方案1】:

您正在使用模块系统。这将无法在浏览器上运行。

我认为您正在尝试使用 ES5 (vanilla) javascript。 为此,请使用此示例。我想它会帮助你。 https://openlayers.org/en/v4.6.5/examples/wms-tiled.html?q=wms

如果你使用的是模块,你应该使用 node 包管理器和 webpack 之类的捆绑库。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-10-14
    • 1970-01-01
    • 2020-08-16
    • 2020-09-14
    • 2016-07-02
    • 2017-09-08
    • 2015-12-10
    • 2013-07-08
    相关资源
    最近更新 更多