vue+openlayers5学习总结(四)改装成vue的一些功能

9 篇文章 0 订阅
8 篇文章 0 订阅

1.实现的一些map基本功能

1.1成果展示

在这里插入图片描述

1.2 olmap/view/olmap.vue

<template>
<div>
  <div id="fullscreen" class="fullscreen">
    <div id="map" ref="rootmap" class="map"></div>
    <div class="sidepanel">
      <span class="sidepanel-title">Side Panel</span>
    </div>
   
    <div>
      <!-- <button @click="click001">切换地图源</button> -->
      <button @click="click002">移到成都</button>
      <!-- <button @click="click003">测量面积</button> -->
    </div>
  </div>
   <div id="mouseposition" ref="xyposition" :style="{marginTop:'100px'}"></div>
   </div>
   
</template>
<script>
import "ol/ol.css";
import { Map, View } from "ol";
import mapconfig from "../config/mapconfig";
import mapfunction from "../methods/mapfunction";
import {
  defaults as defaultControls,
  FullScreen,
  ScaleLine,
  MousePosition,
  ZoomToExtent
} from "ol/control.js";

//用于获取鼠标坐标
import mousePosition from "ol/control/MousePosition.js";
import { createStringXY } from "ol/coordinate.js";

//var chengdu = fromLonLat([11584612, 3588584]);
export default {
  data() {
    return {
      view:null,
      map: null,
      mouseposition,
      chengdu:[11584612, 3588584],
    };
  },
  mounted() {
    //console.log("chengdu" + this.chengdu);
    var mapcontainer = this.$refs.rootmap;
    var mapxyposition = this.$refs.xyposition;
    let myview = new View({
        // center: [11584612, 3588584],
        // zoom: 12
        // projection: "EPSG:4326",    //使用这个坐标系
        center: [mapconfig.x, mapconfig.y], //深圳
        zoom: mapconfig.zoom
      });
    this.view = myview;
    this.map = new Map({
      //约束地图整数倍缩放
      interactions: mapconfig.interactions,
      //地图控件
      controls: defaultControls().extend([
        new FullScreen({
          source: "fullscreen"
        }),
        new ScaleLine({
          source: "scaleline"
        }),
        //鼠标位置
        // new MousePosition({
        //   source: "mouseposition"
        // }),
        new MousePosition({
        coordinateFormat: createStringXY(4),
        projection: 'EPSG:3857',
        // comment the following two lines to have the mouse position
        // be placed within the map.
        className: 'custom-mouse-position',
        target:mapxyposition,
        undefinedHTML: '&nbsp;'
        }),
        //缩放到制定范围
        new ZoomToExtent({
          extent: [
            11584612.7791264898,
            3588584.284081122,
            11694612.9639063801,
            3698584.986909639
          ]
        })
      ]),
      target: mapcontainer,
      //地图图层
      layers: mapconfig.testmap(),
      loadTilesWhileAnimating: true,
      //地图视图
      view:myview, 
      
    });
   // console.log(this.map)
  },
  methods: {
    click001() {
      this.map.layers.setSource(source);
      alert("hello");
    },
    click002() {
      //alert("hello");
      //this.flyTo(this.chengdu,function(){});
      mapfunction.flyTo(this.chengdu,this.view,function(){})
    },
  }
};
</script>

<style scoped>
.fullscreen:-moz-full-screen {
  height: 100%;
}
.fullscreen:-webkit-full-screen {
  height: 100%;
}
.fullscreen:-ms-fullscreen {
  height: 100%;
}

.fullscreen:fullscreen {
  height: 100%;
}

.fullscreen {
  margin-bottom: 10px;
  width: 100%;
  height: 600px;
}

.ol-rotate {
  top: 3em;
}
.sidepanel {
  background: rgb(52, 63, 61);
  width: 20%;
  height: 100%;
  float: right;
}
.map {
  width: 80%;
  height: 100%;
  float: right;
}

.sidepanel-title {
  width: 100%;
  font-size: 1em;
  color: #ffffff;
  display: block;
  text-align: center;
}
</style>

1.3 olmap/methods/mapfunction.js

//用于飞往成都
import { fromLonLat } from 'ol/proj.js';
import { easeIn, easeOut } from 'ol/easing.js'
var flyTo = function(location, view, done) {
    var duration = 2000;

    var zoom = view.getZoom();
    console.log("zoom" + zoom);
    var parts = 2;
    var called = false;

    function callback(complete) {
        --parts;
        if (called) {
            return;
        }
        if (parts === 0 || !complete) {
            called = true;
            done(complete);
        }
    }
    view.animate({
        center: location,
        duration: duration
    }, callback);
    view.animate({
        zoom: zoom - 1,
        duration: duration / 2
    }, {
        zoom: zoom,
        duration: duration / 2
    }, callback);
}


