在一些使用天地图的项目中,地图上需要添加区域
- 首先创建地图,初始化地图
- 然后把区域所对应的json格式的数据加载进来
- json数据中的每一条就是一个区域面,循环每一条,画出对应的区域
- 最后给每一块区域加点击事件,弹出区域名称
<script>
var map=""
initMap()
function initMap(){
map = new T.Map('loadMap');
map.centerAndZoom(new T.LngLat(120.5689390,30.2653626), zoom);
draw()
} function draw(){
var json= {
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"properties": {
"stroke": "#ff8080",
"stroke-width": 2,
"stroke-opacity": 1,
"fill": "#ff8080",
"fill-opacity": 0.5,
"name": "1号区块1号网格"
},
"geometry": {
"type": "Polygon",
"coordinates": [
[
[
120.55684056133032,
30.28462107474871
],
[
120.55629339069131,
30.284593280699056
],
[
120.55628266185522,
30.28425975148924
],
[
120.55633630603553,
30.28235120142624
],
[
120.55657234042886,
30.281322792554214
]
]
]
}
},
{
"type": "Feature",
"properties": {
"stroke": "#ffff80",
"stroke-width": 2,
"stroke-opacity": 1,
"fill": "#ffff80",
"fill-opacity": 0.5,
"name": "1号区块2号网格"
},
"geometry": {
"type": "Polygon",
"coordinates": [
[
[
120.55819272994995,
30.279026494991495
],
[
120.55844753980637,
30.275551979675335
],
[
120.55651333183049,
30.275458166056332
],
[
120.55651802569626,
30.26727113472435
],
[
120.55724926292896,
30.267857227705527
]
]
]
}
},
{
"type": "Feature",
"properties": {
"stroke": "#80ff80",
"stroke-width": 2,
"stroke-opacity": 1,
"fill": "#80ff80",
"fill-opacity": 0.5,
"name": "1号区块3号网格"
},
"geometry": {
"type": "Polygon",
"coordinates": [
[
[
120.56070327758789,
30.284954313209877
],
[
120.56093294173479,
30.282018822710658
],
[
120.56452877819537,
30.282313273249937
],
[
120.56460857391357,
30.27982329983024
],
[
120.57295259088279,
30.280272947379515
]
]
]
}
}
]
}
for (var i=0;i<json.features.length;i++){
var points=[]
for(var j=0;j<json.features[i].geometry.coordinates[0].length;j++){
points.push(new T.LngLat(json.features[i].geometry.coordinates[0][j][0],json.features[i].geometry.coordinates[0][j][1]))
}
var polygon
polygon = new T.Polygon(points, {
color: json.features[i].properties.stroke,
weight: json.features[i].properties.strokeWidth,
opacity: json.features[i].properties.strokeOpacity,
fillColor: json.features[i].properties.fill,
fillOpacity: json.features[i].properties.fillOpacity,
name: json.features[i].properties.name,
});
map.addOverLay(polygon);
polygon.addEventListener('click',function (e) {
var name = e.target.options.name
var latlng = new T.LngLat(e.lnglat.lng,e.lnglat.lat);
var label = new T.Label({
text: name,
position: latlng,
});
label.setBackgroundColor("#040E3E")
label.setFontColor("#ffffff")
label.setBorderColor("#00E0E7")
label.setOffset(new T.Point(-20, -15))
map.addOverLay(label);
label.addEventListener("mouseout",function () {
map.removeOverLay(label)
})
})
}
}
</script>效果图
这是我自己在项目中遇到的实际需求,有什么问题,欢迎私聊!!!