天地图 轨迹AnimatedMarker

若依框架页面中写入的实际例子

需要npm install一些内容

1.有冗余内容偷懒没有删除

2.因为之前不明白 所以此处使用z-index和透明opacity,使地图不会无法获取容器,

实际用弹框时,可以this.$nextTick()或者setTimeout保证容器加载出来后再初始化地图,

可以用flag来判断是否是第一次加载地图,不是第一次则不用再加载

<template>
  <div class="app-container">
    <div class="main" v-show="!open2" style="width:100%;height:100%;background:#fff;position:relative;z-index:100">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="自编号" prop="treeCode">
          <el-input v-model="queryParams.treeCode" placeholder="请输入古树编号" clearable @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item label="车牌号" prop="treeName">
          <el-input v-model="queryParams.treeName" placeholder="请输入古树名称" clearable @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item label="所属单位" prop="ownRegion">
          <el-input v-model="queryParams.ownRegion" placeholder="请输入所属区划" clearable @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item label="使用单位" prop="proteLevel">
          <el-select v-model="queryParams.proteLevel" placeholder="请选择保护级别" clearable>
            <el-option v-for="dict in dict.type.scenicspot_manage_tree_rank" :key="dict.value" :label="dict.label"
              :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" size="mini" @click="handleQuery">搜索</el-button>
          <el-button size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb8">
        <!-- <el-col :span="1.5">
            <el-button type="primary" plain icon="el-icon-add1" size="mini" @click="handleAdd"
              v-hasPermi="['garden:garden_manage_tree:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="primary" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
              v-hasPermi="['garden:garden_manage_tree:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="primary" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
              v-hasPermi="['garden:garden_manage_tree:remove']">删除</el-button>
          </el-col> -->
        <el-col :span="1.5">
          <el-button type="primary" plain icon="el-icon-export1" size="mini" @click="handleExport"
            v-hasPermi="['garden:garden_manage_tree:export']">导出</el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <el-table size="medium" height="65vh" v-loading="loading" :data="list" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="序号" align="center" prop="treeId" fixed="left" />
        <!-- <el-table-column label="古树编号" align="center" prop="treeCode" width="82"/> -->
        <el-table-column label="自编号" align="center" prop="treeName" />
        <el-table-column label="车牌号" align="center" prop="treeSpecie" />
        <el-table-column label="日期" align="center" prop="preType" />
        <el-table-column label="首次点火时间" align="center" prop="ownRegion" width="100" />
        <el-table-column label="最后点火时间" align="center" prop="treeStats" width="100" />
        <el-table-column label="点火时长" align="center" prop="treeSubject" />
        <el-table-column label="出车时间" align="center" prop="treeAge" />
        <el-table-column label="收车时间" align="center" prop="proteLevel" />
        <el-table-column label="非运行时长" align="center" prop="plantYear" width="90" />
        <el-table-column label="运行时长" align="center" prop="plantYear" />
        <el-table-column label="行驶里程(km)" align="center" prop="plantYear" width="100" />
        <el-table-column label="最后更新时间" align="center" prop="plantYear" width="100" />
       <el-table-column label="" align="center" prop="" width="50" />
      <el-table-column fixed="right" label="操作" align="center" class-name="small-padding fixed-width" width="120">
          <template slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-see" @click="goMap(scope.row)"
              v-hasPermi="['garden:garden_manage_tree:edit']">查看轨迹</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
        @pagination="getList" />
    </div>


    <!-- 地图 -->
    <div class="mapDiv" style="width:100%;height:100%;position:absolute;top:0;left:0;background:#fff;z-index:1"
      id="mapContainerTD">
      <i v-if="open2" class="el-icon-close hover"
        style="color:blue;margin-left: 5%;position: absolute;top: 2%;right:10px;z-index:999" @click="closeMap"></i>
      <div id="app">
        <div v-if="open2" class="style-change" style="width:230px;position:absolute;top:1%;left:1%;z-index:999">
          <div style="display: flex;align-items: center;">
            <el-input size="mini" type="text" v-model="formData.coordinates[0]" placeholder="请输入纬度" clearable="clearable"
              @clear="clearHandle">
            </el-input>
            <el-button size="mini" icon="el-icon-search" type="primary" @click="markerPoint()"
              style="margin-left: 5%;"></el-button>
          </div>
          <div style="display: flex;align-items: center;width:76%">
            <el-input size="mini" type="text" v-model="formData.coordinates[1]" placeholder="请输入经度" clearable="clearable"
              @clear="clearHandle"></el-input>
          </div>
        </div>
        <div ref="diKuaiIdXiang" class="koi-body" id="myMap" style="height:100%;width:100%"></div>

      </div>

    </div>
  </div>
