Vue+Cesium创建项目并加载地图全过程

14 篇文章 10 订阅
13 篇文章 0 订阅

目录

一.创建vue项目准备工作

1.执行创建项目命令

2.项目名称 

3.项目说明

 4.作者描述

5. 编译方式

6.是否安装vue路由 

7.是否使用ESLine

8.选择预设的ESLine规则

9.设置单元测试

10.设置e2e

 11.选择安装方式

12.项目创建及依赖自动安装

13.运行项目 

14.停止项目

二.cesium 安装配置

1.安装Cesium环境

2.Webpack配置

build/webpack.base.conf.js

build/webpack.dev.conf.js

build/webpack.prod.conf.js

3. 创建cesium测试组件

三.补充对npm run dev 运行错误处理

四.框架源码


一.创建vue项目准备工作

注释:使用vue-cli脚手架的版本是2.9.6

git 的下载及安装,用于管理源代码

node.js 尽量用低一点的版本(此处用的node.js版本是v12.14),尽可能不要是哟过高版本;

以上大家自行下载安装,我不在赘述;接下来我们开始创建项目

1.执行创建项目命令

前提是已安装node.js 按住win+r进入运行输入 cmd 以管理员打开命令运行页面如下图

 检查node.js和vue版本,如下图

 安装全局vue-cli

npm install vue-cli -g

通过cd 命令进入要创建项目的目录并下执行指令,创建的项目将存放到该目录中,执行创建项目命令,项目名称可以带引号“test” 如下图

vue init webpack test

2.项目名称 

如默认test为项目名称,回车继续,否则输入需要创建的项目名称,不支持中文和大写;

? Project name (test)   

3.项目说明

可以对该项目做一下简要说明,默认直接回车下一步

? Project description (A Vue.js project)

 4.作者描述

默认是vue中配置的作者信息,默认直接回车下一步

? Author (…….@126.com>)

5. 编译方式

vue的编译方式用户使用上下键选择,回车键确定,默认直接回车即可

? Vue build (User arrow keys)
>  Runtime + Compiler: recommended for most users
   Runtime-only: about 6KB lighter min+gzip, but templates (or any Vue-specific HTML) are ONLY allowed in .vue files -render functions are required elsewhere

  对以上做一下翻译:

Vue 编译方式?(用户使用上下键选择,回车键确定)

> 运行时+编译器:建议大多数用户使用

仅运行时:比min+gzip轻约6KB,但模板(或任何特定于Vue的HTML)只允许在.vue文件中使用-其他地方需要呈现函数

6.是否安装vue路由 

默认安装路由,输入 并回车继续

? Install vue-router? (Y/n)

7.是否使用ESLine

使用ESLine来约束代码书写风格 ,ESLine是一个检查语法规范的工具,输入 Y 并继续

? Use ESLint to lint your code?(Y/n)

8.选择预设的ESLine规则

选择默认的标准规范,并回车继续