var mapfunction = {
    //飞往成都
    flyTo,
};

export default mapfunction;

1.4olmap/config/mapconfig.js

import TileLayer from "ol/layer/Tile";
import TileArcGISRest from "ol/source/TileArcGISRest";
import OSM from "ol/source/OSM";
import XYZ from "ol/source/XYZ";
import TileImage from "ol/source/TileWMS";
//用于缩放比例
import { defaults as defaultInteractions, PinchZoom } from "ol/interaction.js";
//矢量
import GeoJSON from 'ol/format/GeoJSON.js';
import VectorLayer from 'ol/layer/Vector.js';
import VectorSource from 'ol/source/Vector.js';
import { Fill, Stroke, Style, Text } from 'ol/style.js';

let mapsource = 2; //0表示部署的离线瓦片地图,1表示OSM,2表示使用Arcgis在线午夜蓝地图服务
//streetmap
var streetmap = function() {
    var maplayer = null;
    switch (mapsource) {
        case 0:
            maplayer = new TileLayer({
                source: new XYZ({
                    url: "http://127.0.0.1:7080/streetmap/shenzhen/{z}/{x}/{y}.jpg"
                })
            });
            break;
        case 1:
            maplayer = new TileLayer({
                source: new OSM()
            });
            break;
        case 2:
            maplayer = new TileLayer({
                source: new TileArcGISRest({
                    url: "https://map.geoq.cn/ArcGIS/rest/services/ChinaOnlineCommunity/MapServer"
                })
            });
            break;
            //arcgis切片
        case 3:
            maplayer = new TileLayer({
                source: new TileImage({
                    url: "https://map.geoq.cn/ArcGIS/rest/services/ChinaOnlineCommunity/MapServer"
                })
            });
            break;
    }
    return [maplayer];
};
//testmap
var testmap = function() {
    var layers = [
        new TileLayer({
            source: new TileArcGISRest({
                url: "https://map.geoq.cn/ArcGIS/rest/services/ChinaOnlineCommunity/MapServer"
            })
        }),
        new VectorLayer({
            title: "add Layer",
            source: new VectorSource({
                //projection: "EPSG:3857",
                //url: "../data/geojson/00.geojson", //GeoJSON的文件路径,用户可以根据需求而改变
                url: "../data/geojson/polygon-samples.geojson", //GeoJSON的文件路径,用户可以根据需求而改变
                format: new GeoJSON()
            })
        })
    ];
    return layers;
};
//约束地图整数倍缩放
var interactions = defaultInteractions({ pinchZoom: false }).extend([
    new PinchZoom({
        constrainResolution: true // force zooming to a integer zoom
    })
]);

var mapconfig = {
    // x: 114.064839, //中心点经度和纬度
    // y: 22.548857,
    x: 11584612,
    y: 3588584,
    zoom: 12, //地图缩放级别
    streetmap: streetmap,
    testmap: testmap,
    interactions: interactions,
};

export default mapconfig;

2.加载本地geojson

成果样例
在这里插入图片描述
olmap文件如下:

<template>
  <div>
    <div id="fullscreen" class="fullscreen">
      <div id="map" ref="rootmap" class="map"></div>
      <div class="sidepanel">
        <span class="sidepanel-title">Side Panel</span>
      </div>
    </div>
    <div id="info">&nbsp;</div>
    <h1>我是谁{{myinfo}}</h1>
  </div>
</template>
<script>
import "ol/ol.css";
import Feature from "ol/Feature.js";
import { Map, View } from "ol";
import GeoJSON from "ol/format/GeoJSON.js";
import VectorLayer from "ol/layer/Vector.js";
import VectorSource from "ol/source/Vector.js";
import { Fill, Stroke, Style, Text } from "ol/style.js";

var myshp = require("../data/geojson/countries.json");
export default {
  data() {
    return {
      featureOverlay: null,
      map: null,
      myinfo: ""
    };
  },
  mounted() {
    var mapcontainer = this.$refs.rootmap;
    const style = new Style({
      fill: new Fill({
        color: "rgba(255, 255, 255, 0.6)"
      }),
      stroke: new Stroke({
        color: "#319FD3",
        width: 1
      }),
      text: new Text({
        font: "12px Calibri,sans-serif",
        fill: new Fill({
          color: "#000"
        }),
        stroke: new Stroke({
          color: "#fff",
          width: 3
        })
      })
    });
    const vectorLayer = new VectorLayer({
      source: new VectorSource({
        features: new GeoJSON().readFeatures(myshp)
      }),
      style: function(feature) {
        style.getText().setText(feature.get("name"));
        return style;
      }
    });
    this.map = new Map({
      layers: [vectorLayer],
      target: mapcontainer,
      view: new View({
        projection: "EPSG:4326",
        center: [0, 0],
        zoom: 2
      })
    });
    const highlightStyle = new Style({
      stroke: new Stroke({
        color: "#f00",
        width: 1
      }),
      fill: new Fill({
        color: "rgba(255,0,0,0.1)"
      }),
      text: new Text({
        font: "12px Calibri,sans-serif",
        fill: new Fill({
          color: "#000"
        }),
        stroke: new Stroke({
          color: "#f00",
          width: 3
        })
      })
    });
    let highlight;
    const displayFeatureInfo = function(mymap,pixel) {
      console.log(mymap);
      const feature = mymap.forEachFeatureAtPixel(pixel, function(feature) {
        return feature;
      });
      const info = document.getElementById("info");
      if (feature) {
        info.innerHTML = feature.getId() + ": " + feature.get("name");
        //this.myinfo = feature.getId() + ": " + feature.get("name");
      } else {
        info.innerHTML = "&nbsp;";
      }
    };
    console.log(this);
    this.map.on("click", function(evt) {
      displayFeatureInfo(this,evt.pixel);
    });
  },
  methods: {}
};
</script>