</template>

<script>
import { listScenicspot_manage_tree, getScenicspot_manage_tree, delScenicspot_manage_tree, addScenicspot_manage_tree, updateScenicspot_manage_tree } from "@/api/garden/garden_manage_tree";
import AMapLoader from '@amap/amap-jsapi-loader'; //引入
require('leaflet.animatedmarker/src/AnimatedMarker');//移动
import 'leaflet-polylinedecorator' //绘制带箭头的线
import L from 'leaflet';
require('leaflet/dist/leaflet.css')

// 封装使用vue+leaflet.chinatmsproviders,显示中国地图,
// npm i leaflet.chinatmsproviders --save
// cnpm install leaflet --save
import 'leaflet.tilelayer.colorfilter';
import Provider from '@/components/chinatmsproviders';

import qsh from '@/components/geojson/qsh.json'
import bygy from '@/components/geojson/bygy.json'
import fhgy from '@/components/geojson/fhgy.json'
import rmgy from '@/components/geojson/rmgy.json'
import green from '@/components/geojson/green.json'
import china from '@/components/geojson/china.json'
export default {
  name: "Scenicspot_manage_tree",
  dicts: ['scenicspot_manage_tree_rank'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 古树名木表格数据
      list: [{ t1: 1 }],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        treeCode: null,
        treeName: null,
        ownRegion: null,
        proteLevel: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      clickindex: 0,
      //   isExpand: true,
      isLoading: false,
      formData: {
        keyword: '',
        coordinates: [null, null],
      },
      styleOptions: [
        {
          label: '幻影黑',
          value: 'dark',
        },
        {
          label: '月光银',
          value: 'light',
        },
      ],
      aMap: null,
      route: null,
      placeSearch: null,
      active: -1,
      timer: null,
      marker: null,
      position: [],
      open2: false,
      lng: '',
      lat: '',
      lng1: '',
      lat1: '',
      carMarker: [[], [], [], [], []],
      deviceMarker: [[], [], [], []],
      staffMarker: [[]],
      staffState: 0,
      geo: [],
      mylayerGroup: [],
      state: 'Satellite',
      green: [],
      mapKey: '86cacccdaad6c7fb8ae3249c71a3ce0c', //你的key
      map: null,
      normalMap: null,
      satelliteMap: null,
      terrainMap: null,
      fistTomap: true,
      markers: [],
      line: [],
      animatedMarker: null,
      realRouteLine: null,//橙色实时轨迹线
      newLatlngs: [],

    };
  },
  created() {
    this.getList();
  },
  computed: {
    sectionStr() {
      return JSON.stringify(this.formData.coordinates.map((item) => item.split(',').map((v) => +v)))
    },
  },
  mounted() {
    setTimeout(() => {
      // this.initMap()
      Provider(L) // 挂载插件

      this.getMap()
    }, 1000)
  },
  methods: {
    goMap() {
      var mapDiv = document.querySelector('.mapDiv')
      mapDiv.style.opacity = 1


      this.open = false
      this.open2 = true
      // this.getIconMove()
      this.getMove()

    },
    getMap() {
      let _this = this
      let myCenter = new L.LatLng(39.898457, 116.391844)
      // 封装方法,不然要重复写很多次
      function mapLoad(value) {
        return L.tileLayer.chinaProvider(`TianDiTu.${value}`, {
          // maxZoom: 15,
          // minZoom: 10,
          key: _this.mapKey,
          doubleClickZoom: false,
        })
      }

      // 定义地图图层,官方api有

      var norMap = mapLoad('Normal.Map'),
        norAnnotion = mapLoad('Normal.Annotion'),
        sateMap = mapLoad('Satellite.Map'),
        sateAnnotion = mapLoad('Satellite.Annotion'),
        terMap = mapLoad('Terrain.Map'),
        terAnnotion = mapLoad('Terrain.Annotion');
      this.normalMap = L.layerGroup([norMap, norAnnotion]),// 矢量
        this.satelliteMap = L.layerGroup([sateMap, sateAnnotion]), // 卫星
        this.terrainMap = L.layerGroup([terMap, terAnnotion]); // 地形
      this.map = L.map('myMap', {
        center: myCenter,
        zoom: 13,
        layers: [this.normalMap], //默认图层展示
        doubleClickZoom: false,
        zoomControl: false,//隐藏自带的缩放控件
        attributionControl: false  //去掉右下角的logo
      })



      /**开始轨迹移动
*/



      //显示鼠标点击位置的经纬度
      // this.map.on('click', function (e) {
      //   if (_this.marker) {
      //     _this.map.removeLayer(_this.marker)
      //   }
      //   _this.getPointer(e.latlng.lat, e.latlng.lng)
      //   _this.$set(_this.formData, 'coordinates', [e.latlng.lat, e.latlng.lng])

      //   console.log(e.latlng)
      //   // L.popup().setLatLng(e.latlng).setContent(e.latlng.toString()).openOn(this.map)
      // })

    },

    //带箭头
    getMove() {
      var that = this
      var latlngs = [
        [39.898457, 116.391844],
        [39.898595, 116.377947],
        [39.898341, 116.368001],
        [39.898063, 116.357144],
        [39.899095, 116.351934],
        [39.905871, 116.350670],
        [39.922329, 116.349800],
        [39.931017, 116.349671],
        [39.939104, 116.349225],
        [39.942233, 116.349910],
        [39.947263, 116.366892],
        [39.947568, 116.387537],
        [39.947764, 116.401988],
        [39.947929, 116.410824],
        [39.947558, 116.426740],
        [39.939700, 116.427338],
        [39.932404, 116.427919],
        [39.923109, 116.428377],
        [39.907094, 116.429583],
        [39.906858, 116.414040],
        [39.906622, 116.405321],
        [39.906324, 116.394954],
        [39.906308, 116.391264],
        [39.916611, 116.390748]
      ];
      var speedList = [1, 1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 4, 4, 5, 5, 4, 4, 4, 3, 2, 2, 1, 1, 1]//speedList数组长度需要与坐标点位长度相同,且一一对应
      // 轨迹线
      var routeLine = L.polyline(latlngs, {
        weight: 8
      }).addTo(that.map);
      // 实时轨迹线
      that.realRouteLine = L.polyline([], {
        weight: 8,
        color: '#FF9900'
      }).addTo(that.map);
      // 轨迹方向箭头
      var decorator = L.polylineDecorator(routeLine, {
        patterns: [{
          repeat: 50,
          symbol: L.Symbol.arrowHead({
            pixelSize: 5,
            headAngle: 75,
            polygon: false,
            pathOptions: {
              stroke: true,
              weight: 2,
              color: '#FFFFFF'
            }
          })
        }]
      }).addTo(that.map);

      var carIcon = L.icon({
        iconSize: [37, 40],
        iconAnchor: [19, 20],
        iconUrl: require('@/assets/images/car.png')
      })
      // 动态marker
      that.animatedMarker = L.animatedMarker(routeLine.getLatLngs(), {
        speedList: speedList,
        interval: 1000, // 默认为100mm 默认速度是 100米/100毫秒
        autoStart: true,
        icon: carIcon,
        playCall: updateRealLine
      }).addTo(that.map)
      that.newLatlngs = [routeLine.getLatLngs()[0]]

      // 绘制已行走轨迹线(橙色那条)
      function updateRealLine(latlng) {
        console.log(1)
        that.newLatlngs.push(latlng)
        that.realRouteLine.setLatLngs(that.newLatlngs)
      }



      that.animatedMarker.on('move', res => { // 监听点位移动事件 move
        // console.log('move',res)
        // this.map.panTo([res.latlng.lat, res.latlng.lng]) //回调中会返回经纬度信息,点移动改变地图中心点
        // path.length > 1 && path.shift() // 保持数组长度,避免过度push不断重新绘制之前的路径
        that.newLatlngs.push([res.latlng.lat, res.latlng.lng])
        that.realRouteLine.setLatLngs(that.newLatlngs)
      })

    },

    // 创建路线和移动icon
    getIconMove() {
      var that = this

      //添加自定义图标
      var bikeIcon = L.icon({
        //图标地址
        iconUrl: require('@/assets/images/tree.png'),
        //图标大小
        iconSize: [40, 50]
      });

      //轨迹线数组
      this.line = L.polyline([[28.68538533236103, 115.91], [28.68538533236103, 115.9175], [28.68538533236103, 115.9178]])
      //  L.polyline([[28.6853, 115.91752731885802], [28.68535, 115.91752731885802], [28.6854, 115.91752731885802]]),

      const lines = L.polyline([[28.68538533236103, 115.91], [28.68538533236103, 115.9175], [28.68538533236103, 115.9178]], { color: '#3387FE' }).addTo(this.map)

      this.animatedMarker = L.animatedMarker(this.line.getLatLngs(), {
        autoStart: false,
        // distance: 10,  // meters
        // interval: 1000, // milliseconds
        icon: bikeIcon,
        onEnd: function () {
          //移动结束后移除
          that.map.removeLayer(that.animatedMarker);
        }
      });
      that.animatedMarker.setSpeetX(2);

      //在新位置添加标注
      this.map.addLayer(this.animatedMarker);
      this.animatedMarker.start()
      setInterval(() => {
        that.animatedMarker = L.animatedMarker(this.line.getLatLngs(), {
          autoStart: false,
          // distance: 10,  // meters
          // interval: 1000, // milliseconds
          icon: bikeIcon,
          onEnd: function () {
            //移动结束后移除
            that.map.removeLayer(that.animatedMarker);
          }
        });
        that.animatedMarker.setSpeetX(2);
        //在新位置添加标注
        that.map.addLayer(that.animatedMarker);
        that.animatedMarker.start()
      }, 5000)

    },
    // 标点函数
    getPointer(lat, lng) {
      let that = this
      that.map.setView([lat, lng])

      this.form.lat = lat
      this.form.lng = lng
      console.log('??')
      this.marker = L.marker([lat, lng]).addTo(this.map);
      // create popup contents
      var customPopup = `<div style='width:100%;color:#fff'>
                      <div style='padding-top:7px;padding-left:30px'>1</div>
                      <div style='padding-top:20px;padding-left:30px'>1</div>
                      <div style='padding-top:5px;padding-left:30px'>xxx</div>
                      <div style='padding-top:5px;padding-left:30px'>xxx</div>
                      <div id='btn' style='cursor:pointer;margin-top:10px;box-shadow: inset 0px 0px 19px 1px #2077F8;width:30%;text-align:center;height: 31px;line-height: 31px;margin-left:35%'>查看详情</div>
                  </div>`;

      // specify popup options
      var customOptions =
      {
        'minWidth': '312',
        'className': 'custom'
      }
      this.map.addLayer(this.marker) // 添加标记

      this.marker.setIcon(L.icon({   // 标记配置-详见leaflet官网
        iconUrl: require('@/assets/images/map_icon_per.png'), // 使用require加载标记图
        iconSize: [30, 50],
      }))

      this.map.on('popupopen', function () {
        document.getElementById('btn').onclick = function (e) {
          console.log('跳转到详情页面的方法', e)
          // that.goUrl(type, i)

        }
      })

      this.marker.bindPopup(customPopup, customOptions) // 默认展开标记点击弹窗
      // marker.bindTooltip(res.name).openTooltip() //默认展开tooltip




      // 自定义其他事件
      this.marker.on('click', () => {
        console.log('标记的可自定义点击事件');
      });

    },
    markerPoint() {
      console.log([Number(this.formData.coordinates[0]), Number(this.formData.coordinates[1])])
      if (this.marker) {
        this.map.removeLayer(this.marker)
        this.marker = null
      }
      this.getPointer(this.formData.coordinates[0], this.formData.coordinates[1])

      this.form.lat = this.formData.coordinates[0]
      this.form.lng = this.formData.coordinates[1]

    },
    all(index, val) {
      if (index == 2) {
        if (val == true) {
          this.deviceData.forEach((currentValue, index) => {
            if (currentValue.length != 0) {
              this.getPointer(currentValue, 'deviceMarker', index)
            }

          })
        } else {
          this.deviceMarker.forEach((currentValue, index) => {
            if (currentValue.length != 0) {
              this.clearPoint('deviceMarker', index)
            }

          })
        }
      }
      if (index == 3) {
        if (val == true) {
          this.carData.forEach((currentValue, index) => {
            if (currentValue.length != 0) {
              this.getPointer(currentValue, 'carMarker', index)
            }

          })
        } else {
          this.carMarker.forEach((currentValue, index) => {
            if (currentValue.length != 0) {
              this.clearPoint('carMarker', index)
            }

          })
        }
      }

    },
    calc(index) {

      if (index == 1) {
        if (this.geo[0]) {
          this.map.removeLayer(this.geo[0])
        }
        if (this.geo[1]) {
          this.map.removeLayer(this.geo[1])
        }
        if (this.geo[2]) {
          this.map.removeLayer(this.geo[2])
        }
        if (this.geo[3]) {
          this.map.removeLayer(this.geo[3])
        }
        this.checkedCities1.forEach((currentValue, index) => {
          if (currentValue.id == 'qsh') {
            this.geo[0] = L.geoJson(qsh).addTo(this.map)
          }
          else if (currentValue.id == 'bygy') {
            this.geo[1] = L.geoJson(bygy).addTo(this.map)
          }
          else if (currentValue.id == 'fhgy') {
            this.geo[2] = L.geoJson(fhgy).addTo(this.map)
          }
          else if (currentValue.id == 'rmgy') {
            this.geo[3] = L.geoJson(rmgy).addTo(this.map)
          }

        })
        // this.mylayerGroup = L.layerGroup([this.marker[0], this.marker[1], this.marker[2],this.marker[3] ])
        // this.map.addLayer(this.mylayerGroup)

      }

    },
    addMarker(pos) {
      console.log('pos', pos)
      if (this.marker) {
        this.aMap.remove(this.marker)
      }
      console.log('1')
      this.marker = new AMap.Marker({
        position: pos
      })
      console.log('2')

      this.aMap.add(this.marker)
      console.log('3')


    },

    closeMap(e) {
      var mapDiv = document.querySelector('.mapDiv')
      mapDiv.style.opacity = 0
      this.open2 = false
      this.open = true

    },
    initMap() {
      AMapLoader.load({
        key: '523c9fc07c690089f319101a72c2c13e',
        version: '2.0Beta',
        // 'key': '	523c9fc07c690089f319101a72c2c13e', // 申请好的Web端开发者Key,首次调用 load 时必填
        // 'version': '2.0Beta' // 指定要加载的 JSAPI 的版本,缺省时默认为 1.4.15
        plugins: ['AMap.DragRoute', 'AMap.PlaceSearch'], // 需要使用的的插件列表,如比例尺'AMap.Scale'等
        // 'AMapUI': { // 是否加载 AMapUI,缺省不加载
        //   'version': '1.1', // AMapUI 缺省 1.1
        //   'plugins': [] // 需要加载的 AMapUI ui插件
        // },
        // 'Loca': { // 是否加载 Loca, 缺省不加载
        //   'version': '1.3.2' // Loca 版本,缺省 1.3.2
        // }
      })
        .then((AMap) => {
          this.aMap = new window.AMap.Map('coordinate-acquisition', {
            zoom: 15,
            mapStyle: `amap://styles/${this.formData.style}`,
            center: [115.86452, 28.68767], //初始化地图中心点位置
            resizeEnable: true
          })

          // 构造地点查询类
          this.placeSearch = new window.AMap.PlaceSearch({
            pageSize: 5, // 单页显示结果条数
            pageIndex: 1, // 页码
            // city: '010', // 兴趣点城市
            // citylimit: true, // 是否强制限制在设置的城市内搜索
            map: this.aMap, // 展现结果的地图实例
            panel: 'search-result', // 结果列表将在此容器中进行展示。
            autoFitView: true, // 是否自动调整地图视野使绘制的 Marker点都处于视口的可见范围,

          })

          this.placeSearch.on('markerClick', () => {
            this.aMap.setZoom(15)
          })

          var that = this
          this.aMap.on('click', (e) => {
            console.log(e)
            if (that.marker) {
              that.aMap.remove(that.marker)
            }

            that.marker = new AMap.Marker({
              position: [e.lnglat.lng, e.lnglat.lat]
            })
            that.position = [e.lnglat.lng, e.lnglat.lat]
            that.aMap.add(that.marker)

          })
        })
        .catch((e) => {
          console.log(e)
        })
    },

    clearHandle() {
      this.$refs.searchResult.innerHTML = ''
    },
    posSearchHandle() {
      // 关键字查询
      this.formData.keyword && this.placeSearch.search(this.formData.keyword)
    },
    setMapStyle() {
      let styleName = 'amap://styles/' + this.formData.style
      this.aMap.setMapStyle(styleName)

      // this.aMap.setZoom(13)
    },
    activeHandle(i) {
      if (this.active === i) {
        this.active = -1
      } else {
        this.active = i
      }
    },
    /** 查询古树名木列表 */
    getList() {
      this.loading = false;

      // this.loading = true;
      // listScenicspot_manage_tree(this.queryParams).then(response => {
      //   this.scenicspot_manage_treeList = response.rows;
      //   this.total = response.total;
      //   this.loading = false;
      // });
    },
    // 取消按钮
    cancel() {
      if (this.marker) {
        this.map.removeLayer(this.marker)
      }
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        treeId: null,
        treeCode: null,
        treeName: null,
        treeSpecie: null,
        preType: null,
        ownRegion: null,
        treeStats: null,
        treeSubject: null,
        treeAge: null,
        proteLevel: null,
        plantYear: null,
        treeHigh: null,
        treeDiameter: null,
        treeCrown: null,
        custodUnit: null,
        intro: null,
        detailAddr: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.treeId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加古树名木";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const treeId = row.treeId || this.ids
      getScenicspot_manage_tree(treeId).then(response => {
        this.form = response.data;
        console.log(this.form)
        if (this.form.lng && this.form.lat) {
          console.log(this.form.lng, this.form.lat)
          this.formData.coordinates = [this.form.lat, this.form.lng]

          // var pos = coordtransform.wgs84togcj02(this.form.lng, this.form.lat)



          // this.addMarker(pos)
          // this.aMap.setZoomAndCenter(15, pos)

          // 指定中心点
          let center = L.latLng(this.form.lat, this.form.lng);
          this.getPointer(this.form.lat, this.form.lng);
          this.map.setView(center);

        }
        this.open = true;
        this.title = "修改古树名木";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.treeId != null) {

            updateScenicspot_manage_tree(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addScenicspot_manage_tree(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.position = []
              this.getList();
            });
          }

          if (this.marker) {
            this.map.removeLayer(this.marker)
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const treeIds = row.treeId || this.ids;
      this.$modal.confirm('是否确认删除古树名木编号为"' + treeIds + '"的数据项?').then(function () {
        return delScenicspot_manage_tree(treeIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('garden/garden_manage_tree/export', {
        ...this.queryParams
      }, `${this.$route.meta.title}${this.getCurrentDate()}.xlsx`)
    }
  }
};
</script>
<style lang="less" scoped>
.hover:hover {
  cursor: pointer;
}

.el-upload__tip {
  display: none;
}

.addForm {
  .el-form-item {
    .el-input {
      width: 200px;
    }

    .el-form-item__label {
      color: #222;
      font-weight: normal;
      font-family: Source Han Sans CN, Source Han Sans CN;
    }

    .el-input--suffix {
      height: 32px
    }

    .el-input__inner {
      height: 32px
    }

    .el-input__icon {
      line-height: 32px
    }


  }
}

.popTop {
  display: flex;
  align-items: center;
  margin-bottom: 10px
}

.popBlue {
  width: 4px;
  height: 15px;
  border-radius: 2px;
  background: #3387FE
}

.popTitle {
  color: #222;
  font-size: 15px;
  margin-left: 10px;
  font-weight: bold
}

.mapDiv {
  opacity: 0
}

#app,
body,
html {
  height: 100%;
  padding: 0;
  margin: 0;
  position: relative
}

.coordinate-acquisition-wraper {
  height: 100%;
  position: relative;
  font-family: PingFangSC, PingFang SC;
}

.coordinate-acquisition-wraper .style-change span {
  font-size: 14px;
  font-weight: bold;
  font-family: PingFangSC, PingFang SC;
}

/* .coordinate-acquisition-wraper .filter-wrap {
      border-right: 1px solid #ddd;
      position: absolute;
      z-index: 7;
      height: 100%;
      background-color: #fff;
      transition: left 0.3s;
      padding: 10px 0 10px 10px;
      width: 397px;
      box-sizing: border-box;
      left: -397px;
  } */

/* .coordinate-acquisition-wraper .filter-wrap.expand {
      left: 0;
  } */
.koi-body {
  position: relative;
  /* pointer-events: none; */

}

.coordinate-acquisition-wraper .filter-wrap>.el-icon {
  cursor: pointer;
  font-size: 18px;
  position: absolute;
  right: -17px;
  height: 60px;
  line-height: 60px;
  width: 16px;
  box-shadow: 1px 1px 2px rgba(0, 0, 0, 0.1);
  top: calc(50% - 30px);
  background-color: #fff;
  border-radius: 0 5px 5px 0;
}

.coordinate-acquisition-wraper .el-form {
  height: 100%;
  overflow: auto;
}

.coordinate-acquisition-wraper .el-form p {
  color: #888;
  text-shadow: 0 0 1px #fff;
  padding-left: 100px;
}

.coordinate-acquisition-wraper .el-form>.el-button {
  display: block;
  margin-left: 212px;
  margin-bottom: 10px;
}

.coordinate-acquisition-wraper .el-form .el-form-item {
  margin-bottom: 20px;
  padding-right: 10px;
}

.coordinate-acquisition-wraper .el-form .el-form-item .el-input.active .el-icon-s-promotion {
  color: #409eff;
}

.coordinate-acquisition-wraper .el-form .el-form-item .el-icon-s-promotion {
  cursor: pointer;
}

.coordinate-acquisition-wraper .el-form .el-form-item .el-form-item-error-tip {
  position: static;
}

.coordinate-acquisition-wraper .el-form .el-form-item .el-form-item__content {
  display: flex;
}

.coordinate-acquisition-wraper .el-form .el-form-item .el-button {
  margin-left: 3px;
}

.coordinate-acquisition-wraper .coordinate-acquisition {
  height: 100%;
}

.coordinate-acquisition-wraper .coordinate-acquisition.active .amap-layer {
  cursor: crosshair !important;
}

.coordinate-acquisition-wraper .coordinate-acquisition .amap-copyright,
.coordinate-acquisition-wraper .coordinate-acquisition .amap-logo {
  display: none !important;
}

.coordinate-acquisition-wraper .style-change {
  background: transform;
  width: 100px;
  position: absolute;
  z-index: 7;
  left: 10px;
  top: 10px;
}

.coordinate-acquisition-wraper .style-change .el-select {
  width: 120px;
}


.coordinate-acquisition-wraper .search-result {
  position: absolute;
  z-index: 7;
  top: 50px;
  right: 10px;
  max-height: calc(100% - 70px);
  overflow: auto;
}


#container {
  width: 100%;
  height: 100%;
  /* margin: 100px auto; */
  /* border: 2px solid red; */
}
</style>

  • 4
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是uniapp地图轨迹回放的步骤和代码示例: 1.引入地图组件和工具类 ```vue <template> <view> <map :longitude="longitude" :latitude="latitude" :polyline="polyline" :include-points="true" :show-location="true" :markers="markers" style="width: 100%; height: 100%;"></map> </view> </template> <script> import { wgs84togcj02 } from '@/utils/utils.js' export default { data() { return { longitude: 0, latitude: 0, polyline: [], markers: [] } }, onLoad() { // 获取轨迹点数据 const points = [ { longitude: 116.397477, latitude: 39.908692 }, { longitude: 116.397529, latitude: 39.908692 }, { longitude: 116.397529, latitude: 39.908692 }, { longitude: 116.397529, latitude: 39.908692 }, { longitude: 116.397529, latitude: 39.908692 }, { longitude: 116.397529, latitude: 39.908692 }, { longitude: 116.397529, latitude: 39.908692 }, { longitude: 116.397529, latitude: 39.908692 }, { longitude: 116.397529, latitude: 39.908692 }, { longitude: 116.397529, latitude: 39.908692 } ] // 将轨迹点数据转换为地图组件需要的格式 const polyline = [{ points: points.map(item => { const { longitude, latitude } = wgs84togcj02(item.longitude, item.latitude) return { longitude, latitude } }), color: '#0000FF', width: 10, borderWidth: 2, arrowLine: true }] // 将第一个点作为地图中心点 const { longitude, latitude } = points[0] // 将轨迹点数据转换为地图组件需要的格式 const markers = [{ id: 1, longitude, latitude, iconPath: '/static/images/location.png', width: 30, height: 30 }] this.longitude = longitude this.latitude = latitude this.polyline = polyline this.markers = markers } } </script> ``` 2.在工具类中添加wgs84togcj02方法 ```javascript /** * WGS84转GCJ02 * @param {Number} lng 经度 * @param {Number} lat 纬度 * @returns {Object} GCJ02坐标系下的经纬度 */ export function wgs84togcj02(lng, lat) { if (out_of_china(lng, lat)) { return { lng, lat } } else { let dlat = transformlat(lng - 105.0, lat - 35.0) let dlng = transformlng(lng - 105.0, lat - 35.0) let radlat = lat / 180.0 * PI let magic = Math.sin(radlat) magic = 1 - ee * magic * magic let sqrtmagic = Math.sqrt(magic) dlat = (dlat * 180.0) / ((a * (1 - ee)) / (magic * sqrtmagic) * PI) dlng = (dlng * 180.0) / (a / sqrtmagic * Math.cos(radlat) * PI) let mglat = lat + dlat let mglng = lng + dlng return { lng: mglng, lat: mglat } } } function transformlat(lng, lat) { let ret = -100.0 + 2.0 * lng + 3.0 * lat + 0.2 * lat * lat + 0.1 * lng * lat + 0.2 * Math.sqrt(Math.abs(lng)) ret += (20.0 * Math.sin(6.0 * lng * PI) + 20.0 * Math.sin(2.0 * lng * PI)) * 2.0 / 3.0 ret += (20.0 * Math.sin(lat * PI) + 40.0 * Math.sin(lat / 3.0 * PI)) * 2.0 / 3.0 ret += (160.0 * Math.sin(lat / 12.0 * PI) + 320 * Math.sin(lat * PI / 30.0)) * 2.0 / 3.0 return ret } function transformlng(lng, lat) { let ret = 300.0 + lng + 2.0 * lat + 0.1 * lng * lng + 0.1 * lng * lat + 0.1 * Math.sqrt(Math.abs(lng)) ret += (20.0 * Math.sin(6.0 * lng * PI) + 20.0 * Math.sin(2.0 * lng * PI)) * 2.0 / 3.0 ret += (20.0 * Math.sin(lng * PI) + 40.0 * Math.sin(lng / 3.0 * PI)) * 2.0 / 3.0 ret += (150.0 * Math.sin(lng / 12.0 * PI) + 300.0 * Math.sin(lng / 30.0 * PI)) * 2.0 / 3.0 return ret } function out_of_china(lng, lat) { return lng < 72.004 || lng > 137.8347 || lat < 0.8293 || lat > 55.8271 } ```

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值