智慧农业绘制地图
guoshilong
2022-09-16 44768f17398c80d86d2aba7e3036cc6362b58ebe
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
<template>
    <div ref="imageWrapper">
        <div class="btn-grounp">
            <button v-if="addShow" class="draw" @click="draw()">开始绘制</button>
            <button v-if="!addShow&&repealShow" class="repeal" @click="repeal()">撤销</button>
            <button v-if="regionFull" class="save" @click="save()">保存</button>
        </div>
        <!-- <button class="disDraw" @click="disDraw()">关闭绘制</button> -->
        <!-- <button class="disDraw" @click="drawPolygon()">关闭绘制</button> -->
        <div id="map"></div>
    </div>
</template>
 
<script>
import wx from 'weixin-js-sdk'
import domtoimage from 'dom-to-image'
import * as esri from 'esri-leaflet'
 
export default {
    data () {
        return {
            map: "",
            polygons: [],
            lng: "",
            lat: "",
            addShow: false,
            repealShow:false,
 
            currentPolygons: [],
 
            complete: null,
 
            rectangleLayer: null,
 
            imgUrl: "",
            file: "",
            regionFull: false,
            tempBounds:""
        }
    },
    created () {
 
    },
    mounted () {
        this.addShow = true
        // this.lng = 115.89886924863
        // this.lat = 28.6780931500551
        //南城县
        this.lng = 116.56705776
        this.lat = 27.42386903
 
        this.initDate()
 
        this.map.pm.addControls({
            position: "topleft",
            drawPolygon: false, // 添加绘制多边形
            drawMarker: false, //添加按钮以绘制标记
            drawCircleMarker: false, //添加按钮以绘制圆形标记
            drawPolyline: false, //添加按钮绘制线条
            drawRectangle: false,    //添加按钮绘制矩形
            drawCircle: false, //  添加按钮绘制圆圈
            editMode: false, //  添加按钮编辑多边形
            dragMode: false, //   添加按钮拖动多边形
            cutPolygon: false, // 添加一个按钮以删除图层里面的部分内容
            removalMode: false  // 清除图层
        })
        // 设置绘制后的线条颜色等
        this.map.pm.setPathOptions({
            color: "orange",
            fillColor: "green",
            fillOpacity: 0.4
        })
        this.map.pm.setLang('zh')
    },
    methods: {
 
        drawPolygon () {
            let points = []
 
            const polygon = new this.$L.Polygon(points)
            this.map.addLayer(polygon)
 
            this.map.on('mousedown', e => {
                points.push([e.latlng.lat, e.latlng.lng])
 
                this.map.on('mousemove', event => {
                    polygon.setLatLngs([...points, [event.latlng.lat, event.latlng.lng]])
                })
            })
 
            this.map.on('dblclick', () => {
                if (points.length) {
                    this.map.off('mousemove')
                    points = []
                }
            })
        },
 
        initDate () {
            var str = window.location.search.substring(1)
            var obj = this.getUrlParams(str)
            if(obj.latitude&&obj.longitude){
                this.lat = obj.latitude
                this.lng = obj.longitude
            }
            this.map = this.$L.map("map", {
                center: [this.lat, this.lng], // 地图中心
                zoom: 14, //缩放比列
                zoomControl: false, //禁用 + - 按钮
                doubleClickZoom: false, // 禁用双击放大
                attributionControl: false, // 移除右下角leaflet标识
            })
            this.$L.tileLayer('https://t{s}.tianditu.gov.cn/DataServer?T=img_w&x={x}&y={y}&l={z}&tk=e9533f5acb2ac470b07f406a4d24b4f0', {
                subdomains: [0, 1, 2, 3, 4, 5, 6, 7],
            }).addTo(this.map)
 
            this.$L.tileLayer('https://t{s}.tianditu.gov.cn/DataServer?T=cva_w&x={x}&y={y}&l={z}&tk=e9533f5acb2ac470b07f406a4d24b4f0', {
                subdomains: [0, 1, 2, 3, 4, 5, 6, 7],
            }).addTo(this.map)
 
            // , this.$L.esri.dynamicMapLayer
 
            // this.$L.tileLayer.WMTS("http://arcgis.jxpskj.com:6080/arcgis/rest/services/nanchengdom/MapServer/WMTS", {
            //     format: 'image/png',
            //     layer: 'nanchengdom',
            //     style: 'default'
            // }).addTo(this.map)
            //   this.map.removeLayer(name)  // 移除图层
        },
 
        draw () {
 
            this.getlatLngs()
 
            this.map.pm.enableDraw("Polygon", {
                snappable: true,
                snapDistance: 10,
            })
 
            //   this.map.pm.enableDraw("Marker", { snappable: false });
            //   this.map.pm.enableDraw("CircleMarker", { snappable: false });
        },
 
        repeal () {
            this.map.pm.disableDraw('Polygon')
 
            this.complete.remove()
 
            this.addShow = true
            this.repealShow = false
            this.regionFull = false
 
            // Object.values(this.map._layers).forEach(item => {
            //     if (item._leaflet_id == this.rectangleLayer._leaflet_id) {
            //         this.map.removeLayer(item)
            //     }
            // })
 
            // this.currentPolygons.forEach(item => {
            //     this.map.removeLayer(item.marker)
            // })
 
            // this.currentPolygons = []
        },
 
        base64ImgtoFile (dataurl, filename = 'file') {
            let arr = dataurl.split(',')
            let mime = arr[0].match(/:(.*?);/)[1]
            let suffix = mime.split('/')[1]
            let bstr = atob(arr[1])
            let n = bstr.length
            let u8arr = new Uint8Array(n)
            while (n--) {
                u8arr[n] = bstr.charCodeAt(n)
            }
            return new File([u8arr], `${filename}.${suffix}`, {
                type: mime
            })
        },
 
        save () {
 
            const that = this
 
            this.map.pm.disableGlobalEditMode()
 
            var arr = []
 
            this.polygons.forEach(item => {
                arr.push([item.lng, item.lat])
            })
 
            arr.push([this.polygons[0].lng, this.polygons[0].lat])
 
            let area = this.$turf.area(this.$turf.polygon([arr]))
 
            var str = window.location.search.substring(1)
            var parmasObj = this.getUrlParams(str)
 
            if(parmasObj.status){//后台镜头移动
                this.repealShow = false
                this.regionFull = false
                if(this.rectangleLayer.getBounds() != this.tempBounds){
                    if(this.map.getZoom()>16){
                        this.rectangleLayer.getBounds()._northEast.lng = this.rectangleLayer.getBounds()._northEast.lng+0.007
                        this.tempBounds = this.rectangleLayer.getBounds()
                        this.map.flyToBounds(this.rectangleLayer.getBounds(),{maxZoom:18}); 
                    }else{
                        this.rectangleLayer.getBounds()._northEast.lng = this.rectangleLayer.getBounds()._northEast.lng+0.06
                        this.tempBounds = this.rectangleLayer.getBounds()
                        this.map.flyToBounds(this.rectangleLayer.getBounds(),{maxZoom:18}); 
                    }
                }
            }else{//小程序镜头移动
                this.map.flyToBounds(this.rectangleLayer.getBounds(),{maxZoom:18}); 
            }
 
            setTimeout(() => {
                if(parmasObj.status){//后台截图
                    domtoimage.toPng(document.getElementById('map'), { width: 450, height: 450 })
                    .then( (dataUrl) => {
 
                        var base64Image = dataUrl // 后台返回的base64数据
                        var imgData = base64Image.replace(/[\r\n]/g, '') // 将回车换行换为空字符''
 
                        var obj = {
                            url:imgData,
                            polygons:arr,
                            area:area
                        }
                        window.parent.postMessage(obj,"*")
                    })
                    .catch(function (error) {
                        console.error('oops, something went wrong!', error)
                    }) 
                    
                    setTimeout(() => {
                        this.repealShow = true
                        this.regionFull = true
                    }, 1000);
 
                }else{//小程序截图
                    domtoimage.toPng(document.getElementById('map'), { width: 375, height: 600 })
                    .then( (dataUrl) => {
                        var base64Image = dataUrl // 后台返回的base64数据
                        var imgData = base64Image.replace(/[\r\n]/g, '') // 将回车换行换为空字符''
                        wx.miniProgram.postMessage({
                            data: { polygons: arr, area, bgUrl: imgData },
                        })
                        wx.miniProgram.navigateBack()
                    })
                    .catch(function (error) {
                        console.error('oops, something went wrong!', error)
                    }) 
                }   
            }, 1000);
        },
 
        getUrlParams(urlParams) {
            var obj = {}
            var arrList = urlParams.split('&')
            arrList.forEach(function (item) {
                var arr = item.split('=') //["name", "%E5%BC%A0%E4%B8%89"]
                obj[arr[0]] = window.decodeURIComponent(arr[1]) //{name: "张三", age: "18"}
            })
            return obj
        },
 
        disDraw () {
            this.map.pm.disableDraw("Polygon")
            //    this.map.pm.disableDraw('Marker');
            //    this.map.pm.disableDraw('CircleMarker');
        },
 
        // 获取绘制的坐标
        getlatLngs () {
            const that = this
            //pm:drawstart 开始第一个点的时候调用
            //pm:drawend  禁止绘制时调用
            //pm:create  创建完成时调用
            this.map.on('pm:drawstart', ({ workingLayer }) => {
 
                this.addShow = false
                this.repealShow = false
                that.rectangleLayer = workingLayer
 
                console.log(workingLayer, 5465456)
 
                workingLayer.on('pm:vertexadded', e => {
                    that.currentPolygons.push(e)
 
                    console.log(that.currentPolygons)
                })
            })
 
            this.map.on("pm:drawend", e => {
                console.log(e, "禁止绘制")
            })
 
            this.map.on("pm:create", e => {
                that.repealShow = true
                that.regionFull = true
 
                // 绘制坐标
                that.polygons = e.layer._latlngs[0]
 
                that.complete = e.layer
 
                // 开启编辑
                e.layer.pm.enable({
                    allowSelfIntersection: false,
                    preventMarkerRemoval: false,  // 禁止右键删除点
                    snapDistance: 0
                })
 
 
                e.layer.on('pm:edit', e => {
 
                    console.log(e)
                    // 拖动后的坐标
                    that.polygons = e.target._latlngs[0]
                })
 
                e.layer.on('pm:vertexadded', e => {
                    console.log(e, "添加顶点")
                })
 
                var arr = []
 
                this.polygons.forEach(item => {
                    arr.push([item.lng, item.lat])
                })
 
                arr.push([this.polygons[0].lng, this.polygons[0].lat])
 
                let area = this.$turf.area(this.$turf.polygon([arr]))
 
                window.parent.postMessage(area,"*")
 
            })
        },
 
        // 获取url信息
        getQueryString (name) {
            var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i")
            var r = window.location.search.substr(1).match(reg)
            if (r != null) {
                return unescape(r[2])
            }
            return null
        },
 
        // 开启编辑按钮
        allEdit () {
            this.map.pm.toggleGlobalEditMode()
        },
    }
};
</script>
 