<style scoped>
.fullscreen:-moz-full-screen {
  height: 100%;
}
.fullscreen:-webkit-full-screen {
  height: 100%;
}
.fullscreen:-ms-fullscreen {
  height: 100%;
}

.fullscreen:fullscreen {
  height: 100%;
}

.fullscreen {
  margin-bottom: 10px;
  width: 100%;
  height: 600px;
}

.ol-rotate {
  top: 3em;
}
.sidepanel {
  background: rgb(52, 63, 61);
  width: 20%;
  height: 100%;
  float: right;
}
.map {
  width: 80%;
  height: 100%;
  float: right;
}

.sidepanel-title {
  width: 100%;
  font-size: 1em;
  color: #ffffff;
  display: block;
  text-align: center;
}
</style>

3、后续功能

3.1按比例尺显示或隐藏两种地图

var testmap = function() {
    var layers = [
        new TileLayer({
            source: new OSM(),
            minResolution: 1,
            maxResolution: 500
        }),
        new TileLayer({
            source: new TileArcGISRest({
                url: "https://map.geoq.cn/ArcGIS/rest/services/ChinaOnlineCommunity/MapServer",
                crossOrigin: 'anonymous',
            }),
            //最大最小比例尺
            minResolution: 500,
            maxResolution: 20000
        }),
    ];
    return layers;
};

3.2控制地图最大最小缩放比例

mounted() {
    //console.log("chengdu" + this.chengdu);
    var mapcontainer = this.$refs.rootmap;
    var mapxyposition = this.$refs.xyposition;

    //缩放的最大比例尺
    const getMinZoom=function() {
        var width = mapcontainer.clientWidth;
        return Math.ceil(Math.LOG2E * Math.log(width / 256));
      }
    const getMaxZoom=function() {
        var width = mapcontainer.clientWidth;
        return Math.ceil(Math.LOG2E * Math.log(width / 0.02));
    }
    console.log(getMinZoom());
     console.log(getMaxZoom());
    let myview = new View({
        // center: [11584612, 3588584],
        // zoom: 12
        // projection: "EPSG:4326",    //使用这个坐标系
        
        minZoom:getMinZoom(),
        maxZoom:getMaxZoom(),
        center: [mapconfig.x, mapconfig.y], //深圳
        zoom: mapconfig.zoom
      });
    this.view = myview;
    this.map = new Map({
      //约束地图整数倍缩放
      interactions: mapconfig.interactions,
      //地图控件
      controls: defaultControls().extend([
        new FullScreen({
          source: "fullscreen"
        }),
        new ScaleLine({
          source: "scaleline"
        }),
        //鼠标位置
        // new MousePosition({
        //   source: "mouseposition"
        // }),
        new MousePosition({
        coordinateFormat: createStringXY(4),
        projection: 'EPSG:3857',
        // comment the following two lines to have the mouse position
        // be placed within the map.
        className: 'custom-mouse-position',
        target:mapxyposition,
        undefinedHTML: '&nbsp;'
        }),
        //缩放到制定范围
        new ZoomToExtent({
          extent: [
            11584612.7791264898,
            3588584.284081122,
            11694612.9639063801,
            3698584.986909639
          ]
        })
      ]),
      target: mapcontainer,
      //地图图层
      layers: mapconfig.testmap(),
      loadTilesWhileAnimating: true,
      //地图视图
      view:myview, 
      
    });
   // console.log(this.map)
  },

3.3获取map显示框边框四个角的坐标

3.3.1 DIV下代码

<div>
      <label>top</label>
      <input type="text" id="top">
      <label>right</label>
      <input type="text" id="right">
      <br>
      <label>bottom</label>
      <input type="text" id="bottom">
      <label>left</label>
      <input type="text" id="left">
    </div>

