leaflet操作地图(矩形框、定位、测距、截图、圆)

地图(vue+leaflet+element)

一、地图拉矩形框

  1. web端代码
     // 添加区域          
      addRectArea(){
          var that = this;
          var map = that.$store.state.map; //获取已保存的地图
          if(that.stopRectArea != null){  //stopRectArea在data中定义,清除重复的拉框操作
              map.off('mousedown', that.stopRectArea.mousedown);
          }
          var rectangleMeasure = {
              startPoint: null,
              endPoint: null,
              rectangle:null,
              layer: L.layerGroup(),
              color: "red",
              addRectangle:function(){
                  rectangleMeasure.destory();
                  var bounds = [];
                  bounds.push(rectangleMeasure.startPoint);
                  bounds.push(rectangleMeasure.endPoint);
                  rectangleMeasure.rectangle = L.rectangle(bounds, {color: rectangleMeasure.color, weight: 1});
                  rectangleMeasure.rectangle.addTo(rectangleMeasure.layer);        
      
                  var northWestPoint = rectangleMeasure.rectangle.getBounds().getNorthWest(),
                      northEastPoint = rectangleMeasure.rectangle.getBounds().getNorthEast(),
                      southEastPoint = rectangleMeasure.rectangle.getBounds().getSouthEast();
                  var width = northWestPoint.distanceTo(northEastPoint)/1000,
                      height = northEastPoint.distanceTo(southEastPoint)/1000;
                  var area = Number(width) * Number(height);
                  rectangleMeasure.layer.addTo(map);
              },
              mousedown: function(e){
                  rectangleMeasure.rectangle = null;
                  map.dragging.disable();
                  rectangleMeasure.startPoint = e.latlng;
                  map.on('mousemove',rectangleMeasure.mousemove)
              },
              mousemove:function(e){
                  rectangleMeasure.endPoint = e.latlng;
                  rectangleMeasure.addRectangle();
                  map.off('mousedown ', rectangleMeasure.mousedown).on('mouseup', rectangleMeasure.mouseup);
              },
              mouseup: function(e){        
                  map.dragging.enable();
                  map.off('mousemove',rectangleMeasure.mousemove).off('mouseup', rectangleMeasure.mouseup);
                  that.locations = {}; //locations在data中定义
                  that.locations['leftX'] = rectangleMeasure.startPoint.lat;
                  that.locations['leftY'] = rectangleMeasure.startPoint.lng;
                  that.locations['rightX'] = rectangleMeasure.endPoint.lat;
                  that.locations['rightY'] = rectangleMeasure.endPoint.lng;
                  that.locations['layer_id'] = rectangleMeasure.layer._leaflet_id;
                  that.locations['layer'] = rectangleMeasure.layer;
                  that.locations['rectangle'] = rectangleMeasure.rectangle;
                  //在此处对数据进行处理(1)...
              },
              destory:function(){
                  if(rectangleMeasure.rectangle)
                      rectangleMeasure.layer.removeLayer(rectangleMeasure.rectangle);
              }
          };
          that.stopRectArea = rectangleMeasure; //记录已点击拉框按钮,未在地图上拉框
          map.on('mousedown', rectangleMeasure.mousedown); //在地图上拉框
      },
      //清除框选
      clearFrame(){
          var that = this;
          if(that.stopRectArea != null){
              var map = that.$store.state.map;
              map.off('mousedown', that.stopRectArea.mousedown);
          }
          //清除选框
          for(var i in that.allLocations){ //将(1)处保存框选图层数据,在此处删除图层
              that.allLocations[i].layer.removeLayer(that.allLocations[i].rectangle);
          }
      }, 
    
  2. 移动端代码
        //添加区域
        chooseRect(){
            var that = this;
            var map = that.$store.state.map;  //获取已保存的地图
        
            var rectangleMeasure = {
                startPoint: null,
                endPoint: null,
                rectangle:null,
                layer: L.layerGroup(),
                color: "red",
                addRectangle:function(){
                    rectangleMeasure.destory();
                    var bounds = [];
                    bounds.push(rectangleMeasure.startPoint);
                    bounds.push(rectangleMeasure.endPoint);
                    rectangleMeasure.rectangle = L.rectangle(bounds, {color: rectangleMeasure.color, weight: 1});
                    rectangleMeasure.rectangle.addTo(rectangleMeasure.layer);        
        
                    var northWestPoint = rectangleMeasure.rectangle.getBounds().getNorthWest(),
                        northEastPoint = rectangleMeasure.rectangle.getBounds().getNorthEast(),
                        southEastPoint = rectangleMeasure.rectangle.getBounds().getSouthEast();
                    var width = northWestPoint.distanceTo(northEastPoint)/1000,
                        height = northEastPoint.distanceTo(southEastPoint)/1000;
                    var area = Number(width) * Number(height);
                    rectangleMeasure.layer.addTo(map);
                },
                touchstart: function(e){
                    rectangleMeasure.rectangle = null;
                    map.dragging.disable();
                    var touch_1 = e.touches[0];
                    var latlng_1 = map.containerPointToLatLng(new L.Point(touch_1.pageX,touch_1.pageY));
                    rectangleMeasure.startPoint = latlng_1;
                    L.DomEvent.on(map._container, 'touchmove',rectangleMeasure.touchmove,that);
                },
                touchmove:function(e){
                    var touch_2 = e.touches[0];
                    var latlng_2 = map.containerPointToLatLng(new L.Point(touch_2.pageX,touch_2.pageY));
                    rectangleMeasure.endPoint = latlng_2;
                    rectangleMeasure.addRectangle();
                    L.DomEvent.on(map._container, 'touchend',rectangleMeasure.touchend,that);
                },
                touchend: function(e){     
                    L.DomEvent.off(map._container, 'touchstart',rectangleMeasure.touchstart,that);
                    L.DomEvent.off(map._container, 'touchmove',rectangleMeasure.touchmove,that);
                    L.DomEvent.off(map._container, 'touchend',rectangleMeasure.touchend,that);
                    map.dragging.enable();
        
                    that.locations = {};  //locations在data中定义
                    that.locations['leftX'] = rectangleMeasure.startPoint.lat;
                    that.locations['leftY'] = rectangleMeasure.startPoint.lng;
                    that.locations['rightX'] = rectangleMeasure.endPoint.lat;
                    that.locations['rightY'] = rectangleMeasure.endPoint.lng;
                    that.locations['layer_id'] = rectangleMeasure.layer._leaflet_id;
                    that.locations['layer'] = rectangleMeasure.layer;
                    that.locations['rectangle'] = rectangleMeasure.rectangle;
                    //在此处对数据进行处理(1)...
                },
                destory:function(){
                    if(rectangleMeasure.rectangle)
                        rectangleMeasure.layer.removeLayer(rectangleMeasure.rectangle);
                }
            };
            that.stopRectArea = rectangleMeasure;//记录已点击拉框按钮,未在地图上拉框
            L.DomEvent.on(map._container, 'touchstart',rectangleMeasure.touchstart,that);//在地图上拉框
        },
        //清除框选
        clearFrame(){
            var that = this;
            //清除选框
            for(var i in that.allLocations){//将(1)处保存框选图层数据,在此处删除图层
                that.allLocations[i].layer.removeLayer(that.allLocations[i].rectangle);
            }
        }, 
        //取消拉框操作
        closeRectChoose(){                
            var map = this.$store.state.map;
            if(this.stopRectArea != null){
                L.DomEvent.off(map._container, 'touchstart',this.stopRectArea.touchstart,this);
            }
        },
    