<style lang="scss" scoped>
#map {
    position: relative;
    width: 100vw;
    height: 100vh;
    z-index: 1;
}
 
.btn-grounp {
    position: fixed;
    bottom: 34px;
    top: auto;
    left: 0;
    right: 0;
    margin: auto;
    width: 100%;
    height: 44px;
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 10;
    font-size: 16px;
 
    .draw {
        // width: 144px;
        // height: 44px;
        line-height: 44px;
        background: #5abf78;
        color: #fff;
        border: none;
        border-radius: 22px;
 
        width: 216px;
        height: 66px;
        font-size: 30px;
    }
 
    .repeal {
        // width: 100px;
        // height: 44px;
 
        border-radius: 22px;
        border: none;
        color: #000;
        background: #fff;
        width: 150px;
        height: 66px;
        font-size: 30px;
    }
 
    .save {
        margin-left: 10px;
        // width: 100px;
        // height: 44px;
        border-radius: 22px;
        border: none;
        color: #000;
        background: #fff;
        width: 150px;
        height: 66px;
        font-size: 30px;
    }
}
 
.disDraw {
    display: flex;
    z-index: 2;
    width: 100px;
    height: 50px;
    position: absolute;
    left: 200px;
    justify-content: center;
    align-items: center;
}
</style>