如果你有两个window.onload=function(){} 引起冲突

本文探讨了JavaScript中多个window.onload事件导致的冲突问题,并提出了使用window.attachEvent和window.addEventListener的解决方案,确保页面加载完成后能够正确执行多个脚本。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

不要奇怪。

为什么会出现两个window.onload。

很久很久以前。

我一直不明白为什么 有的 JavaScript 必须写在页面的底部才会正常执行。

而放到页面的head区则没有任何反应。

后来我明白了 因为页面加载速度的原因。

有的JavaScript脚本必须等待页面加载结束 才能正常执行。

对于这样的情况有两个解决方法:

1、将脚本写到html的结束位置。这样只有html全部接在完毕后才会加载执行JavaScript脚本。

2、将脚本放在任意位置。通过 window.onload来执行脚本。

window.onload的意思是当页面加载完毕的时候执行。

很久很久以后,我遇到了一个新的问题。

我有两个window.onload=function(){};


我自己写一个函数(T_T不是类,我蹩脚的JavaScript还不会封装类哦!)。这个函数必须在页面加载完毕之后才能正常执行。

开始我就写了一个window.onload来执行这个函数。

然后我发现了这行不通。

我写这个函数就是为了封装好给别人用的。

最终目的是 只要在页面里引用这个JavaScript脚本就可以实现相关功能。

但是现在这个脚本占用了window.onload……。

而通常一个页面是只能执行一个window.onload的。

假设某个用户使用了我这个脚本。

而他因为其他原因需要用到window.onload那不是冲突了……。

两个只能活一个啊……。

那假如我有两个window.onload应该怎么办呢?

这时就要用window.attachEvent和window.addEventListener来解决一下。

当某一事件被触发时需要执行某个函数,在IE下可用attachEvent,在FF下则要用addEventListener。

attachEvent()有两个参数,第一个是事件名称,第二个是需执行的函数;

addEventListener()有三个参数,第一个是事件名称,但与IE事件不同的是,事件不带"on",比如"onsubmit"在这里应为"submit",第二个是需执行的函数,第三个参数为布尔值;

if (document.all){

window.attachEvent('onload',函数名)//IE中

}

else{

window.addEventListener('load',函数名,false);//firefox

}

使用上边的脚本来执行我的函数就可以不与其他的onload冲突啦!

这真是太爽了!

看到prototype.js中有个Event.observe的方法可以实现这种功能。不过为了这个在加载个prototype.js。有点累赘哦。


解决多个window.onload的冲突.txt

window.onload=function(){
   alert("加载完成");
   onload2();
   onload3();
}


本文来自优快云博客,转载请标明出处:http://blog.youkuaiyun.com/mtzai/archive/2009/11/21/4846404.aspx