二、地理定位

  1. 用户地理位置的查询显示
       getLocation(){ 
           var that = this;
           var m = that.$store.state.map;
           that.clearUser();
       
           // Geolocation
           m.locate({
               setView: true,
               maxZoom: 16
           });
       
           m.once('locationfound', function(e) {
               var radius = e.accuracy / 2;
               that.userLocation = L.marker(e.latlng).addTo(m).bindPopup("你就在这个圈内");//data中定义
               that.userBounds = L.circle(e.latlng, radius).addTo(m);//data中定义
           });
       
           m.once('locationerror', function(e) {
               console.log('定位出错=====>', e);
           });
       },
       clearUser(){
           var that = this;
           that.map = that.$store.state.map;//data中定义
       
           if(that.userLocation != null){
               that.map.removeLayer(that.userLocation);
               that.userLocation = null;
               that.map.removeLayer(that.userBounds);
               that.userBounds = null;
           }
       }
    

三、地图测距

  1. 方法一
     var mile = L.latLng([lat,lng]).distanceTo([lat,lng]);  //单位(米),其中lat-纬度,lng-经度
  1. 方法二
     function GetDistance( lat1,  lng1,  lat2,  lng2){
         var radLat1 = lat1*Math.PI / 180.0;
         var radLat2 = lat2*Math.PI / 180.0;
         var a = radLat1 - radLat2;
         var  b = lng1*Math.PI / 180.0 - lng2*Math.PI / 180.0;
         var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a/2),2) +
         Math.cos(radLat1)*Math.cos(radLat2)*Math.pow(Math.sin(b/2),2)));
         s = s *6378.137 ;// EARTH_RADIUS;
         s = Math.round(s * 10000) / 10000;
         return s;
     }
     var l = GetDistance(32.06681,118.81162,32.0465,118.78238)*1000;

