OpenLayers demo

本文档主要展示了如何在Vue项目中创建一个OpenLayers的演示示例,通过Vue组件化的方式集成OpenLayers库,实现地图展示和交互功能。

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

Demo – Vue

<template>
  <div>
    <div id="map" class="map" tabindex="0"></div>
    <button id="zoom-out" @click="add">Zoom out</button>
    <button id="zoom-in" @click="deleteMap">Zoom in</button>
    <button @click="biginDraw">开始绘制</button>
    <button @click="removeDraw">移除上一步</button>
    <button @click="getkey">获取坐标</button>
    <button @click="finishDraw">结束绘制</button>
    <button @click="addPolygon">添加多边形</button>
    <button @click="removeMap">移除多边形</button>
    <div id="popup" title="Welcome to OpenLayers">

    </div>
    <img id='marker' title='世界人民大和平万岁' @click="clickMark" src="https://pub-resoure.oss-cn-hangzhou.aliyuncs.com/sus-cannabis/static/big-screen/%E7%A7%8D%E5%AD%90%E4%BC%81%E4%B8%9A.png" alt="">
  </div>
</template>
<script>
import "ol/ol.css";
import Map from "ol/Map";
import View from "ol/View";
import { Circle as CircleStyle, Fill, Stroke, Style, Icon } from "ol/style";
import { Draw, Modify, Snap, Select } from "ol/interaction";
import { OSM, Vector as VectorSource } from "ol/source";
import Projection from "ol/proj/Projection";
import ImageLayer from "ol/layer/Image";
import { Tile as TileLayer, Vector as VectorLayer, Image } from "ol/layer";
import TileWMS from "ol/source/TileWMS";
import ImageWMS from "ol/source/ImageWMS";
import XYZ from "ol/source/XYZ";
import { get, getTransform, transform, fromLonLat } from "ol/proj";
import Feature from "ol/Feature";
import Polygon from "ol/geom/Polygon";
import Point from "ol/geom/Point";
import GeoJSON from "ol/format/GeoJSON";
import Overlay from "ol/Overlay";
import WMTS from "ol/source/WMTS";
import { WMTS as WMTStile } from "ol/tilegrid/WMTS";
import { getTopLeft, getWidth } from "ol/extent";
import {
  DragRotateAndZoom,
  defaults as defaultInteractions,
} from "ol/interaction";
import {
  ScaleLine,
  defaults as defaultControls,
  ZoomSlider,
  OverviewMap,
} from "ol/control";
import { getArea } from "ol/sphere";
// console.log(proj);
export default {
  data() {
    return {
      msg: "1232131",
      map: null,
      raster: null,
      source: null,
      vector: null,
      draw: null,
      projection: null,
      zoom: 0,
    };
  },
  mounted() {
    this.projection = get("EPSG:4326");
    //卫星地图
    const myImageLoader = new Image({
      source: new ImageWMS({
        
        url: "",
        params: {
          LAYERS: "",
          // LAYERS: "tiger:tiger_roads",
          VERSION: "1.1.1",
          SERVICE: "WMS",
          REQUEST: "GetMap",
          FORMAT: "image/jpeg",
          exceptions: "application/vnd.ogc.se_inimage",
        },
        serverType: "geoserver",
      }),
      extent: [
        minx,
        miny,
        max,
        maxy,
      ],
      zIndex: 3,
      title: "卫星",
    });
    //天地图影像地图
    var tian_di_tu_satellite_layer = new TileLayer({
      title: "天地图卫星影像",
      visible: true,
      source: new XYZ({
        url:
          "http://t4.tianditu.com/DataServer?T=img_w&x={x}&y={y}&l={z}&tk=key",
      }),
      zIndex: 2,
    });
    //天地图矢量标注
    var tian_di_tu_cva_ce_layer = new TileLayer({
      title: "天地图矢量标注",
      visible: true,
      source: new XYZ({
        url:
          "http://t4.tianditu.com/DataServer?T=cva_w&x={x}&y={y}&l={z}&tk=key",
      }),
      zIndex: 5,
    });
    this.map = new Map({
      controls: defaultControls().extend([
        new ScaleLine({
          units: "metric",
        }),
        new ZoomSlider(),
      ]),
      interactions: defaultInteractions().extend([new DragRotateAndZoom()]),
      target: "map",
      layers: [
        tian_di_tu_satellite_layer,
        myImageLoader,
        tian_di_tu_cva_ce_layer,
      ], //,
      // layers: [],
      view: new View({
        // center: [106.52714, 29.62487],
        projection: "EPSG:4326",
        // zoom: 12,
        center: [101.07631543310927, 22.72],
        // projection: "EPSG:4326",
        zoom: 13,
        minZoom: 1,
        maxZoom: 19,
        // center: [0, 0],
        // zoom: 2,
      }),
    });

    const arr1 = [
      [101.06728082817908, 22.720943209735943],
      [101.07436667363437, 22.722716903975638],
      [101.07238842390178, 22.716396154830054],
      [101.06611592474968, 22.71755415467352],
      [101.06728082817908, 22.720943209735943],
    ];
    var polygonFeature = new Feature(new Polygon([arr1]));

    this.source = new VectorSource({
      features: [polygonFeature],
      wrapX: false,
    });
    var vector = new VectorLayer({
      source: this.source,
      style: new Style({
        image: new Icon({
          anchor: [0.5, 46],
          anchorXUnits: "fraction",
          anchorYUnits: "pixels",
          opacity: 0.95,
          src: "data/icon.png",
        }),
        stroke: new Stroke({
          width: 3,
          color: [255, 0, 0, 1],
        }),
        fill: new Fill({
          color: [0, 0, 255, 0.6],
        }),
      }),
      zIndex: 10,
    });
    this.map.addLayer(vector);
    var marker = new Overlay({
      position: [101.06728082817908, 22.720943209735943],
      positioning: "center-center",
      element: document.getElementById("marker"),
      stopEvent: false,
    });
    this.map.addOverlay(marker);
    // this.map.on("pointermove", this.movefound);
  },
  methods: {
    removeMap() {
      this.source.clear();
    },
    movefound(evt) {
      if (evt.dragging) {
        return;
      }
      this.map.forEachLayerAtPixel(
        evt.pixel,
        function (layer, pixel) {
          console.log(pixel);
          var height =
            -10000 + (pixel[0] * 256 * 256 + pixel[1] * 256 + pixel[2]) * 0.1;
          this.innerText = height.toFixed(1);
          console.log(height);
        },
        {
          layerFilter: function (layer) {
            // return layer === disabledLayer;
          },
        }
      );
    },
    addRandomFeature() {
      var x = Math.random() * 360 - 180;
      var y = Math.random() * 180 - 90;
      var geom = new Point(fromLonLat([x, y]));
      var feature = new Feature(geom);
      this.source.addFeature(feature);
    },
    clickMark() {
      var popup = new Overlay({
        element: document.getElementById("popup"),
      });
      var element = popup.getElement();
      $(element).title = "世界人民大和平万岁";
      // var coordinate = evt.coordinate;
      // var hdms = toStringHDMS(toLonLat(coordinate));

      // $(element).popover("dispose");
      console.log($(element).popover);
      popup.setPosition([101.06728082817908, 22.720943209735943]);
      this.map.addOverlay(popup);
      $(element).popover({
        container: element,
        placement: "top",
        animation: false,
        html: true,
        content: "<p>The location you clicked was:</p><code>1232331</code>",
      });
      $(element).popover("show");
    },
    addPolygon() {
      const arr = [
        [
          [101.06728082817908, 22.720943209735943],
          [101.07436667363437, 22.722716903975638],
          [101.07238842390178, 22.716396154830054],
          [101.06611592474968, 22.71755415467352],
          [101.06728082817908, 22.720943209735943],
        ],
      ];
      const myPolygon = new Polygon(arr);
      myPolygon.applyTransform(getTransform("EPSG:4326", "EPSG:3857"));
      var feature = new Feature(myPolygon);

      // var vectorSource = new VectorSource();
      this.source.addFeature(feature);
      this.vector = new VectorLayer({
        zIndex: 999,
        source: this.source,
        style: new Style({
          fill: new Fill({
            color: "rgba(255, 255, 255, 0.2)",
          }),
          stroke: new Stroke({
            color: "#ffcc33",
            width: 2,
          }),
          image: new CircleStyle({
            radius: 7,
            fill: new Fill({
              color: "#ffcc33",
            }),
          }),
        }),
      });
      console.log(this.vector);
      this.map.addLayer(this.vector);

      // var vectorLayer = new VectorLayer({
      //   source: vectorSource,
      // });
      // this.map.addLayer(vectorLayer);
      console.log(myPolygon.getArea());
    },
    biginDraw() {
      var snap;
      this.draw = new Draw({
        source: this.source,
        type: "Polygon",
        style: new Style({
          fill: new Fill({
            color: "rgba(255, 255, 255, 0.2)",
          }),
          stroke: new Stroke({
            color: "#ffcc33",
            width: 2,
          }),
          image: new CircleStyle({
            radius: 7,
            fill: new Fill({
              color: "#ffcc33",
            }),
          }),
        }),
        zIndex: 10,
      });
      this.map.addInteraction(this.draw);
      snap = new Snap({ source: this.source });
      this.map.addInteraction(snap);
      this.draw.on("drawend", (res) => {
        console.log(res);
        console.log(res.feature.geometryChangeKey_.target.flatCoordinates);
        console.log(
          getArea(res.feature.geometryChangeKey_.target, {
            projection: this.projection,
            // radius: 6378137,
          })
        );
      });
    },
    getkey() {
      console.log(this.draw.getOverlay());
    },
    finishDraw() {
      this.draw.finishDrawing();
      this.map.removeInteraction(this.draw);
      this.map.removeInteraction(this.snap);
    },
    removeDraw() {
      this.draw.removeLastPoint();
    },
    add() {
      var view = this.map.getView();
      var zoom = view.getZoom();
      view.setZoom(zoom - 1);
    },
    deleteMap() {
      var view = this.map.getView();
      var zoom = view.getZoom();
      view.setZoom(zoom + 1);
    },
  },
};
</script>
<style lang="less">
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
}