<template> <!-- 客流OD--> <div class="layout-wrapper passengerflowOd-wrap"> <logo></logo> <animate-b-g-image name="passengerflowOd-wrap"></animate-b-g-image> <div class="header-wrapper" style="z-index: 200"> <img class="header-image" :src="titleSrc" /> <select-model :typeName="'客流OD'"></select-model> </div> <area-module class="left-wrap" :nowIndex="nowIndex" @getAreaInfo="customAreaData" ref="searchChild" @transferData="transferData" :editingStatus="editingStatus"> </area-module> <right-module class="right-wrap" :nowIndex="nowIndex" :isShowAllArea="showAllArea" :searchParams="searchParams" :rightMode="rightMode" :liquidFillChartInfo="liquidFillChartInfo" :odTableList="odTableList" @changeFlowEvent="changeFlowEvent" :flag="flag" @getLineMap="getLineMap" @enlargeBtn="enlargeBtn"> </right-module> <div class="od-line" v-show="showGraphicsMode && showCustomMode && !sliderDisabled"> <div> OD线 </div> <div class="od-slider"> <el-slider v-model="sliderOdLine" range :marks="marks" :max="legendList.oDNumMax" @change="changeOdLine" :disabled="sliderDisabled"> </el-slider> </div> </div> <div class="check-map" v-show="showGraphicsMode && showCustomMode"> <ul> <li v-for="(item, index) in options" :key="index" :class="[nowIndex == index ? 'checkType' : '']" @click="changeModule(item.value)"> <img :src="item.icon" alt="" /> <span>{{ item.label }}</span> </li> </ul> </div> <div class="legend-map" v-show="showGraphicsMode && showCustomMode"> <div class="item"> <div :class="['base-color','color-'+ 0]"></div> <span> {{legendList.oDNumMax}}</span> </div> <div class="item"> <div :class="['base-color','color-'+ 1]"></div> <span> {{legendList.oDNumMid}}</span> </div> <div class="item"> <div :class="['base-color','color-'+ 2]"></div> <span> {{legendList.oDNumMin}}</span> </div> </div> <!-- 站点线路地图 --> <div id="container" style="width:100%;height:100%" v-loading="isLoading" element-loading-background="rgba(255, 255, 255, 0)" element-loading-text="加载中,请稍后..." element-loading-spinner="el-icon-loading"> </div> <!-- 站点搜索 --> <div class="siteSearch" v-show="savaState"> <el-select v-model="searchKeys" placeholder="请输入站点名" suffix-icon="el-icon-search" class="search-input" filterable remote clearable :remote-method="remoteMethod" @change="checkValue" @clear="clearMarker"> <el-option v-for="(item, index) in searchSiteValues" :key="index" :label="item.stationName + '('+ item.roadName +')'" :value="index"> </el-option> </el-select> </div> <div class="areaName" v-show="savaState"> <el-form :model="ruleForm" :rules="rules" ref="ruleForm" :inline="true"> <el-form-item prop="name"> <el-input placeholder="设定区域名称" clearable v-model="ruleForm.name"> </el-input> </el-form-item> <el-form-item> <el-button type="primary" @click="onSubmit">保存</el-button> </el-form-item> </el-form> </div> <InfoWindow v-show="showInfoWindow" ref="infoWindow" :itemObj="infoWindowData" :info-window="stationInfoWindow" :infoTitle="infoTitle" :expandStatus="false"></InfoWindow> <el-dialog :visible.sync="dialogVisible" :before-close="handleClose" id="DvelopmentTargets" custom-class="my-dialog"> <table-list :isSort="true" :tableData="tableDataEnlargeBtn" :colorCircle="true" style="max-height: 100%;padding: 0 20px;" /> </el-dialog> </div> </template> <script> import API_PASSENGEROD from '@/api/api_passengerOD' import VueSlider from 'vue-slider-component' import 'vue-slider-component/theme/default.css' import selectModel from "@/components/selectModel"; import "./../layout/layout.scss"; import InfoWindow from "@/components/stationInfoWindows.vue" import areaModule from "./areaModule"; import rightModule from "./rightModule"; import { AMapManager, lazyAMapApiLoaderInstance } from "vue-amap"; import tableList from "@/components/tableList"; let lineColor = null; // od线颜色 // 站点地图 let stationPathSimplifierIns = null; let showStations = null; let hideStations = null; // 线路地图 let linePathSimplifierIns = null; let showLine = null; let hideLine= null; // 选中站点od let lineStationPathSimplifierIns = null; let showStationLine = null; let hideStationLine = null; // 区域地图 let areaPathSimplifierIns = null; let showAreaLine = null; let hideAreaLine = null; // 展示圆多边形 let circleCase = null; let polygonCase = null; let siteMarker = null; // 搜索站点 // 绘制编辑圆多边形 let circleEditor = null; let polyEditor = null; import AnimateBGImage from "@/components/AnimateBGImage"; import logo from '@/components/logo' let layer1 = null let layer2 = null let layer3 = null let markIcon1 = null let markIcon2 = null let markIcon3 = null export default { name: "passengerFlowOd", components: { selectModel, VueSlider, areaModule, rightModule, InfoWindow, tableList, AnimateBGImage, logo }, data() { return { max : null, mid : null, min : null, layerList : [], redIcon:require('../../assets/red.gif'), yellowIcon:require('../../assets/yellow.gif'), tableDataEnlargeBtn:[], dialogVisible:false, selectLineCase:{ data:[], id:'' }, showInfoWindow: false, stationInfoWindow: null, // 信息框 infoTitle:'', radius: '', center: [], path: [], pathArea: '', mouseTool: null, ruleForm: { name: '', }, rules: { name: [{ required: true, message: '请输入区域名称', trigger: 'blur' }, { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' } ], }, searchSiteValues: [], // 模糊搜索数据 searchKeys: '', // 搜索关键词 siteCenter: [], // 搜索站点坐标 infoWindowData: [{ overviewTitle: '区域面积', overviewValue: '', }, { overviewTitle: '流入数量', overviewValue: '', }, { overviewTitle: '流出数量', overviewValue: '', } ], searchParams: {}, //查询条件 searchId: '', odTableList: [], //top10表格数据 titleSrc: require("../../assets/images/common/bcImg.png"), sliderOdLine: [null, null], odLineData: [], legendList: { oDNumMin: null, oDNumMid: null, oDNumMax: null, // OD最大 }, marks: {}, options: [{ value: 0, label: "站点", icon: require("../../assets/images/layout/lines.png"), }, { value: 1, label: "线路", icon: require("../../assets/images/layout/site.png"), }, { value: 2, label: "区域", icon: require("../../assets/images/layout/vehicle.png"), }, ], showGraphicsMode: true, showCustomMode: true, savaState: false, nowIndex: 0, //0 站点 1线路 2区域 checkModeIndex: '', // 自定义圆坐标 customCircleData: { radius: '', location: [], }, customPolygonData: { areaCoverage: '', // 面积 location: [], }, // 自定义矩形坐标 liquidFillChartInfo: { chartId: "coverAreaRateInfo", chartName: "流入/流出占比", chartValue: [0.4, 0.6], }, showAllArea: true, rightMode: true, dotOptions: [{ tooltip: 'always' }, { tooltip: 'always' }], isLoading: false, // od线加载 exportParams: {}, odLinePrams: { ODNumBefore: '', ODNumAfter: '', }, flag: false, // 流入流出渲染 editingStatus: true, allAreaState: false, // 全城od线 customState: false, // 自定义od线 stationMapData:[], lineMapData:[], checkLineObj:{ linePath:[], lineStationInfo:[], lineName:'', passengerNum:'', stationNum:"", timeImbalanceFactor:"", }, checkStationOd:[], map:null, sliderDisabled:false, stationMarkerArr:[], } }, methods: { /** * @Description: 清空地图信息 飞线图 站点 * @author konghaitao * @date 2023-2-16 */ clearMap(){ if(layer1 ){ layer1.setMap(null); layer2.setMap(null); layer3.setMap(null); } if(markIcon1){ markIcon1.setMap(null); markIcon2.setMap(null); } }, //放大功能 enlargeBtn(data) { console.log(data,'dataaa') $(".my-dialog").css({ margin: "0 auto ", width: "80%", 'max-height':data.tableList.length <= 10 ? '50%':"90%", padding: "1%", top: data.tableList.length <= 10 ? '20%' :'5%' }); this.tableDataEnlargeBtn = data this.dialogVisible = true; }, //关闭 handleClose(done) { $(".el-dialog__wrapper").css({ "z-index": "-11100", }); this.$nextTick(() => { done(); }); }, remoteMethod(query) { let that = this; if (query !== "") { setTimeout(() => { that.getSearchStation(query); }, 500); } }, getSearchStation(query) { API_PASSENGEROD .getStationInfo({ stationName: query, }) .then((response) => { if (response.code == 0) { this.searchSiteValues = response.value; } else { console.log(response.message); } }) .catch((error) => { console.log(error) }); }, // 站点搜索 checkValue(val) { var that = this; if (this.searchKeys !== "") { this.siteCenter = [that.searchSiteValues[val].longitude, that.searchSiteValues[val].latitude] this.$nextTick(() => { that.drawSiteMap() }) } }, drawSiteMap() { var that = this; siteMarker && this.map.remove(siteMarker) siteMarker = new AMap.Marker({ icon: "//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png", position: that.siteCenter, offset: new AMap.Pixel(-13, -30) }); siteMarker.setMap(that.map); this.map.setFitView([siteMarker]) }, // 清除覆盖 clearMarker() { siteMarker && this.map.remove(siteMarker) }, // 更改模块 changeModule(value) { this.odTableList = [] this.nowIndex = value }, getDay(day) { var today = new Date(); var targetday_milliseconds = today.getTime() + 1000 * 60 * 60 * 24 * day; today.setTime(targetday_milliseconds); //注意,这行是关键代码 var tYear = today.getFullYear(); var tMonth = today.getMonth(); var tDate = today.getDate(); tMonth = this.doHandleMonth(tMonth + 1); tDate = this.doHandleMonth(tDate); return tYear + tMonth + tDate; }, doHandleMonth(month) { var m = month; if (month.toString().length == 1) { m = "0" + month; } return m; }, /**滑动od线 */ changeOdLine(val) { this.sliderOdLine = val; switch(this.nowIndex) { case 0: if(this.searchParams.platformIdOff == '' && this.searchParams.platformIdOn == '') { this.getStationMap(this.searchParams,false,0); } else { this.getStationMap(this.searchParams,false,1); } // false 滑动od线时不重置起始 break case 1: if(this.searchParams.lineId == '') { this.defaultLineOD(this.searchParams,false) } else { this.getLineStationPassengersOD(this.searchParams,false,1) } break case 2: this.getStationPathOfAreaInfo( this.searchParams, false) break } }, transferData(data) { this.map && this.map.clearMap(); this.searchParams = data; this.customState = false; this.allAreaState = false; this.sliderOdLine = [null, null]; console.log('bbbbbbb') console.log('cccc',new Loca.LinkLayer) this.getInfo(data) }, //获取当前模块所有信息 getInfo(data){ switch (this.nowIndex) { case 0: this.sliderDisabled = false; this.sliderOdLine = [null, null]; // 隐藏 线路 区域地图数据 linePathSimplifierIns && hideLine(); lineStationPathSimplifierIns && hideStationLine(); this.map && this.map.clearMap(); if(this.stationMarkerArr.length > 0) { this.stationMarkerArr.map((item,index)=>{ this.map.remove(item); }) } lineStationPathSimplifierIns && hideStationLine(); areaPathSimplifierIns && hideAreaLine(); // 清除线路 if(data.platformIdOff == '' && data.platformIdOn == ''){ this.showAllArea = true; this.getRoadOD(data); this.getStationMap(data,true,0); // //未选择站点图 }else { this.showAllArea = false; //查询表格信息及站点坐标 this.getStationOD() this.getStationMap(data,true,1); // 1为选中站图 } break; case 1: //线路 // 隐藏站点地图 this.sliderOdLine = [null, null]; stationPathSimplifierIns && hideStations(); linePathSimplifierIns && hideLine(); lineStationPathSimplifierIns && hideStationLine(); this.map && this.map.clearMap(); if(this.stationMarkerArr.length > 0) { this.stationMarkerArr.map((item,index)=>{ this.map.remove(item); }) }; lineStationPathSimplifierIns && hideStationLine(); areaPathSimplifierIns && hideAreaLine(); if(data.lineId == '') { this.showAllArea = true; this.sliderDisabled = false; this.getLineOD() //线路top10 this.defaultLineOD(data,true); // 默认线路 }else { //查询单个线路信息 this.showAllArea = false; this.sliderDisabled = true; this.getLineSingelTable(); this.checkLineOD(data); } break; case 2: // 隐藏站点线路地图 this.sliderDisabled = false; this.sliderOdLine = [null, null]; linePathSimplifierIns && hideLine(); stationPathSimplifierIns && hideStations(); linePathSimplifierIns && hideLine(); this.map && this.map.clearMap(); if(this.stationMarkerArr.length > 0) { this.stationMarkerArr.map((item,index)=>{ this.map.remove(item); }) }; // 清除站点 // 清除站点od线 lineStationPathSimplifierIns && hideStationLine(); this.customAreaData(data.id) // 区域图+ 流入流出占比 this.getStationOfAreaInfo(data.id, true) // 自定义区域表格 console.log(data,'33333') this.getStationPathOfAreaInfo(data, true) // 自定义区域Od线 // } break; } }, //查询单个线路信息 getLineSingelTable(){ let params = this.searchParams if(!params.lineId){ return } params.top = 10 API_PASSENGEROD.getRoadSectionPassenger(params).then(response => { if(response.value.length){ this.showAllArea = false this.odTableList = response.value console.log( this.odTableList ,'查询单个线路信息') }else { this.odTableList = [] } }).catch(err =>{ this.$message.error(err); }) }, //查询线路top10 getLineOD(){ let params = this.searchParams params.byLine = true params.top = 10 API_PASSENGEROD.getRegionalTravelOD(params).then(response=>{ if(response.value.length){ this.showAllArea = true this.odTableList = response.value } else { this.odTableList = [] } }).catch(err =>{ this.$message.error(err); }) }, //获取站点表格数据及坐标 getStationOD(flag){ // if(flag){ // this.searchParams.platformIdOff = this.searchParams.stationPointId // this.searchParams.platformIdOn = null // } else { // this.searchParams.platformIdOn = this.searchParams.stationPointId // this.searchParams.platformIdOff = null // } API_PASSENGEROD.getStationOD( this.searchParams).then(response => { console.log(response,'表格数据') if(response.value.length){ this.showAllArea = false this.odTableList = response.value } else { this.odTableList = [] } }).catch(err =>{ this.$message.error(err); }) }, getLineMap(data) { var that = this; if( data.id === that.selectLineCase.id){ that.map.remove( that.selectLineCase.data); that.selectLineCase = { data :[], id :'', } } else { that.demo(data) } }, demo(data){ var that = this; that.map.remove(that.selectLineCase.data); that.selectLineCase = { data :[], id :'', } let newRouteLine = new AMap.Polyline({ path: data.stationLocation, strokeColor: "#a9db35", isOutline: false, geodesic: true, // 大地线 strokeOpacity: 1, strokeWeight: 4, strokeStyle: "solid", strokeDasharray: [10, 5], lineJoin: "round", lineCap: "round", borderWeight: 2, outlineColor: "transparent", }); that.selectLineCase = { data:newRouteLine, id:data.id } newRouteLine.setMap(that.map); }, /* initMapData(data) { var that = this; this.odLineData = []; this.isLoading = true; let params = data; params.ODNumBefore = this.sliderOdLine[0]; params.ODNumAfter = this.sliderOdLine[1]; API_PASSENGEROD .getODNum3(params) .then((response) => { if (response.code === 0) { if (this.allAreaState) { let data = response.value.stationPathDto.splice(0, 100); if (data.length > 0) { data.map((item, index) => { that.odLineData.push({ oDNum: item.oDNum, path: [ [item.startLongitude, item.startLatitude], [item.endLongitude, item.endLatitude] ], startStationName: item.startStationName, endStationName: item.endStationName, }) }) this.isLoading = false; } else { this.isLoading = false; } } else { this.legendList.oDNumMin = response.value.oDNumMin; this.legendList.oDNumMid = response.value.oDNumMid; this.legendList.oDNumMax = response.value.oDNumMax; let keyData = [0, this.legendList.oDNumMin, this.legendList.oDNumMid, this.legendList.oDNumMax]; let valData = [String(0), String(this.legendList.oDNumMin), String(this.legendList.oDNumMid), String( this.legendList.oDNumMax)] let obj = {}; for (let i = 0; i < valData.length; i++) { const key = keyData[i]; obj[key] = valData[i] } this.marks = obj; this.sliderOdLine = [0, this.legendList.oDNumMax] let data = response.value.stationPathDto.splice(0, 100); if (data.length > 0) { data.map((item, index) => { that.odLineData.push({ oDNum: item.oDNum, path: [ [item.startLongitude, item.startLatitude], [item.endLongitude, item.endLatitude] ], startStationName: item.startStationName, endStationName: item.endStationName, }) }) this.isLoading = false; } else { this.isLoading = false; } } } else { this.isLoading = false; console.log(response.message); } }) .catch((error) => { this.isLoading = false; this.$message.error(error); }); },*/ //查询 自定义区域数据(地图及流入流出占比) customAreaData(id) { var that = this; let params = this.searchParams; params.id = id; this.customCircleData.location = []; // 圆区域 this.customPolygonData.location = []; // 多边行区域 if (id !== '') { that.flag = false; API_PASSENGEROD.getAreaInfo(params).then((response) => { if (response.code == 0) { // 圆 if (response.value.areaType == 0) { this.customCircleData.radius = response.value.radius; this.customCircleData.location = [response.value.stationLocationDtoList[0].lng, response.value .stationLocationDtoList[0].lat ]; this.circleMarker(this.customCircleData); // 绘制圆 } else if (response.value.areaType == 1) { // 矩形 this.customPolygonData.areaCoverage = response.value.areaCoverage; let data = response.value.stationLocationDtoList; data.map((item, index) => { this.customPolygonData.location.push( [item.lng, item.lat] ) }) // 绘制矩形 this.polygonMarker(this.customPolygonData); }; this.liquidFillChartInfo = { chartId: "coverAreaRateInfo", chartName: "流入/流出占比", chartValue: [], chartTitle: ['流入率', '流出率'] } if (response.value.inflowProportion == null || response.value.outflowProportion == null) { this.liquidFillChartInfo.chartValue.push(0) this.liquidFillChartInfo.chartValue.push(0) } else { this.liquidFillChartInfo.chartValue.push(response.value.inflowProportion) this.liquidFillChartInfo.chartValue.push(response.value.outflowProportion) } this.infoWindowData = [{ overviewTitle: '区域面积', overviewValue: response.value.areaCoverage, }, { overviewTitle: '流入数量', overviewValue: response.value.inflowPassengers, }, { overviewTitle: '流出数量', overviewValue: response.value.outflowPassengers, } ]; this.$nextTick(() => { that.flag = true; }); } else { this.$message({ message: response.message, type: 'warning' }); } }).catch((error) => { console.log(error) }) } else { this.customCircleData.location = []; this.customPolygonData.location = []; } }, circleMarker(val) { var that = this; // 先清除之前的图形 circleCase && this.map.remove(circleCase) polygonCase && this.map.remove(polygonCase) circleCase = new AMap.Circle({ center: val.location, radius: val.radius, //半径 borderWeight: 3, strokeColor: "#FF33FF", strokeOpacity: 1, strokeWeight: 6, strokeOpacity: 0.2, fillOpacity: 0.4, strokeStyle: 'dashed', strokeDasharray: [10, 10], // 线样式还支持 'dashed' fillColor: '#1791fc', zIndex: 50, }) circleCase.setMap(this.map) that.map.setCenter(val.location) // 缩放地图到合适的视野级别 // this.map.setFitView([circleCase]) circleCase.on("click", function (e) { that.setInfoWindows(e.lnglat); }); }, polygonMarker(val) { var that = this; circleCase && this.map.remove(circleCase) polygonCase && this.map.remove(polygonCase) polygonCase = new AMap.Polygon({ path: val.location, strokeColor: "#FF33FF", strokeWeight: 6, strokeOpacity: 0.2, fillOpacity: 0.4, fillColor: '#1791fc', zIndex: 50, }) this.map.add(polygonCase); polygonCase.on("click", function (e) { that.setInfoWindows(e.lnglat); }); // 缩放地图到合适的视野级别 that.map.setCenter(val.location) // this.map.setFitView([polygonCase]) }, setInfoWindows(e) { var that = this; this.showInfoWindow = true; const infoWindow = new AMap.InfoWindow({ isCustom: true, anchor: "bottom-center", content: this.$refs['infoWindow'].$el, offset: new AMap.Pixel(0, -10), autoMove: true, closeWhenClickMap: true, }); this.stationInfoWindow = infoWindow; this.infoTitle = '基础指标'; // 信息窗口打开 infoWindow.open(that.map, e); }, // 保存后 查询自定义区域地图+ OD线+ 右侧表格+ 图表 seachCustomArea(id, name) { this.editingStatus = true; this.showGraphicsMode = true; this.showCustomMode = true; this.showAllArea = false; this.savaState = false; this.rightMode = true; this.customAreaData(id) // 区域图+ 流入流出占比 this.searchParams.id = id; this.getStationPathOfAreaInfo(this.searchParams, true) // 自定义区域Od线 this.getStationOfAreaInfo(id, true) // 自定义区域表格 this.$refs.searchChild.$emit('childMethod', id, name) // 左侧自定义区域id及名称,保存后改变新增区域状态 }, //选择新增区域类型 checkMode(val) { this.map.clearMap(); this.clearMap(); this.ruleForm.name = ''; this.searchKeys = ''; // this.checkModeIndex = data.label; if (val.label == '图形模式') { if (val.isSelect) { this.showGraphicsMode = false; this.savaState = true; this.rightMode = false; areaPathSimplifierIns && hideAreaLine(); this.mouseTool && this.mouseTool.close(true); circleEditor && circleEditor.close(); this.drawCircleMap() } else { this.showGraphicsMode = true; this.showCustomMode = true; this.savaState = false; this.rightMode = true; areaPathSimplifierIns && showAreaLine(); this.mouseTool && this.mouseTool.close(true); } } else if (val.label == '自定义模式') { if (val.isSelect) { // 选中 this.showCustomMode = false; this.savaState = true; this.rightMode = false; areaPathSimplifierIns && hideAreaLine(); this.mouseTool && this.mouseTool.close(true); polyEditor && polyEditor.close(); this.drawPolygonMap() } else { this.showGraphicsMode = true; this.showCustomMode = true; this.savaState = false; this.rightMode = true; areaPathSimplifierIns && showAreaLine(); this.mouseTool && this.mouseTool.close(true); } } }, // 编辑圆 drawCircleMap() { var that = this; this.mouseTool = new AMap.MouseTool(this.map); this.mouseTool.circle({ strokeColor: "#FF33FF", strokeOpacity: 1, strokeWeight: 6, strokeOpacity: 0.2, fillColor: "#1791fc", fillOpacity: 0.4, strokeStyle: "solid", }); this.mouseTool.on("draw", function (event) { that.radius = event.obj.De.radius.toFixed(0); let centerLng = event.obj.De.center.lng; let centerLat = event.obj.De.center.lat; let position = [centerLng, centerLat]; that.center = [{ lat: centerLat, lng: centerLng }] that.map.clearMap() // 先拿到绘制好的半径圆心再清除进入编辑 var circle = new AMap.Circle({ center: position, radius: that.radius, //半径 borderWeight: 3, strokeColor: "#FF33FF", strokeOpacity: 1, strokeWeight: 6, strokeOpacity: 0.2, fillOpacity: 0.4, strokeStyle: "dashed", strokeDasharray: [10, 10], fillColor: "#1791fc", zIndex: 50, }); circle.setMap(that.map); that.map.setFitView([circle]); circleEditor = new AMap.CircleEditor(that.map, circle); circleEditor.open(); circleEditor.on("move", function (event) {}); circleEditor.on("adjust", function (event) {}); circleEditor.on("end", function (event) { that.radius = event.target.w.radius.toFixed(0); let centerLng = event.target.w.center.lng; let centerLat = event.target.w.center.lat; that.center = [{ lat: centerLat, lng: centerLng }] }); }); }, // 编辑矩形 drawPolygonMap() { var that = this; this.mouseTool = new AMap.MouseTool(this.map); this.mouseTool.polygon({ strokeColor: "#FF33FF", strokeOpacity: 1, strokeWeight: 6, strokeOpacity: 0.2, fillColor: "#1791fc", fillOpacity: 0.4, strokeStyle: "solid", }); this.mouseTool.on("draw", function (event) { that.path = event.obj.w.path; that.map.clearMap(); var polygon = new AMap.Polygon({ path: that.path, strokeColor: "#FF33FF", strokeWeight: 6, strokeOpacity: 0.2, fillOpacity: 0.4, fillColor: '#1791fc', zIndex: 50, }) that.pathArea = polygon.getArea(); // 编辑前的面积 that.map.add(polygon) that.map.setFitView([polygon]); polyEditor = new AMap.PolyEditor(that.map, polygon); polyEditor.open(); polyEditor.on('addnode', function (event) {}) polyEditor.on('adjust', function (event) {}) polyEditor.on('removenode', function (event) {}) polyEditor.on('end', function (event) { that.path = event.target.w.path; // 编辑后面积 that.pathArea = Math.round(AMap.GeometryUtil.ringArea(event.target.w.path)); }) }); }, // 保存 onSubmit() { var that = this; this.$refs.ruleForm.validate((valid) => { if (valid) { if (!that.showGraphicsMode) { // 圆 that.circleOdLine() } else if (!that.showCustomMode) { // 多边形 that.polygonOdLine() } } else { console.log('error submit!!'); return false; } }); }, // 图形模式保存 circleOdLine() { var that = this; let params = { areaName: this.ruleForm.name, areaType: 0, // 区域类型 radius: this.radius, location: this.center, } API_PASSENGEROD.saveAreaInfo(params).then((response) => { if (response.code == 0) { this.map.clearMap(); let id = response.value; this.mouseTool.close(); circleEditor && circleEditor.close(); this.seachCustomArea(id, this.ruleForm.name) } else { this.$message({ message: response.message, type: 'warning' }); } }).catch((error) => { this.$message({ message: error, type: 'warning' }); }) }, // 自定义模式保存 polygonOdLine() { let location = []; this.path.map((item, index) => { location.push({ lat: item.lat, lng: item.lng }) }) let params = { areaName: this.ruleForm.name, areaType: 1, // 区域类型 location: location, areaCoverage: this.pathArea, } API_PASSENGEROD.saveAreaInfo(params).then((response) => { if (response.code == 0) { this.map.clearMap(); let id = response.value; this.mouseTool.close(); polyEditor && polyEditor.close(); this.seachCustomArea( id, this.ruleForm.name); } else { this.$message({ message: response.message, type: 'warning' }); } }).catch((error) => { this.$message({ message: error, type: 'warning' }); }) }, //右侧全城区域top10表格 getRoadOD(data) { let params = { startTime: data.startTime, endTime: data.endTime, peakSection: data.peakSection, isWeekday: data.isWeekday, top: 10, } API_PASSENGEROD.getRegionalTravelOD(params).then(res => { if (res.code == 0 && res.value.length != 0) { this.odTableList = res.value } else { this.odTableList = []; this.$message.error('未查询到 线路OD Top10 数据') } }) }, // 站点od getStationMap(data,status,isStationId){ this.isLoading = true; let params = {}; params.startTime = data.startTime; params.endTime = data.endTime; params.byLine =false; params.top = 100; params.ODNumBefore =this.sliderOdLine[0]; params.ODNumAfter =this.sliderOdLine[1]; if(isStationId == 0) { params.platformIdOn =''; params.platformIdOn =''; params.peakSection =''; params.isWeekday= ''; } else { params.platformIdOn=data.platformIdOn; params.platformIdOff=data.platformIdOff; params.peakSection=data.peakSection; params.isWeekday=data.isWeekday; } this.stationMapData = []; API_PASSENGEROD.getODNum3(params).then(res => { if(res.code == 0) { this.legendList.oDNumMin = res.value.oDNumMin; this.legendList.oDNumMid = res.value.oDNumMid; this.legendList.oDNumMax = res.value.oDNumMax; let keyData = [0, this.legendList.oDNumMin, this.legendList.oDNumMid, this.legendList.oDNumMax]; let valData = [String(0), String(this.legendList.oDNumMin), String(this.legendList.oDNumMid), String( this.legendList.oDNumMax)] let obj = {}; for (let i = 0; i < valData.length; i++) { const key = keyData[i]; obj[key] = valData[i] } this.marks = obj; if(status){ this.sliderOdLine = [0, this.legendList.oDNumMax] } this.stationMapData = res.value this.drawStationMap(); } else { this.isLoading = false; console.log(res.message) } }).catch((error)=>{ this.isLoading = false; console.log(error.msg) }) }, //绘制飞线图 drawStationMap() { var that = this; if(stationPathSimplifierIns !== null){ showStations(); } else { AMapUI.loadUI( ["misc/PathSimplifier", "misc/PointSimplifier"], (PathSimplifier, PointSimplifier) => { if (!PathSimplifier.supportCanvas) { alert("当前环境不支持 Canvas!"); return; } // od线 let oDMaxList = this.stationMapData.oDMaxList let oDMidList = this.stationMapData.oDMidList let oDMinList = this.stationMapData.oDMinList let red = this.stationMapData.red let yellow = this.stationMapData.yellow let arr = [oDMaxList,oDMidList,oDMinList] let iconList = [red,yellow] that.renderLayerMark(arr,iconList) }); } }, // 默认线路 defaultLineOD(data,status){ lineStationPathSimplifierIns && hideStationLine(); this.isLoading = true; let params = { startTime: data.startTime, endTime: data.endTime, ODNumBefore:this.sliderOdLine[0], ODNumAfter:this.sliderOdLine[1], byLine:true, top:100, } this.lineMapData = []; API_PASSENGEROD.getODNum3(params).then(res => { if(res.code == 0) { this.legendList.oDNumMin = res.value.oDNumMin; this.legendList.oDNumMid = res.value.oDNumMid; this.legendList.oDNumMax = res.value.oDNumMax; let keyData = [0, this.legendList.oDNumMin, this.legendList.oDNumMid, this.legendList.oDNumMax]; let valData = [String(0), String(this.legendList.oDNumMin), String(this.legendList.oDNumMid), String( this.legendList.oDNumMax)] let obj = {}; for (let i = 0; i < valData.length; i++) { const key = keyData[i]; obj[key] = valData[i] } this.marks = obj; if(status){ this.sliderOdLine = [0, this.legendList.oDNumMax] } this.sliderOdLine = res.value this.drawLineMap(); } else { this.isLoading = false; console.log(res.message) } }).catch((error)=>{ this.isLoading = false; console.log(error.msg) }) }, drawLineMap() { var that = this; if(linePathSimplifierIns !== null) { showLine(); } else { AMapUI.loadUI( ["misc/PathSimplifier", "misc/PointSimplifier"], (PathSimplifier, PointSimplifier) => { if (!PathSimplifier.supportCanvas) { alert("当前环境不支持 Canvas!"); return; } let oDMaxList = this.sliderOdLine.oDMaxList let oDMidList = this.sliderOdLine.oDMidList let oDMinList = this.sliderOdLine.oDMinList let red = this.sliderOdLine.red let yellow = this.sliderOdLine.yellow let arr = [oDMaxList,oDMidList,oDMinList] let iconList = [red,yellow] that.renderLayerMark(arr,iconList) }); } }, // 选中线路 checkLineOD(data){ this.sliderDisabled = true; // 先清除之前线路 if(this.stationMarkerArr.length > 0) { this.stationMarkerArr.map((item,index)=>{ this.map.remove(item); }) } this.map.clearMap(); this.stationMarkerArr = []; this.checkLineObj.lineStationInfo = []; let params = { lineId:data.lineId, direction:data.direction , startTime: data.startTime, endTime: data.endTime, peakSection:data.peakSection, isWeekday:data.isWeekday, } API_PASSENGEROD.getLinePassengerODBaseInfo(params).then(res => { if(res.code == 0) { console.log(layer1,'layer1') if(layer1){ layer1.setMap(null); layer2.setMap(null); layer3.setMap(null); } if(markIcon1){ markIcon1.setMap(null); markIcon2.setMap(null); } let data = res.value; this.checkLineObj.linePath = JSON.parse(data.linePath); data.lineStationInfo.map((item,index)=>{ let obj = {}; obj.center = [item.longitude,item.latitude]; obj.name = item.stationName; obj.stationId = item.stationId; this.checkLineObj.lineStationInfo.push(obj); }) this.checkLineObj.lineName = data.lineName; this.checkLineObj.passengerNum = data.passengerNum; this.checkLineObj.stationNum = data.stationNum; this.checkLineObj.timeImbalanceFactor = data.timeImbalanceFactor; this.$nextTick(()=>{ this.getcheckLineMap(this.checkLineObj.linePath,this.checkLineObj.lineStationInfo); }) } else { console.log(res.message) } }).catch((error)=>{ console.log(error.msg) }) }, getcheckLineMap(path,stations){ var that = this; // 站点 let iconStyle = new AMap.Icon({ size: new AMap.Size(15, 15), image: require("@/assets/images/layout/selected-vehicle.png"), imageSize: new AMap.Size(15, 15), }); this.stationMarkerArr = []; stations.forEach((marker) => { var stationMarker= new AMap.Marker({ icon: iconStyle, map: this.map, offset: new AMap.Pixel(-8, -8), position: [marker.center[0], marker.center[1]], }); stationMarker.setLabel({ offset: new AMap.Pixel(5, 20), //设置文本标注偏移量 content: marker.name, direction: "right", //设置文本标注方位 }); that.stationMarkerArr.push(stationMarker); // 点击显示站点od stationMarker.on("click", () => { this.searchParams.stationId = marker.stationId; this.getLineStationPassengersOD(this.searchParams,true,0) }); }); // 线路 // 定义线的风格 var polyline = new AMap.Polyline({ path: path, isOutline: true, outlineColor: "#49C3FC", borderWeight: 1, strokeColor: "#49C3FC", strokeOpacity: 1, strokeWeight: 2, strokeStyle: "solid", strokeDasharray: [10, 5], lineJoin: "round", lineCap: "round", zIndex: 10, }); polyline.setMap(this.map); // 线路 // 路线的起始点 var startMarker = new AMap.Marker({ position: path[0], icon: "https://webapi.amap.com/theme/v1.3/markers/n/start.png", map: this.map, }); var endMarker = new AMap.Marker({ position: path[path.length - 1], icon: "https://webapi.amap.com/theme/v1.3/markers/n/end.png", map: this.map, }); startMarker.setMap(this.map); endMarker.setMap(this.map); // 缩放地图到合适的视野级别 this.map.setFitView([polyline, startMarker, endMarker]); }, // 线路站点基本信息 getLineStationPassengersOD(val,status,initStatus){ // 首次点击无od量 this.isLoading = true; this.sliderDisabled = false; let params = {}; params.lineId = val.lineId; params.direction = val.direction; params.stationId = val.stationId; params.startTime = val.startTime; params.endTime = val.endTime; params.peakSection = val.peakSection; params.isWeekday = val.isWeekday; if(initStatus == 0){ params.ODNumBefore = ''; params.ODNumAfter = ''; } else { params.ODNumBefore =this.sliderOdLine[0]; params.ODNumAfter = this.sliderOdLine[1]; } this.checkStationOd = []; API_PASSENGEROD.getLineStationPassengersOD2(params).then(res => { if(res.code == 0) { this.legendList.oDNumMin = res.value.oDNumMin; this.legendList.oDNumMid = res.value.oDNumMid; this.legendList.oDNumMax = res.value.oDNumMax; let keyData = [0, this.legendList.oDNumMin, this.legendList.oDNumMid, this.legendList.oDNumMax]; let valData = [String(0), String(this.legendList.oDNumMin), String(this.legendList.oDNumMid), String( this.legendList.oDNumMax)] let obj = {}; for (let i = 0; i < valData.length; i++) { const key = keyData[i]; obj[key] = valData[i] } this.marks = obj; if(status){ this.sliderOdLine = [0, this.legendList.oDNumMax] } this.checkStationOd = res.value this.$nextTick(()=>{ this.checkStationOdMap(); }) this.isLoading = false; } else { console.log(res.message); this.isLoading = false; } }).catch((error)=>{ console.log(error.msg); this.isLoading = false; }) }, // 选择线路站点 checkStationOdMap(){ var that = this; if(lineStationPathSimplifierIns !== null) { showStationLine() } else { AMapUI.loadUI( ["misc/PathSimplifier", "misc/PointSimplifier"], (PathSimplifier, PointSimplifier) => { if (!PathSimplifier.supportCanvas) { alert("当前环境不支持 Canvas!"); return; } let oDMaxList = this.checkStationOd.oDMaxList let oDMidList = this.checkStationOd.oDMidList let oDMinList = this.checkStationOd.oDMinList let red = this.checkStationOd.red let yellow = this.checkStationOd.yellow let arr = [oDMaxList,oDMidList,oDMinList] let iconList = [red,yellow] that.renderLayerMark(arr,iconList) }); } }, /** * @Description: 创建飞线图及高亮站点 * @author konghaitao * @date 2023-2-20 * @params arr 飞线图数组 iconList 图标数组 */ renderLayerMark(arr,iconList){ //倒叙创建覆盖 let that = this let colors = [ "#FF0000", "#FFC402", "#4E79E9", ]; let icons = [this.redIcon,this.yellowIcon] that.clearMap() layer3 = new Loca.LinkLayer({ map: that.map, fitView: false, }); layer3.setData(arr[2], { lnglat: 'lnglat' }); layer3.setOptions({ style: { // 曲率 [-1, 1] 区间 curveness: function(data) { if(data.value.dis < 300){ return 0.005; } else { return 0.001; } }, borderWidth: 1.5, width: 1, opacity: 0.8, color: colors[2] } }); layer2 = new Loca.LinkLayer({ map: that.map, fitView: false, }); layer2.setData(arr[1], { lnglat: 'lnglat' }); layer2.setOptions({ style: { // 曲率 [-1, 1] 区间 curveness: function(data) { if(data.value.dis < 300){ return 0.005; } else { return 0.001; } }, width: 1, opacity: 0.8, color: colors[1] } }); layer1 = new Loca.LinkLayer({ map: that.map, fitView: false, }); layer1.setData(arr[0], { lnglat: 'lnglat' }); layer1.setOptions({ style: { // 曲率 [-1, 1] 区间 curveness: function(data) { if(data.value.dis < 300){ return 0.005; } else { return 0.001; } }, width: 1, opacity: 0.8, color: colors[0] } }); layer1.render(); layer2.render(); layer3.render(); if(iconList){ markIcon2 = new Loca.IconLayer({ map: that.map, fitView: true, }); markIcon2.setData(iconList[1], { lnglat: 'center' }); markIcon2.setOptions({ source: function (res) { return icons[1]; }, style: { size: 28, } }); markIcon2.render(); markIcon1 = new Loca.IconLayer({ map: that.map, fitView: true, }); markIcon1.setData(iconList[0], { lnglat: 'center' }); markIcon1.setOptions({ source: function (res) { return icons[0]; }, style: { size: 28, } }); markIcon1.render(); } that.$nextTick(()=>{ that.isLoading = false; }) }, changeFlowEvent(data) { // let params = this.searchParams; switch (this.nowIndex) { case 0: this.getStationOD() break case 1: break case 2: this.getStationOfAreaInfo(this.searchId, data); this.getStationPathOfAreaInfo(this.searchId, data) // 自定义区域Od线 break } }, getStationOfAreaInfo(id, data) { let params = this.searchParams; params.id = id; params.flowChoose = data; params.top = 1000; this.searchId = id; API_PASSENGEROD .getStationOfAreaInfo(params) .then((response) => { if (response.code === 0) { this.odTableList = response.value } else { console.log(response.message); } }) .catch((error) => { this.$message.error(error); }); }, getStationPathOfAreaInfo(data, status) { console.log(data.id,'aaaa') var that = this; this.odLineData = []; this.isLoading = true; let params = { id:data.id, startTime:data.startTime, endTime:data.endTime, peakSection:data.peakSection, isWeekday:data.isWeekday, flowChoose:data.flowChoose, ODNumBefore: this.sliderOdLine[0], ODNumAfter:this.sliderOdLine[1], } API_PASSENGEROD .getStationPathOfAreaInfo2(params) .then((response) => { if (response.code === 0) { this.legendList.oDNumMin = response.value.oDNumMin; this.legendList.oDNumMid = response.value.oDNumMid; this.legendList.oDNumMax = response.value.oDNumMax; let keyData = [0, this.legendList.oDNumMin, this.legendList.oDNumMid, this.legendList.oDNumMax]; let valData = [String(0), String(this.legendList.oDNumMin), String(this.legendList.oDNumMid), String( this.legendList.oDNumMax)] let obj = {}; for (let i = 0; i < valData.length; i++) { const key = keyData[i]; obj[key] = valData[i] } this.marks = obj; if(status) { this.sliderOdLine = [0, this.legendList.oDNumMax] } that.odLineData = response.value this.areaOdLineMap(); } else { this.isLoading = false; console.log(response.message); } }) .catch((error) => { this.isLoading = false; this.$message.error(error); }); }, // 区域od线 areaOdLineMap(){ var that = this; if(areaPathSimplifierIns !== null){ showAreaLine(); } else { AMapUI.load(['ui/misc/PathSimplifier', 'lib/$'], function (PathSimplifier, $) { if (!PathSimplifier.supportCanvas) { alert('当前环境不支持 Canvas!'); return; } let oDMaxList = that.odLineData.oDMaxList let oDMidList = that.odLineData.oDMidList let oDMinList = that.odLineData.oDMinList let arr = [oDMaxList,oDMidList,oDMinList] that.renderLayerMark(arr) }); } }, // 初始化地图 initMap() { lazyAMapApiLoaderInstance.load().then(() => { this.map = new AMap.Map(document.getElementById("container"), { mapStyle: "amap://styles/9824f612cff8dc63104cff89ddfd1a93", expandZoomRange: true, zoom: 13, zooms: [3, 21], resizeEnable: false, center: [117.38, 32.92], keyboardEnable: false, zoomEnable: true, dragEnable: true, animateEnable: true, viewMode: '3D', pitch: 30, }); }); }, }, mounted() { this.$bus.$on('checkMode', (data) => { this.checkMode(data); if(data.type == 1){ //type为1 新增区域模块 this.editingStatus = !data.isSelect; } }) console.log('aaaaaaaaaaaa') this.initMap(); }, created() { }, beforeDestroy() { this.$bus.$off("checkMode"); this.map = null; stationPathSimplifierIns = null; linePathSimplifierIns = null; lineStationPathSimplifierIns = null; areaPathSimplifierIns = null; this.clearMap() }, } </script> <style lang="scss" scoped> // PX 转 rem @function px2Rem($px, $base-font-size: 19.2px) { @if (unitless($px)) { //有无单位 @return ($px / 19.2) * 1rem; } @else if (unit($px)==em) { @return $px; } @return ($px / $base-font-size) * 1rem; } .passengerflowOd-wrap { .left-wrap { .modeList { float: left; position: relative; } .mode { width: px2Rem(150px); height: px2Rem(40px); text-align: center; line-height: px2Rem(40px); background-color: #fff; margin-right: px2Rem(10px); } .mask { position: absolute; left: 0px; top: 0px; width: px2Rem(150px); height: px2Rem(40px); border: 2px solid #2894ec; } } // 图例 .legend-map { position: absolute; bottom: px2Rem(55px); right: 28%; width: px2Rem(80px); height: px2Rem(100px); display: flex; justify-content: space-between; flex-direction: column; color: #fff; background: #001539; box-shadow: 0px 0px 8px 2px rgba(16, 108, 222, 0.8); border-radius: 4px; opacity: 0.8; z-index: 100; .item { height: px2Rem(30px); display: flex; flex-direction: row; // justify-content: start; justify-content: space-around; align-items: center; font-size: px2Rem(14px); margin: 0 15px 0px; .base-color { width: px2Rem(15px); height: px2Rem(6px); border-radius: 2px; } .color-0 { background: #FF0000; } .color-1 { background: #FFC402; } .color-2 { background: #4E79E9; } } } .od-line { position: absolute; bottom: px2Rem(55px); left: 28%; z-index: 100; font-size: px2Rem(18px); color: #fff; .od-slider { margin-top: px2Rem(10px); padding: px2Rem(7px) px2Rem(15px); width: px2Rem(250px); height: px2Rem(60px); background: #001539; box-shadow: 0px 0px 8px 2px rgba(16, 108, 222, 0.8); border-radius: 4px; z-index: 100; } } .siteSearch { position: absolute; top: px2Rem(100px); right: 28%; z-index: 100; } .areaName { position: absolute; bottom: px2Rem(55px); right: 28%; z-index: 100; } } </style> <style lang="scss"> // PX 转 rem @function px2Rem($px, $base-font-size: 19.2px) { @if (unitless($px)) { //有无单位 @return ($px / 19.2) * 1rem; } @else if (unit($px)==em) { @return $px; } @return ($px / $base-font-size) * 1rem; } // 站点名样式 .amap-marker-label { position: absolute; border: none; background-color: transparent; white-space: nowrap; cursor: pointer; padding: 3px; font-size: 9px; font-family: AlibabaPuHuiTiR; color: #ffffff; // l } </style> 分析当前代码,首次切换模块打印new Loca.LinKLayer报错,强制刷新后Loca功能才可使用,排查下原因
06-18
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值