四、地图截图

  1. 对地图div区域截图
     //1、引入html2canvas.min.js文件,jquery这里用了2.2.4版本
     <script src="https://cdn.bootcss.com/html2canvas/0.5.0-beta4/html2canvas.min.js"></script> 
     //2、地图配置加上:preferCanvas: true
     var map = L.map('mainPage',{
         center:[32.041975, 118.788561],
         crs:L.CRS.EPSG4326,
         zoom: 12,
         maxZoom: 19,
         zoomControl: true,
         attributionControl:false,
         layers:[wmts],
         preferCanvas: true //***轨迹***
     });
     //3、html
     <div id="qqq">
         <div id="mainPage" style="width:100%;height:100%"></div>
      <el-button type="text" @click="testCanvas" icon="el-icon-picture-outline">抓取</el-button>
     </div>
     //4、javascript
     testCanvas(){
         var that = this;
         console.log(1);
     
         html2canvas(that.jQuery("#qqq"),{ // $("#qqq")是你要复制生成canvas的区域,可以自己选
             useCORS:true, 
             logging:true,
             onrendered:function(canvas){
                 // dataURL =canvas.toDataURL("image/png");
                 console.log(2);
                 that.jQuery("body").append(canvas);
                 console.log(canvas);
     
                 //下载图片
                 // that.jQuery('#down_button').attr( 'href' ,  dataURL ) ;
                 // that.jQuery('#down_button').attr( 'download' , 'myjobdeer.png' ) ;
             },
             width:1000,
             height:570
         })
     }

五、地图leaflet画圆

  1、0.7.7版本:L.circle([32.100276,118.911946], 500).addTo(map); 

  2、1.3.4版本:L.circle([50.5, 30.5], {radius: 500}).addTo(map); 
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 211,042评论 6 490
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 89,996评论 2 384
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 156,674评论 0 345
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 56,340评论 1 283
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 65,404评论 5 384
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,749评论 1 289
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,902评论 3 405
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,662评论 0 266
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,110评论 1 303
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,451评论 2 325
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,577评论 1 340
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,258评论 4 328
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,848评论 3 312
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,726评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,952评论 1 264
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,271评论 2 360
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,452评论 2 348