百度地图api使用-区域网格管理

说明及效果图

在地图上高亮显示成都市的行政区域
效果图
切换高亮显示行政区域
效果图
在行政区域添加自定义的中心点以及网格范围
效果图
效果图

使用技术

laytpl, jquery, es6

interesting point

  1. 判断一个点是否在一个不规则多边形内,使用射线法
  2. basic js is very useful! 给对象绑定属性和方法如下:
    1
    2
    3
    4
    BMap.Polygon.prototype.datas = {};
    BMap.Polygon.prototype.setDatas = function(datas) {
    this.datas = datas;
    };
  3. 面向对象开发,能有效使你脑壳不晕。

代码

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
<div class="wrapper-content">
<div class="row">
<div class="col-sm-12">
<div class="bdmap-area">
<div class="zoom-operation">
<div class="left-opers">
<a class="fa fa-list toggle-region-grid-list">&nbsp;网格区域列表</a>
<div class="fold-grid-region-list hide" id="grid-region-distribute-view"></div>
</div>
<div class="rgt-opers">
<button class="btn btn-primary add-marker">添加网格区域</button>
<button class="btn btn-primary save-region-grid hide">保存</button>
</div>
</div>
<div id="container"></div>
</div>
</div>
</div>
</div>
<div class="wrapper-content hide" id="grid-region-form">
<div class="row">
<div class="col-sm-12">
<form method="get" class="form-horizontal">
<input type="hidden" name="id">
<input type="hidden" name="regionId">
<div class="form-group">
<label class="col-sm-3 control-label">网格区域名称</label>
<div class="col-sm-9">
<input class="form-control" placeholder="输入网格区域名称" type="text" name="name" value="">
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">负责人</label>
<div class="col-sm-9">
<input class="form-control" placeholder="请选择一个负责人" type="text" name="chargePerson" value="">
</div>
</div>
<div class="form-group">
<div class="col-sm-4 col-sm-offset-3">
<button class="btn btn-primary" type="submit">去地图上选点</button>
</div>
</div>
</form>
</div>
</div>
</div>
<script>
$('#container').css('height', ($(window).height() - 140) + 'px');
GridRegionUtil.init({
containerId: 'container',
gridRegions: JSON.parse('[{"region":{"id":5,"name":"青羊区"},"relates":[{"id":1,"name":"文家路社区","chargePerson":"李丹","point":{"lng":103.954011,"lat":30.685222},"gridPoints":[{"lng":103.95601099999999,"lat":30.687222},{"lng":103.952011,"lat":30.687222},{"lng":103.952011,"lat":30.683222},{"lng":103.95601099999999,"lat":30.683222},{"lng":103.961988,"lat":30.685067},{"lng":103.95601099999999,"lat":30.687222}]}]},{"region":{"id":1,"name":"金牛区"},"relates":[{"id":2,"name":"呵呵哒社区","chargePerson":"李丹","point":{"lng":104.023396,"lat":30.721085},"gridPoints":[{"lng":104.025396,"lat":30.723084999999998},{"lng":104.023468,"lat":30.727263},{"lng":104.02139600000001,"lat":30.723084999999998},{"lng":104.010999,"lat":30.720992},{"lng":104.02139600000001,"lat":30.719085},{"lng":104.024079,"lat":30.710498},{"lng":104.025396,"lat":30.719085},{"lng":104.035074,"lat":30.720713},{"lng":104.025396,"lat":30.723084999999998}]}]},{"region":{"id":3,"name":"锦江区"},"relates":[{"id":3,"name":"天啦噜社区","chargePerson":"李丹","point":{"lng":104.093697,"lat":30.65301},"gridPoints":[{"lng":104.092278,"lat":30.662221},{"lng":104.079944,"lat":30.658716},{"lng":104.080402,"lat":30.652233},{"lng":104.084912,"lat":30.650974},{"lng":104.09429,"lat":30.646252},{"lng":104.097434,"lat":30.640768},{"lng":104.1078,"lat":30.653709},{"lng":104.09508,"lat":30.658928},{"lng":104.092278,"lat":30.662221}]}]}]')
})
</script>

