【WebGIS初学到入职】(12)从OpenLayers官网案例出发

一、前言

OpenLayers的官网给我们提供了相当多的例子,打开一个例子你就能直接看到运行效果还有一些说明,接着就是下面的代码:main.jsindex.htmlpackage.json
在这里插入图片描述

但如果一个纯纯纯小白比如我,点开来之后可能会有些懵:

还没学到JS模块化编程,就可能看不懂这一堆的importimport 'ol/ol.css';
import Map from 'ol/Map';
import OSM from 'ol/source/OSM';
或者是还没学过node.js的可能会不知道每个例子最下面为啥会有个 `package.json`

看着这些都贴脸上的代码,对只学过简单的HTML+CSS+一点点JavaScript的我来说,属实是无从下手。

二、开始

然后今天看黑马程序员Vue全套视频教程,从vue2.0到vue3.0一套全覆盖,前端必会的框架教程的时候,刚好学到了一点node.js的知识。现学现用,开始试试自己能不能打开ol官网的例子。

环境:Windows11 + Visual Code

2.1 首先安装node.js

在这里插入图片描述

2.2 新建项目

  • 新建一个空文件夹
  • 用vscode打开项目文件夹
  • 在vscode的终端里输入:npm init -y
    在这里插入图片描述
  • 成功后会得到一个 package.json 文件。

2.3 拷贝案例源代码

2.4 配置ol和parcel

  • 在vscode的终端处输入:
npm install ol -S
npm install parcel -D
  • 前者是安装OpenLayers的包
  • 后者是安装Parcel的包
  • 成功之后可以在 package.json 中看到它们:
    在这里插入图片描述
  • 然后修改一下 package.json 中 “scripts”: {}里的内容
"scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
改成
  "scripts": {
    "start": "parcel index.html",
    "build": "parcel build --public-url . index.html"
    },

2.5 开始调试

  • 可以直接点击package.json里的调试小按钮,选择start
    在这里插入图片描述
  • 铛铛!报错:
    在这里插入图片描述
    报错全文:
PS X:\Repository\newstart\day1> npm run start
Debugger attached.

> day1@1.0.0 start
> parcel index.html

Debugger attached.
Server running at http://localhost:1234
× Build failed.

@parcel/transformer-js: Browser scripts cannot have imports or
exports.

  X:\Repository\newstart\day1\main.js:1:1
  > 1 | import 'ol/ol.css';
  >   | ^^^^^^^^^^^^^^^^^^^
    2 | import Map from 'ol/Map';
    3 | import OSM from 'ol/source/OSM';

  X:\Repository\newstart\day1\index.html:7:5
    6 |     <!-- Pointer events polyfill for old browsers, see https:/
  > 7 |     <script src="https://unpkg.com/elm-pep"></script>
  >   |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ The environment was originally created here
    8 |     <!-- The line below is only needed for old environments li
    9 |     <script src="https://cdn.polyfill.io/v3/polyfill.min.js?fe

  ℹ Add the type="module" attribute to the <script> tag.
  ℹ Learn more:
     https://parceljs.org/languages/javascript/#classic-scripts       


  • 按照提示,我们在index.html的 <script>中添加type="module"
    在这里插入图片描述
  • 再来一遍,成功!控制台显示:
PS X:\Repository\newstart\day1> npm run start
Debugger attached.

> day1@1.0.0 start> parcel index.html
Debugger attached.
Server running at http://localhost:1234
√ Built in 1.90s

  • 打开 http://localhost:1234 得到:
    在这里插入图片描述

三、最后

因为自己也是刚开始学,所以很多东西都不是很了解,但是能成功运行出来就已经很满足了。等后续node.js学得差不多了再回来修改这篇文章中的错误吧(虽然不知道有没有错)。

  • 4
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值