3.3.2mounted下代码

let self = this


    this.map.on("moveend", function(evt) {
      //console.log(this.map);
      
      self.onMoveEnd(evt);
      
    });

3.3.3methods下代码


display(id, value) {
      document.getElementById(id).value = value.toFixed(2);
    },
    wrapLon(value) {
      var worlds = Math.floor((value + 180) / 360);
      return value - worlds * 360;
    },
    onMoveEnd(evt) {
      var map = evt.map;
      //alert(map);
      var extent = map.getView().calculateExtent(map.getSize());
      var bottomLeft = toLonLat(getBottomLeft(extent));
      var topRight = toLonLat(getTopRight(extent));
      this.display("left", this.wrapLon(bottomLeft[0]));
      this.display("bottom", bottomLeft[1]);
      this.display("right", this.wrapLon(topRight[0]));
      this.display("top", topRight[1]);
    }

3.4拖拽gpx,geojson,igc,kml,topojson到地图中

import代码

import "ol/ol.css";
import { Map, View } from "ol";
import mapconfig from "../config/mapconfig";
import mapfunction from "../methods/mapfunction";
import {
  defaults as defaultControls,
  FullScreen,
  ScaleLine,
  MousePosition,
  ZoomToExtent
} from "ol/control.js";

//用于获取鼠标坐标
import mousePosition from "ol/control/MousePosition.js";
import { createStringXY } from "ol/coordinate.js";

//获取map四个角坐标
import { toLonLat } from "ol/proj.js";
import { getBottomLeft, getTopRight } from "ol/extent.js";
//拖动gpx,geojson,igc,kml,topojson到地图中
import { GPX, GeoJSON, IGC, KML, TopoJSON } from "ol/format.js";
import {
  defaults as defaultInteractions,
  DragAndDrop
} from "ol/interaction.js";
import { Vector as VectorLayer, Tile as TileLayer } from "ol/layer.js";
import { BingMaps, Vector as VectorSource } from "ol/source.js";

mounted中的代码

mounted() {
    let self = this;
    //console.log("chengdu" + this.chengdu);
    var mapcontainer = this.$refs.rootmap;
    var mapxyposition = this.$refs.xyposition;
    //拖动gpx,geojson,igc,kml,topojson到地图中
    var dragAndDropInteraction = new DragAndDrop({
      formatConstructors: [GPX, GeoJSON, IGC, KML, TopoJSON]
    });
    dragAndDropInteraction.on("addfeatures", function(event) {
      console.log(this);
      
      var vectorSource = new VectorSource({
        features: event.features
      });
      console.log(vectorSource);
      self.map.addLayer(
        new VectorLayer({
          renderMode: "image",
          source: vectorSource
        })
      );
      self.map.getView().fit(vectorSource.getExtent());
    });
    //缩放的最大比例尺
    const getMinZoom = function() {
      var width = mapcontainer.clientWidth;
      return Math.ceil(Math.LOG2E * Math.log(width / 256));
    };
    const getMaxZoom = function() {
      var width = mapcontainer.clientWidth;
      return Math.ceil(Math.LOG2E * Math.log(width / 0.02));
    };
    //初始化地图
    let myview = new View({
      // center: [11584612, 3588584],
      // zoom: 12
      // projection: "EPSG:4326",    //使用这个坐标系

      minZoom: getMinZoom(),
      maxZoom: getMaxZoom(),
      center: [mapconfig.x, mapconfig.y], //深圳
      zoom: mapconfig.zoom
    });
    this.view = myview;
    this.map = new Map({
      //拖放
      interactions: defaultInteractions().extend([dragAndDropInteraction]),
      //约束地图整数倍缩放
      //interactions: mapconfig.interactions,
      //地图控件
      controls: defaultControls().extend([
        new FullScreen({
          source: "fullscreen"
        }),
        new ScaleLine({
          source: "scaleline"
        }),
        //鼠标位置
        // new MousePosition({
        //   source: "mouseposition"
        // }),
        new MousePosition({
          coordinateFormat: createStringXY(4),
          projection: "EPSG:3857",
          // comment the following two lines to have the mouse position
          // be placed within the map.
          className: "custom-mouse-position",
          target: mapxyposition,
          undefinedHTML: "&nbsp;"
        }),
        //缩放到制定范围
        new ZoomToExtent({
          extent: [
            11584612.7791264898,
            3588584.284081122,
            11694612.9639063801,
            3698584.986909639
          ]
        })
      ]),
      target: mapcontainer,
      //地图图层
      layers: mapconfig.testmap(),
      loadTilesWhileAnimating: true,
      //地图视图
      view: myview
    });

    //监控鼠标移动事件,查询地图四个角坐标
    this.map.on("moveend", function(evt) {
      self.onMoveEnd(evt);
    });

    // console.log(this.map)
  },
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值