1、npm install cesium --save
2、修改webpack.base.conf.js
‘use strict‘ const path = require(‘path‘) const utils = require(‘./utils‘) const config = require(‘../config‘) const vueLoaderConfig = require(‘./vue-loader.conf‘) //1、The path to the CesiumJS source code cesium的源码目录 const cesiumSource = ‘../node_modules/cesium/Source‘ function resolve(dir) { return path.join(__dirname, ‘..‘, dir) } 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, //2、 Needed to compile multiline strings in Cesium sourcePrefix: ‘‘ }, resolve: { extensions: [‘.js‘, ‘.vue‘, ‘.json‘], alias: { ‘vue$‘: ‘vue/dist/vue.esm.js‘, ‘@‘: resolve(‘src‘), //3、 CesiumJS module name 我们就可以在应用程序中引用cesium了 cesium: path.resolve(__dirname, cesiumSource) } }, module: { rules: [{ 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‘, 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]‘) } } ], //4、 unknownContextCritical: false }, node: { // prevent webpack from injecting useless setImmediate polyfill because Vue // source contains it (although only uses it if it‘s native). setImmediate: false, // prevent webpack from injecting mocks to Node native modules // that does not make sense for the client dgram: ‘empty‘, fs: ‘empty‘, net: ‘empty‘, tls: ‘empty‘, child_process: ‘empty‘ } }
修改webpack.dev.conf.js
‘use strict‘ const utils = require(‘./utils‘) const webpack = require(‘webpack‘) const config = require(‘../config‘) const merge = require(‘webpack-merge‘) const path = require(‘path‘) const baseWebpackConfig = require(‘./webpack.base.conf‘) const CopyWebpackPlugin = require(‘copy-webpack-plugin‘) const HtmlWebpackPlugin = require(‘html-webpack-plugin‘) const FriendlyErrorsPlugin = require(‘friendly-errors-webpack-plugin‘) const portfinder = require(‘portfinder‘) //1、定义源码目录 const cesiumSource = ‘node_modules/cesium/Source‘ const cesiumWorkers = ‘../Build/Cesium/Workers‘ const HOST = process.env.HOST const PORT = process.env.PORT && Number(process.env.PORT) const devWebpackConfig = merge(baseWebpackConfig, { module: { rules: utils.styleLoaders({ sourceMap: config.dev.cssSourceMap, usePostCSS: true }) }, // cheap-module-eval-source-map is faster for development devtool: config.dev.devtool, // these devServer options should be customized in /config/index.js devServer: { clientLogLevel: ‘warning‘, historyApiFallback: { rewrites: [ { from: /.*/, to: path.posix.join(config.dev.assetsPublicPath, ‘index.html‘) }, ], }, hot: true, contentBase: false, // since we use CopyWebpackPlugin. compress: true, host: HOST || config.dev.host, port: PORT || config.dev.port, open: config.dev.autoOpenBrowser, overlay: config.dev.errorOverlay ? { warnings: false, errors: true } : false, publicPath: config.dev.assetsPublicPath, proxy: config.dev.proxyTable, quiet: true, // necessary for FriendlyErrorsPlugin watchOptions: { poll: config.dev.poll, } }, plugins: [ new webpack.DefinePlugin({ ‘process.env‘: require(‘../config/dev.env‘) }), new webpack.HotModuleReplacementPlugin(), new webpack.NamedModulesPlugin(), // HMR shows correct file names in console on update. new webpack.NoEmitOnErrorsPlugin(), // https://github.com/ampedandwired/html-webpack-plugin new HtmlWebpackPlugin({ filename: ‘index.html‘, template: ‘index.html‘, inject: true }), // copy custom static assets new CopyWebpackPlugin([{ from: path.resolve(__dirname, ‘../static‘), to: config.dev.assetsSubDirectory, ignore: [‘.*‘] }]), //2、开始 new CopyWebpackPlugin([{ from: path.join(cesiumSource, cesiumWorkers), to: ‘Workers‘ }]), new CopyWebpackPlugin([{ from: path.join(cesiumSource, ‘Assets‘), to: ‘Assets‘ }]), new CopyWebpackPlugin([{ from: path.join(cesiumSource, ‘Widgets‘), to: ‘Widgets‘ }]), new CopyWebpackPlugin([{ from: path.join(cesiumSource, ‘ThirdParty/Workers‘), to: ‘ThirdParty/Workers‘ }]), new webpack.DefinePlugin({ // Define relative base path in cesium for loading assets CESIUM_BASE_URL: JSON.stringify(‘‘) }) //2 结束 ] }) module.exports = new Promise((resolve, reject) => { portfinder.basePort = process.env.PORT || config.dev.port portfinder.getPort((err, port) => { if (err) { reject(err) } else { // publish the new Port, necessary for e2e tests process.env.PORT = port // add port to devServer config devWebpackConfig.devServer.port = port // Add FriendlyErrorsPlugin devWebpackConfig.plugins.push(new FriendlyErrorsPlugin({ compilationSuccessInfo: { messages: [`Your application is running here: http://${devWebpackConfig.devServer.host}:${port}`], }, onErrors: config.dev.notifyOnErrors ? utils.createNotifierCallback() : undefined })) resolve(devWebpackConfig) } }) })
修改webpack.prod.conf.js
‘use strict‘ const path = require(‘path‘) const utils = require(‘./utils‘) const webpack = require(‘webpack‘) const config = require(‘../config‘) const merge = require(‘webpack-merge‘) const baseWebpackConfig = require(‘./webpack.base.conf‘) const CopyWebpackPlugin = require(‘copy-webpack-plugin‘) const HtmlWebpackPlugin = require(‘html-webpack-plugin‘) const ExtractTextPlugin = require(‘extract-text-webpack-plugin‘) const OptimizeCSSPlugin = require(‘optimize-css-assets-webpack-plugin‘) const UglifyJsPlugin = require(‘uglifyjs-webpack-plugin‘) const env = require(‘../config/prod.env‘) //1、 const cesiumSource = ‘node_modules/cesium/Source‘ const cesiumWorkers = ‘../Build/Cesium/Workers‘ const webpackConfig = merge(baseWebpackConfig, { module: { rules: utils.styleLoaders({ sourceMap: config.build.productionSourceMap, extract: true, usePostCSS: true }) }, devtool: config.build.productionSourceMap ? config.build.devtool : false, output: { path: config.build.assetsRoot, filename: utils.assetsPath(‘js/[name].[chunkhash].js‘), chunkFilename: utils.assetsPath(‘js/[id].[chunkhash].js‘) }, plugins: [ // http://vuejs.github.io/vue-loader/en/workflow/production.html new webpack.DefinePlugin({ ‘process.env‘: env }), new UglifyJsPlugin({ uglifyOptions: { compress: { warnings: false } }, sourceMap: config.build.productionSourceMap, parallel: true }), // extract css into its own file new ExtractTextPlugin({ filename: utils.assetsPath(‘css/[name].[contenthash].css‘), // Setting the following option to `false` will not extract CSS from codesplit chunks. // Their CSS will instead be inserted dynamically with style-loader when the codesplit chunk has been loaded by webpack. // It‘s currently set to `true` because we are seeing that sourcemaps are included in the codesplit bundle as well when it‘s `false`, // increasing file size: https://github.com/vuejs-templates/webpack/issues/1110 allChunks: true, }), // Compress extracted CSS. We are using this plugin so that possible // duplicated CSS from different components can be deduped. new OptimizeCSSPlugin({ cssProcessorOptions: config.build.productionSourceMap ? { safe: true, map: { inline: false } } : { safe: true } }), // generate dist index.html with correct asset hash for caching. // you can customize output by editing /index.html // see https://github.com/ampedandwired/html-webpack-plugin new HtmlWebpackPlugin({ filename: config.build.index, template: ‘index.html‘, inject: true, minify: { removeComments: true, collapseWhitespace: true, removeAttributeQuotes: true // more options: // https://github.com/kangax/html-minifier#options-quick-reference }, // necessary to consistently work with multiple chunks via CommonsChunkPlugin chunksSortMode: ‘dependency‘ }), // keep module.id stable when vendor modules does not change new webpack.HashedModuleIdsPlugin(), // enable scope hoisting new webpack.optimize.ModuleConcatenationPlugin(), // split vendor js into its own file new webpack.optimize.CommonsChunkPlugin({ name: ‘vendor‘, minChunks(module) { // any required modules inside node_modules are extracted to vendor return ( module.resource && /\.js$/.test(module.resource) && module.resource.indexOf( path.join(__dirname, ‘../node_modules‘) ) === 0 ) } }), // extract webpack runtime and module manifest to its own file in order to // prevent vendor hash from being updated whenever app bundle is updated new webpack.optimize.CommonsChunkPlugin({ name: ‘manifest‘, minChunks: Infinity }), // This instance extracts shared chunks from code splitted chunks and bundles them // in a separate chunk, similar to the vendor chunk // see: https://webpack.js.org/plugins/commons-chunk-plugin/#extra-async-commons-chunk new webpack.optimize.CommonsChunkPlugin({ name: ‘app‘, async: ‘vendor-async‘, children: true, minChunks: 3 }), // copy custom static assets new CopyWebpackPlugin([{ from: path.resolve(__dirname, ‘../static‘), to: config.build.assetsSubDirectory, ignore: [‘.*‘] }]), //2、开始 new CopyWebpackPlugin([{ from: path.join(cesiumSource, cesiumWorkers), to: ‘Workers‘ }]), new CopyWebpackPlugin([{ from: path.join(cesiumSource, ‘Assets‘), to: ‘Assets‘ }]), new CopyWebpackPlugin([{ from: path.join(cesiumSource, ‘Widgets‘), to: ‘Widgets‘ }]), new CopyWebpackPlugin([{ from: path.join(cesiumSource, ‘ThirdParty/Workers‘), to: ‘ThirdParty/Workers‘ }]), new webpack.DefinePlugin({ // Define relative base path in cesium for loading assets 注意和dev中略有不同 ‘‘ 变成了‘./‘ CESIUM_BASE_URL: JSON.stringify(‘./‘) }) //2、结束 ] }) if (config.build.productionGzip) { const CompressionWebpackPlugin = require(‘compression-webpack-plugin‘) webpackConfig.plugins.push( new CompressionWebpackPlugin({ asset: ‘[path].gz[query]‘, algorithm: ‘gzip‘, test: new RegExp( ‘\\.(‘ + config.build.productionGzipExtensions.join(‘|‘) + ‘)$‘ ), threshold: 10240, minRatio: 0.8 }) ) } if (config.build.bundleAnalyzerReport) { const BundleAnalyzerPlugin = require(‘webpack-bundle-analyzer‘).BundleAnalyzerPlugin webpackConfig.plugins.push(new BundleAnalyzerPlugin()) } module.exports = webpackConfig
3、main.js
// The Vue build version to load with the `import` command // (runtime-only or standalone) has been set in webpack.base.conf with an alias. import Vue from ‘vue‘ import App from ‘./App‘ import router from ‘./router‘ //新版本的cesium 不支持以前的import 方式导入 这是个坑 var Cesium = require(‘cesium/Cesium‘); var widgets = require(‘cesium/Widgets/widgets.css‘); //此处将cesium 赋给全局 Vue.prototype.Cesium = Cesium Vue.prototype.widgets = widgets Vue.config.productionTip = false /* eslint-disable no-new */ new Vue({ el: ‘#app‘, router, components: { App }, template: ‘<App/>‘ })
4、App.vue
<template> <div id="app"> <router-view/> </div> </template> <script> export default { name: ‘App‘ } </script> <style> #app { font-family: ‘Avenir‘, Helvetica, Arial, sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; text-align: center; color: #2c3e50; } </style>
路由
{ path: ‘/‘, name: ‘CesiumViewer‘, component:()=>import ("@/components/CesiumViewer"), }
components/CesiumViewer.vue
<template> <div> <div id = "ipt"> 经度:{{jd}} 纬度:{{wd}} 高度:{{gd}} </div> <div id="cesiumContainer"></div> </div> </template> <script> export default { name: "cesiumviewer", data() { return { jd:‘‘, wd:‘‘, gd:‘‘ }; }, mounted() { // ‘eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiJhMmE0MWVmOC1kYzE1LTRhNzAtOTU5OC1mM2ZmNjAzNTlhNjEiLCJpZCI6NzkxMSwic2NvcGVzIjpbImFzciIsImdjIl0sImlhdCI6MTU1MDcxNjI3Nn0.ltozny7cbdFYNT8hQJoqKwbC9kseDOAen1Cj9tFbhww‘ var Cesium = this.Cesium; var viewer = new Cesium.Viewer("cesiumContainer", { sceneModel: Cesium.SceneMode.SCENE3D, fullscreenButton: false, animation: false, //是否显示动画控件 baseLayerPicker: false, //是否显示图层选择控件 geocoder: false, //是否显示地名查找控件 timeline: false, //是否显示时间线控件 sceneModePicker: true, //是否显示投影方式控件 navigationHelpButton: false, //是否显示帮助信息控件 infoBox: false, //是否显示点击要素之后显示的信息 scene3DOnly: false, //每个几何实例将只能以3D渲染以节省GPU内存 sceneMode: 3, imageryProvider:new Cesium.ArcGisMapServerImageryProvider({ url: ‘https://services.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer‘ }), }); viewer.scene.screenSpaceCameraController.minimumZoomDistance = 250; // viewer.scene.screenSpaceCameraController.maximumZoomDistance = 2500; this.qingxi(viewer,Cesium); this.mouse(viewer,Cesium); this.dingwei(viewer,Cesium); this.xian(viewer,Cesium); this.ponit(viewer,Cesium); this.rightClick(viewer,Cesium) // }, methods:{ mouse(viewer,Cesium){ var ts = this; var ellipsoid=viewer.scene.globe.ellipsoid; var handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas); handler.setInputAction(function(movement){ var cartesian=viewer.camera.pickEllipsoid(movement.endPosition, ellipsoid); if(cartesian){ var cartographic=viewer.scene.globe.ellipsoid.cartesianToCartographic(cartesian); var lat_String=Cesium.Math.toDegrees(cartographic.latitude).toFixed(8); var log_String=Cesium.Math.toDegrees(cartographic.longitude).toFixed(8); var alti_String=(viewer.camera.positionCartographic.height/1000).toFixed(2); ts.jd = lat_String; ts.wd = log_String; ts.gd = alti_String; // console.log(log_String+","+lat_String) } },Cesium.ScreenSpaceEventType.MOUSE_MOVE); }, getJwd(Cesium,viewer,movement){ let jd2 = ‘‘; let jd3 = ‘‘; let ellipsoid = viewer.scene.globe.ellipsoid; var cartesian = viewer.camera.pickEllipsoid(movement.position, ellipsoid); if(cartesian){ var cartographic = viewer.scene.globe.ellipsoid.cartesianToCartographic(cartesian); jd2=Cesium.Math.toDegrees(cartographic.latitude).toFixed(8); jd3=Cesium.Math.toDegrees(cartographic.longitude).toFixed(8); } return jd2+","+jd3 }, qingxi(viewer,Cesium){ viewer.scene.fxaa = false; viewer.scene.globe.maximumScreenSpaceError = 4/3; let layer0 = viewer.scene.imageryLayers.get(0); layer0.gamma = 0.66; if(Cesium.FeatureDetection.supportsImageRenderingPixelated()){ viewer.resolutionScale = window.devicePixelRatio; } viewer.scene.fxaa=false viewer.scene.postProcessStages.fxaa.enabled = false; var supportsImageRenderingPixelated = viewer.cesiumWidget._supportsImageRenderingPixelated; if (supportsImageRenderingPixelated) { var vtxf_dpr = window.devicePixelRatio; while (vtxf_dpr >= 2.0) { vtxf_dpr /= 2.0; } viewer.resolutionScale = vtxf_dpr; } }, dingwei(viewer,Cesium){ var citizensBankPark = viewer.entities.add({ name : ‘Citizens Bank Park‘, position : Cesium.Cartesian3.fromDegrees(112.59464848,37.73554763), label : { text : ‘定位中心点‘, font : ‘8pt monospace‘, style: Cesium.LabelStyle.FILL_AND_OUTLINE, outlineWidth : 2, verticalOrigin : Cesium.VerticalOrigin.BOTTOM, pixelOffset : new Cesium.Cartesian2(0, -9) } }); viewer.flyTo(viewer.entities); viewer._cesiumWidget._creditContainer.style.display = "none"; }, xian(viewer,Cesium){ viewer.entities.add({ polygon: { hierarchy: Cesium.Cartesian3.fromDegreesArray([ 112.59297132,37.73652464, 112.59461605,37.73665416, 112.59628378,37.73655672, 112.59634897,37.73559557, 112.59612692,37.73473993, 112.59470690,37.73460243, 112.59315768,37.73457544, 112.59304493,37.73551596 ]), height : 0, material : Cesium.Color.RED.withAlpha(0.1), outline : true, outlineColor : Cesium.Color.ORANGE } }) }, ponit(viewer,Cesium){ var point_options = { show: true, pixelSize: 8, color: Cesium.Color.RED, outlineColor: Cesium.Color.YELLOW, outlineWidth: 4, } viewer.scene.postProcessStages.fxaa.enabled = false; viewer.entities.add({ position: Cesium.Cartesian3.fromDegrees(112.59605738,37.73624547), point: point_options, label : { text : ‘宇翔大厦‘, font : ‘18pt monospace‘, style: Cesium.LabelStyle.FILL_AND_OUTLINE, outlineWidth : 2, verticalOrigin : Cesium.VerticalOrigin.BOTTOM, pixelOffset : new Cesium.Cartesian2(0, -9) } }); }, rightClick(viewer,Cesium){ var ts = this; let handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas); handler.setInputAction(function(click){ const pickedObject = viewer.scene.pick(click.position) if(pickedObject.primitive._color.red == 1){ ts.$router.push({ path:‘3dThree‘ }) } },Cesium.ScreenSpaceEventType.RIGHT_CLICK); } } }; </script> <!-- Add "scoped" attribute to limit CSS to this component only --> <style scoped> #cesiumContainer { width: 100%; height: 100%; margin: 0; padding: 0; overflow: hidden; } #ipt{ position: absolute; top: 20px; z-index: 999; font-size: 10; color: #F2F6FC; } </style>