? Pick an ESLint preset (User arrow keys)
>  Standard (https://github.com/standard/standard)
   Airbnb (https://github.com/airbnb/javascript)
   none (configure it yourself)

9.设置单元测试

测试单元默认不创建,输入n 并回车继续;

如需创建测试单元,输入 Y 并回车继续,下一步默认 jest 回车继续

? Set up unit tests (Y/n)

10.设置e2e

使用Nightwatch框架设置e2e测试,默认输入n 并回车继续

? Setup e2e tests with Nightwatch?(Y/n)

 11.选择安装方式

创建项目时有很多依赖包需要下载,可以使用npm工具或者yarn工具类自动下载,默认直接回车,使用NPM安装

? Should we run `npm install` for you after the project has been created? (recommended) (Use arrow keys)
>    Yes, use NPM
     Yes, use Yarn
     No, I will handle that myself

12.项目创建及依赖自动安装

等待安装 ……

13.运行项目 

依次输入以下命令行

cd test
npm run dev

等待出现以下提示信息表示项目以运行成功

 DONE  Compiled successfully in 2768ms                   11:33:49

 I  Your application is running here: http://localhost:8080 

 项目访问地址,在浏览器中访问以下地址

http://localhost:8080 

备注:查看项目的启动命令在项目的根目录下 README.md 文件中 查看

14.停止项目

在命令窗口中按 ctrl + c ,出现以下提示,输入Y 并回车继续就会停止项目

二.cesium 安装配置

1.安装Cesium环境

在命令窗口或VS Code开发工具中打开text项目,执行 npm install cesium 安装命令,如下图

命令窗口中安装cesium环境

 VS Code 开发工具安装cesium环境

在安装cesium可能会报以下错误,若没有则忽略

rollbackFailedOptional: verb npm-session ab1b9becfc5b03e4

解决办法:

1.执行以下命令修改npm的资源镜像链接

npm config set registry http://registry.npm.taobao.org

2.查看是否修改成功

npm config get registry           

以下结果为修改成功

2.Webpack配置

在配置之前,使用过Cesium的都知道它是一个非常复杂的库,很难去直接打包,我们无法通过在main.js 中像引入Vue那样直接进行引入Cesium,具体配置如下

build/webpack.base.conf.js

1、定义 Cesium 源码路径

'use strict'
const path = require('path')
const utils = require('./utils')
const config = require('../config')
const vueLoaderConfig = require('./vue-loader.conf')

// cesium 配置
const cesiumSource = '../node_modules/cesium/Source'

2、在output 里加入sourcePrefix: ' ' ,让webpack 正确处理多行字符串
3、配置 amd 参数
4、module 中在rules后添加 unknownContextCritical: false

module.exports = {
  context: path.resolve(__dirname, '../'),
  entry: {
    app: './src/main.js'
  },
  output: {
    path: config.build.assetsRoot,
    filename: '[name].js',
    publicPath: process.env.NODE_ENV === 'production'
      ? config.build.assetsPublicPath
      : config.dev.assetsPublicPath,
    sourcePrefix: ' ' // cesium 配置
  },
  // cesium 配置 --start
  amd:{
      toUrlUndefined: true
  },
  // cesium 配置 --end
  resolve: {
    extensions: ['.js', '.vue', '.json'],
    alias: {
      'vue$': 'vue/dist/vue.esm.js',
      '@': resolve('src'),
		  'cesium': path.resolve(__dirname, cesiumSource) // cesium 配置
    }
  },
  module: {
    rules: [
      // ...(config.dev.useEslint ? [createLintingRule()] : []),
      {
        test: /\.vue$/,
        loader: 'vue-loader',
        options: vueLoaderConfig
      },
      {
        test: /\.js$/,
        loader: 'babel-loader',
        include: [resolve('src'), resolve('test'), resolve('node_modules/webpack-dev-server/client')]
      },
      {
        test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
        loader: 'url-loader',
        exclude: [resolve('src/assets/icons')], // svg配置
        options: {
          limit: 10000,
          name: utils.assetsPath('img/[name].[hash:7].[ext]')
        }
      },
      {
        test: /\.(mp4|webm|ogg|mp3|wav|flac|aac)(\?.*)?$/,
        loader: 'url-loader',
        options: {
          limit: 10000,
          name: utils.assetsPath('media/[name].[hash:7].[ext]')
        }
      },
      {
        test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
        loader: 'url-loader',
        options: {
          limit: 10000,
          name: utils.assetsPath('fonts/[name].[hash:7].[ext]')
        }
      }
    ],
    unknownContextCritical: false // cesium 配置
  }
}

build/webpack.dev.conf.js

1、定义 Cesium 源码路径和Cesium Workers 路径(注意:这里的 node_modules 与webpack.base.conf.js中的配置不同,前面没有 ../ 

// cesium 配置
const cesiumSource = 'node_modules/cesium/Source'
const cesiumWorkers = '../Build/Cesium/Workers'

2、定义CESIUM_BASE_URL变量
3、在plugins 中加入下面插件,拷贝静态资源

  plugins: [
    new webpack.DefinePlugin({
      'process.env': require('../config/dev.env'),
      'CESIUM_BASE_URL': JSON.stringify('') // cesium 配置
    }),
    new HtmlWebpackPlugin({
      ……
    }),
    new CopyWebpackPlugin([ { from: path.join(cesiumSource, cesiumWorkers), to: 'Workers' } ]), // cesium 配置
    new CopyWebpackPlugin([ { from: path.join(cesiumSource, 'Assets'), to: 'Assets' } ]), // cesium 配置
    new CopyWebpackPlugin([ { from: path.join(cesiumSource, 'Widgets'), to: 'Widgets' } ]), // cesium 配置
    new CopyWebpackPlugin([ { from: path.join(cesiumSource, 'ThirdParty/Workers'), to: 'ThirdParty/Workers' } ]), // cesium 配置
    
    // copy custom static assets
    new CopyWebpackPlugin([
      ……
    ])
  ]

build/webpack.prod.conf.js

1、定义路径

// cesium 配置
const cesiumSource = 'node_modules/cesium/Source';
const cesiumWorkers = '../Build/Cesium/Workers';

2、定义'CESIUM_BASE_URL'变量
3、在plugins 中加入下面插件,拷贝静态资源

plugins: [
    // http://vuejs.github.io/vue-loader/en/workflow/production.html
    new webpack.DefinePlugin({
      'process.env': env,
      'CESIUM_BASE_URL': JSON.stringify('static') // cesium 配置
    }),
    new UglifyJsPlugin({
      ……
    }),
    new ExtractTextPlugin({
      ……
    }),
    new OptimizeCSSPlugin({
      ……
    }),
    new HtmlWebpackPlugin({
      ……
    }),

    new CopyWebpackPlugin([ { from: path.join(cesiumSource, cesiumWorkers), to: 'static/Workers' } ]), // cesium 配置
    new CopyWebpackPlugin([ { from: path.join(cesiumSource, 'Assets'), to: 'static/Assets' } ]), // cesium 配置
    new CopyWebpackPlugin([ { from: path.join(cesiumSource, 'Widgets'), to: 'static/Widgets' } ]), // cesium 配置
    new CopyWebpackPlugin([ { from: path.join(cesiumSource, 'ThirdParty/Workers'), to: 'ThirdParty/Workers' } ]), // cesium 配置
    new CopyWebpackPlugin([ { from: 'ThirdParty', to: 'ThirdParty' } ]), // cesium 配置
    
    ……
  ]

4、ThirdParty文件夹创建

        在项目根目录新建文件夹ThirdParty,放入draco_decoder.wasm文件,在加载gltf模型文件等需要用到。

5、main.js配置全局样式

// cesium 配置
import widgets from "../node_modules/cesium/Source/Widgets/widgets.css"
Vue.prototype.widgets = widgets

3. 创建cesium测试组件

<template>
  <div>
    <div id="map3DView">
  </div>
  </div>
</template>

<script>
const Cesium = require('cesium/Cesium')
let viewer = undefined

export default {
  name: 'map3DView',
  data () {
    return {      
    }
  },
  mounted(){
    Cesium.Ion.defaultAccessToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiI0NzhhMDI0NC05NDUwLTRjZWYtOWI5Mi1mYzNjNWQ5OGQ1ZWQiLCJpZCI6NDU0MTEsImlhdCI6MTYyNjA4MTg2MX0.dn2cDGd6p2ar3atcOEwX9LVjmgqcBj1RCqVaWkwFEcU';
    viewer = new Cesium.Viewer("map3DView", {
      requestRenderMode: true, // 开启请求的渲染模式
      maximumRenderTimeChange: Infinity, // 处理模拟时间改变
      animation: false, // 是否创建动画小器件,左下角仪表
      baseLayerPicker: false, // 是否显示图层选择器
      fullscreenButton: false, // 是否显示全屏按钮
      geocoder: false, // 是否显示geocoder小器件,右上角查询按钮
      homeButton: false, // 是否显示Home按钮
      infoBox: false, // 是否显示信息框
      shouldAnimate: true,  // 允许动画
      sceneModePicker: false, // 是否显示3D/2D选择器
      selectionIndicator: false, // 是否显示选取指示器组件鼠标绿色框
      timeline: true, // 是否显示时间轴
      navigationHelpButton: false, // 是否显示右上角的帮助按钮
      vrButton: false, // 是否显示双屏
      scene3DOnly: true, // 如果设置为true,则所有几何图形以3D模式绘制以节约GPU资源
      fullscreenElement: document.body, // 全屏时渲染的HTML元素
      allowDataSourcesToSuspendAnimation: false,
      navigationInstructionsInitiallyVisible: false,
      terrainProvider:
        Cesium.createWorldTerrain(),
      orderIndependentTranslucency: false,
      contextOptions: {
        webgl: {
          alpha: true,
          depth: true,
          stencil: true,
          antialias: true, //!mobilecheck(),
          premultipliedAlpha: true,
          //通过canvas.toDataURL()实现截图需要将该项设置为true
          preserveDrawingBuffer: true,
          failIfMajorPerformanceCaveat: true
        }
      },
      requestWaterMask: true // 水面特效
    })
    viewer.shadows = true //开启或关闭阴影

    // 关闭抗锯齿
    viewer.scene.fxaa = true
    viewer.scene.postProcessStages.fxaa.enabled = true;

    //开启帧率检测
    viewer.scene.debugShowFramesPerSecond = true;

    // 开启全球光照
    viewer.scene.globe.enableLighting = true

    //更改配置,性能优化
    viewer.scene.logarithmicDepthBuffer = true;
    // 取消双击事件-追踪该位置
    viewer.cesiumWidget.screenSpaceEventHandler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK);
    
    viewer.camera.flyTo({ 
      destination: Cesium.Cartesian3.fromDegrees(103.04756,37.48098,21119200),
      orientation: {
        heading: 6.07, 
        pitch: -1.53,
      },
      duration: 5 
    })
  }
}
</script>

<style lang="scss" scoped>
#map3DView{
  width: 100%;
  height: 100%;
  overflow: hidden;

  /* cesium 去版权 */
    /deep/ .cesium-widget-credits {
      display: none !important;
      visibility: hidden !important;
    }
    
    /deep/ .cesium-widget-credits {
      display: none !important;
      visibility: hidden !important;
    }

    /* 隐藏时间轴 */
    /deep/ .cesium-viewer-timelineContainer{
      display: none;
    }
    
    /* 帧率位置控制 */
    /deep/ .cesium-performanceDisplay-defaultContainer{
      top: auto;
      bottom: 36px;
    }

    /* 隐藏帧率名称 */
    /deep/ .cesium-performanceDisplay-throttled{
      display: none;
    }
  }
</style>

 运行结果如下

至此在vue中创建cesium项目及安装配置等完美收工;

三.补充对npm run dev 运行错误处理

执行npm run dev时出现以下信息需要进行处理

You may use special comments to disable some warnings.
Use // eslint-disable-next-line to ignore the next line.
Use /* eslint-disable */ to ignore all warnings in a file.

解决方法如下

方法一:webpack.base.conf.js 文件中,找到 module节点下的 rules节点,注释掉这一行 

// ...(config.dev.useEslint ? [createLintingRule()] : []),

方法二:如果是较新版本的 vue ,使用的不是 webpack.base.conf.js 配置,而是 vue-cli-service 配置,找到 vue.config.js 文件,将 lintOnSave 设为 false 即可

四.框架源码

下载:Vue2+Cesium框架源码

老铁,如果对您有用的话,别忘了给点个赞 + 关注!!!

  • 9
    点赞
  • 45
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

向着太阳往前冲

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值