web前端

openlayer画图:折线、圆、矩形和多边形

2020-11-27  本文已影响0人  姜治宇
import { Component, OnInit } from '@angular/core';
declare var ol:any; // 声明全局变量
@Component({
  selector: 'app-example',
  templateUrl: './example.component.html',
  styleUrls: ['./example.component.scss']
})
export class ExampleComponent implements OnInit {
  
  constructor() { }
  ngOnInit(): void {
    
  }
  map:any;
  ngAfterContentInit(): void {
    //Called after ngOnInit when the component's or directive's content has been initialized.
    //Add 'implements AfterContentInit' to the class.
    let source = new ol.source.OSM();
    this.map = new ol.Map({
      target: 'map',
      view:new ol.View({
          center:[123,46],
          zoom:4
      }),
      layers: [
        new ol.layer.Tile({
          source: source
      })
      ]
    });
    var drawLayer = new ol.layer.Vector({
      //layer所对应的source
      source: new ol.source.Vector(),

  })
  //把layer加入到地图中
    this.map.addLayer(drawLayer);

    this.drawLine(drawLayer);




  }
  //折线
  drawLine(drawLayer){
    let draw = new ol.interaction.Draw({
      source: drawLayer.getSource(),//一定要共享source
      type:'LineString'
    })
    draw.on('drawend',(e)=>{
      console.log('draw line over');
      
      //this.map.removeInteraction(draw);
    });
    this.map.on('contextmenu',e=>{
      e.preventDefault();
      this.map.getInteractions().clear();//清除所有交互
    })

    this.map.addInteraction(draw);//添加矢量图
  }


  //画圆
  drawCircle(drawLayer){
    let draw = new ol.interaction.Draw({
      source: drawLayer.getSource(),//一定要共享source
      type:'Circle'
    })
    draw.on('drawend',(e)=>{
      console.log('draw circle over');
      
      //this.map.removeInteraction(draw);
    });
    this.map.on('contextmenu',e=>{
      e.preventDefault();
      this.map.getInteractions().clear();//清除所有交互
    })

    this.map.addInteraction(draw);//添加矢量图

  }


  //画矩形
  drawRectangle(drawLayer){
    let draw = new ol.interaction.Draw({
      source: drawLayer.getSource(),//一定要共享source
      type:'Circle',
      geometryFunction:ol.interaction.Draw.createBox()
      
    })
    draw.on('drawend',(e)=>{
      console.log('draw rectangle over');
      
      //this.map.removeInteraction(draw);
    });
    this.map.on('contextmenu',e=>{
      e.preventDefault();
      this.map.getInteractions().clear();//清除所有交互
    })

    this.map.addInteraction(draw);//添加矢量图

  }
  //多边形
  drawPolygon(drawLayer){
    let draw = new ol.interaction.Draw({
      source: drawLayer.getSource(),//一定要共享source
      type:'Polygon'
    })
    draw.on('drawend',(e)=>{
      console.log('draw Polygon over');
      
      //this.map.removeInteraction(draw);
    });
    this.map.on('contextmenu',e=>{
      e.preventDefault();
      this.map.getInteractions().clear();//清除所有交互
    })

    this.map.addInteraction(draw);//添加矢量图

  }

}

上一篇 下一篇

猜你喜欢

热点阅读