js

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
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
let GridRegionUtil = (function() {
let mp = null,
opers = null,
geoLocation = new BMap.Geolocation(),
geoc = new BMap.Geocoder(),
centerPoint = null,
bdary = new BMap.Boundary(),
i = 0,
j = 0,
city = '',
regions = [],
colors = [],
isMarker = false,
latestMarkerInfo = null,
latestMarkerPoint = null,
latestPolygon = null,
gridRegions = [],
tpl = null,
view = null,
loadType = 1,
scrollFunc = function(e) {
e=e || window.event;
if (parseInt(mp.getZoom()) >= 15) {
$('.add-marker').removeClass('hide');
$('.save-region-grid').addClass('hide');
if (loadType == 1) {
loadGridRegions();
loadType = 2;
}
} else {
$('.add-marker').addClass('hide');
$('.save-region-grid').addClass('hide');
isMarker = false;
if (loadType == 2) {
loadGridRegions();
loadType = 1;
}
}
},
setBasicDatas = function() {
city = '成都市';
regions.push({
id: 1,
name: '金牛区'
});
regions.push({
id: 2,
name: '武侯区'
});
regions.push({
id: 3,
name: '锦江区'
});
regions.push({
id: 4,
name: '成华区'
});
regions.push({
id: 5,
name: '青羊区'
});
regions.push({
id: 6,
name: '龙泉驿区'
});
regions.push({
id: 7,
name: '青白江区'
});
regions.push({
id: 8,
name: '新都区'
});
regions.push({
id: 9,
name: '温江区'
});
regions.push({
id: 10,
name: '金堂县'
});
regions.push({
id: 11,
name: '郫都区'
});
regions.push({
id: 12,
name: '双流区'
});
regions.push({
id: 13,
name: '浦江县'
});
regions.push({
id: 14,
name: '大邑县'
});
regions.push({
id: 15,
name: '新津县'
});
regions.push({
id: 16,
name: '崇州市'
});
regions.push({
id: 17,
name: '都江堰市'
});
regions.push({
id: 18,
name: '彭州市'
});
regions.push({
id: 19,
name: '邛崃市'
});
colors = new Array(
"rgb(0, 85, 194)",
"rgb(5, 129, 163)",
"rgb(16, 150, 154)",
"rgb(7, 188, 153)",
"rgb(195, 21, 15)",
"rgb(222, 170, 1)",
"rgb(221, 88, 5)",
"rgb(177, 191, 55)",
"rgb(49, 175, 80)",
"rgb(190, 157, 2)",
"rgb(14, 207, 173)",
"rgb(56, 225, 81)",
"rgb(43, 110, 163)",
"rgb(0, 132, 160)",
"rgb(169, 222, 12)",
"rgb(51, 171, 177)",
"rgb(5, 135, 217)",
"rgb(218, 14, 7)",
"rgb(174, 154, 2)",
"rgb(9, 182, 153)"
)
},
setBoundaries = function(region, color) {
var pointCount = 0,
polygon = null;
bdary.get(region == '郫都区' ? '郫县' : region, function(rs){ //获取行政区域
pointCount = rs.boundaries.length; //行政区域的点有多少个
for (i = 0; i < pointCount; i++) {
polygon = new BMap.Polygon(rs.boundaries[i], {
strokeWeight: 1,
strokeColor: "#fff",
fillOpacity:0.2,
fillColor:'#2480cc'
}); //建立多边形覆盖物
mp.addOverlay(polygon); //添加覆盖物
polygon.setDatas({
type: 'region',
detail: {
name: region
}
});
}
});
},
addMarker = function() {
$('#grid-region-form').removeClass('hide');
// 使用layer弹窗打开模板
layer.open({
type: 1,
title: '添加网格',
skin: 'layui-layer-demo', //样式类名
closeBtn: 0, //不显示关闭按钮
anim: 2,
shadeClose: true, //开启遮罩关闭
area : [ '784px', '240px' ], //宽高
content: $('#grid-region-form')
});
$("#grid-region-form form").validate({
rules: {
},
messages: {
},
submitHandler:function(form){
latestMarkerInfo = $("#grid-region-form form").serializeObject();
isMarker = true;
layer.closeAll();
}
});
},
inGridPoint = null,
markerPoint = function(point) {
if (latestMarkerPoint) {
mp.removeOverlay(latestMarkerPoint);
}
latestMarkerPoint = point;
// 创建点坐标
mp.addOverlay(latestMarkerPoint);
latestMarkerPoint.enableDragging();
if (point.datas && point.datas.detail && point.datas.detail.name) {
latestMarkerPoint.setLabel(getMarkerLabel(point.datas.detail.name));
}
inGridPoint = point;
},
addPolygon = function() {
if (!latestMarkerPoint) {
console.log('请先添加应急中心!');
return false;
}
if (latestPolygon) {
return false;
}
var centerPoint = latestMarkerPoint.point;
latestPolygon = new BMap.Polygon([
new BMap.Point(centerPoint.lng + 0.002, centerPoint.lat + 0.002),
new BMap.Point(centerPoint.lng - 0.002, centerPoint.lat + 0.002),
new BMap.Point(centerPoint.lng - 0.002, centerPoint.lat - 0.002),
new BMap.Point(centerPoint.lng + 0.002, centerPoint.lat - 0.002)
], {strokeColor:"red", strokeWeight:2, strokeOpacity:0.2,
fillColor:'#fff'}); //创建多边形
mp.addOverlay(latestPolygon); //增加多边形
latestPolygon.enableEditing();
latestPolygon.setDatas({
type: 'polygon',
detail: latestMarkerInfo
});
},
contextMenu = null,
dragMarker = function(e, ee, m){
latestPolygon = filterOverLays(ol => ol.datas && ol.datas.type == 'polygon' && ol.datas.detail.id == m.datas.detail.id);
latestPolygon.enableEditing();
loadType = 3;
m.enableDragging();
latestMarkerPoint = m;
inGridPoint = m;
latestMarkerPoint.addEventListener("dragend", function(e) {
var result = BMapLib.GeoUtils.isPointInPolygon(e.point, latestPolygon);
if (!result) {
alert('应急点必须在应急区域内!');
markerPoint(inGridPoint);
} else {
inGridPoint = new BMap.Marker(e.point);
inGridPoint.setDatas(latestMarkerPoint.datas);
}
});
latestMarkerInfo = m.datas.detail;
$('.save-region-grid').removeClass('hide');
},
filterOverLays = function(fn) {
let overLays = mp.getOverlays(),
filtered = [];
for (i = 0; i < overLays.length; i++) {
if (fn(overLays[i], i) === true) {
filtered.push(overLays[i]);
}
}
return filtered.length == 1 ? filtered[0] : filtered;
},
saveMarker = function(e, ee, m) {
},
editPolygon = function(e, ee, p) {
p.enableEditing();
},
savePolygon = function(e, ee, p) {
},
saveRegionGrid = function() {
// 判断中心点是否在区域范围内
var result = BMapLib.GeoUtils.isPointInPolygon(latestMarkerPoint.point, latestPolygon);
if (!result) {
alert('应急中心点不能在区域范围之外');
return false;
} else {
geoc.getLocation(latestMarkerPoint.point, function(rs){
let regionName = rs.addressComponents.district,
region = null,
regionIndex = -1,
relateIndex = -1;
for (i = 0; i < regions.length; i++) {
if (regions[i].name == regionName) {
region = regions[i];
}
}
for (i = 0; i < gridRegions.length; i++) {
if (gridRegions[i].region.name == regionName) {
regionIndex = i;
}
}
if (regionIndex < 0) {
gridRegions.push({
region: region,
relates: []
});
regionIndex = gridRegions.length - 1;
}
latestMarkerInfo.point = latestMarkerPoint.point;
latestMarkerInfo.gridPoints = latestPolygon.ia;
for (i = 0; i < gridRegions[regionIndex].relates.length; i++) {
if (gridRegions[regionIndex].relates[i].id == latestMarkerInfo.id) {
relateIndex = i;
}
}
if (relateIndex >= 0) {
gridRegions[regionIndex].relates[relateIndex] = latestMarkerInfo;
} else {
gridRegions[regionIndex].relates.push(latestMarkerInfo);
}
$('.save-region-grid').addClass('hide');
loadGridRegions();
});
}
},
loadGridRegions = function() {
filterOverLays(ol => ol.datas && (ol.datas.type == 'marker' || ol.datas.type == 'polygon')).map(f => mp.removeOverlay(f));
loadType = 1;
if (latestMarkerPoint) {
latestMarkerPoint.disableDragging();
latestMarkerPoint = null;
}
if (latestPolygon) {
latestPolygon.disableEditing();
latestPolygon = null;
}
isMarker = false;
if (gridRegions.length > 0 ) {
for (i = 0; i < gridRegions.length; i++) {
for (j = 0; j < gridRegions[i].relates.length; j++) {
var relate = gridRegions[i].relates[j],
point = relate.point,
gridPoints = relate.gridPoints,
marker = new BMap.Marker(new BMap.Point(point.lng, point.lat)),
polygon = new BMap.Polygon(gridPoints.map(gp => new BMap.Point(gp.lng, gp.lat)), {strokeColor:"red", strokeWeight:1, strokeOpacity:0.3, fillColor:'rgb(253, 80, 0)'});
mp.addOverlay(marker);
mp.addOverlay(polygon);
if (mp.getZoom() >= 15) {
marker.setLabel(getMarkerLabel(relate.name));
}
marker.setDatas({
type: 'marker',
detail: relate
});
polygon.setDatas({
type: 'polygon',
detail: relate
});
contextMenu = new BMap.ContextMenu();
contextMenu.addItem(new BMap.MenuItem('重新定点', dragMarker.bind(marker)));
marker.addContextMenu(contextMenu);
contextMenu = new BMap.ContextMenu();
contextMenu.addItem(new BMap.MenuItem('重新定义范围', editPolygon.bind(polygon)));
polygon.addContextMenu(contextMenu);
}
}
tpl = grid_region_distribute_datas.innerHTML;
view = $('#grid-region-distribute-view');
var a = 1;
for (i = 0; i < gridRegions.length; i++) {
regions.map(r => r.name == gridRegions[i].region.name ? r.grids = gridRegions[i].relates : a = 2);
}
laytpl(tpl).render(regions, function(html){
view.html(html);
$('.center-zoom-region').click(function() {
for (i = 0; i < $('.center-zoom-region').length; i++) {
$($('.center-zoom-region')[i]).parent().parent().removeClass('selected');
}
$(this).parent().parent().addClass('selected');
centerZoomRegion($(this).attr('data-name'));
})
$('.center-zoom-grid').click(function() {
let gridName = $(this).attr('data-name'),
gridMarker = null;
gridMarker = filterOverLays(ol => ol.datas && ol.datas.type == 'marker' && ol.datas.detail.name == gridName);
gridMarker.setLabel(getMarkerLabel(gridName));
mp.centerAndZoom(gridMarker.point, 16);
});
});
}
},
getMarkerLabel = function(txt) {
let markerLabel = new BMap.Label(txt, {
offset:new BMap.Size(20,-10)
});
markerLabel.setStyle({
'border': 0,
'background-color': 'rgb(255, 255, 255, 0)'
});
return markerLabel;
},
colorRegion = function(region) {
filterOverLays(ol => ol.datas && ol.datas.type == 'region').forEach(function(rp) {
if (rp.datas.detail.name == region) {
rp.setFillColor('red');
} else {
rp.setFillColor('blue');
}
})
},
centerZoomRegion = function(region) {
mp.centerAndZoom(city + region, 13);
colorRegion(region);
},
init = function(p) {
if (!p.containerId) {
return false;
}
BMap.Polygon.prototype.datas = {};
BMap.Polygon.prototype.setDatas = function(datas) {
this.datas = datas;
};
BMap.Marker.prototype.datas = {};
BMap.Marker.prototype.setDatas = function(datas) {
this.datas = datas;
};
// 显示网格区域边界
gridRegions = p.gridRegions ? p.gridRegions : [];
setBasicDatas();// 基础数据装载
mp = new BMap.Map(p.containerId);
// 创建点坐标
mp.centerAndZoom(city, 12);
// 初始化地图,设置中心点坐标和地图级别
mp.enableScrollWheelZoom();
// 显示行政区域边界
for(i = 0; i < regions.length; i++){
setBoundaries(regions[i].name, colors[i]);
}
loadGridRegions();
// 地图添加点击时间
mp.addEventListener("click", function(e) {
if (isMarker) { // isMarker为true时点击功能表示添加标注
let newMarker = new BMap.Marker(e.point);
newMarker.setDatas({
type: 'marker',
detail: latestMarkerInfo
});
markerPoint(newMarker);
latestMarkerPoint.addEventListener("dragend", function(e) {
var result = BMapLib.GeoUtils.isPointInPolygon(e.point, latestPolygon);
if (!result) {
alert('应急点必须在应急区域内!');
markerPoint(inGridPoint);
} else {
inGridPoint = new BMap.Marker(e.point);
inGridPoint.setDatas(latestMarkerPoint.datas);
}
});
addPolygon();
$('.save-region-grid').removeClass('hide');
} else { // 否则设置点击点为中心,放大地图
mp.centerAndZoom(e.point, 16);
// 设置点击区域
geoc.getLocation(e.point, function(rs){
var addComp = rs.addressComponents,
regionPolygons = null;
$('.region-select').val(addComp.district);
colorRegion(addComp.district);
});
// 显示操作栏
scrollFunc();
}
});
// 滚动监听地图缩放级别,控制操作栏的显示和隐藏
if(document.addEventListener){
document.addEventListener('DOMMouseScroll',scrollFunc,false);
}//W3C
window.onmousewheel=document.onmousewheel=scrollFunc;//IE/Opera/Chrome
$('.region-select').html('<option>-切换目标区域-</option>' + regions.map(r => '<option value="' + r.name + '">' + r.name + '</option>').join(''));
$('.add-marker').click(function() {
addMarker();
});
$('.save-region-grid').click(function() {
saveRegionGrid();
});
$('.toggle-region-grid-list').click(function() {
if ($(this).hasClass('selected')) {
$(this).removeClass('selected');
$('#grid-region-distribute-view').addClass('hide');
} else {
$(this).addClass('selected');
$('#grid-region-distribute-view').removeClass('hide');
}
});
};
return {
init: init
}
}());