#nav {
  padding: 30px;

  a {
    font-weight: bold;
    color: #2c3e50;

    &.router-link-exact-active {
      color: #42b983;
    }
  }
}
.map {
  width: 100%;
  height: 90vh;
}
a.skiplink {
  position: absolute;
  clip: rect(1px, 1px, 1px, 1px);
  padding: 0;
  border: 0;
  height: 1px;
  width: 1px;
  overflow: hidden;
}
a.skiplink:focus {
  clip: auto;
  height: auto;
  width: auto;
  background-color: #fff;
  padding: 0.3em;
}
#map:focus {
  outline: #4a74a8 solid 0.15em;
}
#marker {
  width: 20px;
  height: 20px;
}
.popover-content {
  min-width: 276px;
}
</style>
文件列表: OL3Demo\.DS_Store OL3Demo\css\base.css OL3Demo\css\js_demo.css OL3Demo\css\ol.css OL3Demo\demos\.DS_Store OL3Demo\demos\Controls\Animation.htm OL3Demo\demos\Controls\CanvasTiles.htm OL3Demo\demos\Controls\FullScreen.htm OL3Demo\demos\Controls\LayerControl.htm OL3Demo\demos\Controls\LayerSpy.htm OL3Demo\demos\Controls\Measure.htm OL3Demo\demos\Controls\MousePosition.htm OL3Demo\demos\Controls\Operation.htm OL3Demo\demos\Controls\OverviewMap.htm OL3Demo\demos\Controls\ScaleLine.htm OL3Demo\demos\Controls\ZoomSlider.htm OL3Demo\demos\data\geojson\countries-110m.json OL3Demo\demos\data\geojson\countries.geojson OL3Demo\demos\data\geojson\GeoJSON.json OL3Demo\demos\data\geojson\samples.json OL3Demo\demos\data\geolocation-orientation.json OL3Demo\demos\data\geolocation_marker_heading.png OL3Demo\demos\data\gml\gml.xml OL3Demo\demos\data\gml\topp-states-wfs.xml OL3Demo\demos\data\gpx\fells_loop.gpx OL3Demo\demos\data\kml\2012-02-10.kml OL3Demo\demos\data\kml\2012_Earthquakes_Mag5.kml OL3Demo\demos\data\kml\kml.xml OL3Demo\demos\DataHandler.ashx OL3Demo\demos\Drawing\DrawFeatures.htm OL3Demo\demos\Drawing\FeaturesStyle.htm OL3Demo\demos\Drawing\ModifyFeatures.htm OL3Demo\demos\Drawing\MoveFeatures.htm OL3Demo\demos\Drawing\SaveFeatures.htm OL3Demo\demos\Labels\AddClusterLabels.htm OL3Demo\demos\Labels\AddLabels.htm OL3Demo\demos\Labels\AddPopup.htm OL3Demo\demos\MultiData\LoadBasicMaps.htm OL3Demo\demos\MultiData\LoadOpenData.htm OL3Demo\demos\MultiData\LoadPublicMaps.htm OL3Demo\demos\MultiData\LoadTiandituMap.htm OL3Demo\demos\MultiData\MapExport.htm OL3Demo\demos\MultiData\OSM.htm OL3Demo\demos\MultiData\OverLayerMaps.htm OL3Demo\demos\OGC\LoadWCSMap.htm OL3Demo\demos\OGC\LoadWFSFeatrue.htm OL3Demo\demos\OGC\LoadWMSMap.htm OL3Demo\demos\OGC\LoadWMTSMap.htm OL3Demo\demos\OGC\WFS_Transaction.htm OL3Demo\demos\Others\AddPOI.htm OL3Demo\demos\Others\CreatCharts.htm OL3Demo\demos\Others\Geolocation.htm OL3Demo\demos\Others\Heatmap.htm OL3Demo\demos\Others\HotSpots.htm OL3Demo\demos\Others\LoadPublicMaps.htm OL3Demo\demos\Others\MilitaryPlotting.htm OL3Demo\demos\Others\MultiViewLinkage.htm OL3Demo\demos\Others\ProjectionTransformation.htm OL3Demo\demos\Others\SimulateGeolocation.htm OL3Demo\demos\Others\副本 LoadPublicMaps.htm OL3Demo\demos\RegDataHandler.ashx OL3Demo\demos\Web.config OL3Demo\images\ArrowIcon\arbitrary_area.png OL3Demo\images\ArrowIcon\arrow.png OL3Demo\images\ArrowIcon\arrow1.png OL3Demo\images\ArrowIcon\arrowcross.png OL3Demo\images\ArrowIcon\assembly.png OL3Demo\images\ArrowIcon\circle.png OL3Demo\images\ArrowIcon\CircleClosedangleCompass.png OL3Demo\images\ArrowIcon\closedangle.png OL3Demo\images\ArrowIcon\curve_flag.png OL3Demo\images\ArrowIcon\custom_arrow.png OL3Demo\images\ArrowIcon\custom_tail_arrow.png OL3Demo\images\ArrowIcon\custom_tail_arrow_.png OL3Demo\images\ArrowIcon\DoubleClosedangleCompass.png OL3Demo\images\ArrowIcon\double_arrow.png OL3Demo\images\ArrowIcon\fourstar.png OL3Demo\images\ArrowIcon\rect_flag.png OL3Demo\images\ArrowIcon\rhombus.png OL3Demo\images\ArrowIcon\SameDirectionClosedangleCompass.png OL3Demo\images\ArrowIcon\singleLine_arrow.png OL3Demo\images\ArrowIcon\smooth_curve.png OL3Demo\images\ArrowIcon\stright_arrow.png OL3Demo\images\ArrowIcon\tail_arrow.png OL3Demo\images\ArrowIcon\triangle.png OL3Demo\images\ArrowIcon\triangle_flag.png OL3Demo\images\ArrowIcon\VaneCompass.png OL3Demo\images\content\dotted.png OL3Demo\images\label\bj.png OL3Demo\images\label\blueIcon.png OL3Demo\images\label\icon.png OL3Demo\images\label\restaurant.png OL3Demo\images\label\国有企业.png OL3Demo\images\left\app.png OL3Demo\images\left\app_current.png OL3Demo\images\left\channel.png OL3Demo\images\left\channel_current.png OL3Demo\images\left\cloud.png OL3Demo\images\left\cloud_current.png OL3Demo\images\left\custom.png
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值