//针对的是mapbox加载geojson的数据格式去渲染点线面
首先说说source的类型有哪些:
source的类型有:
1.type: "geojson" (点(circle)线(line)面(fill)图标(symbol))【map.getSource('geojson').setData(geojson)给数据源赋值】
2.type: "image" (图片)【map.getSource("radar").updateImage({ url: getPath() });】
3.type: 'canvas',
4.type: "raster", (瓦片WMS 服务加载)
下面的代码着重写的是geojson格式的数据源渲染点线面,代码如下:
//申明一个变量
var geojson = {
"type": "FeatureCollection",
"features": []
};
//加载source数据源
map.addSource('geojson', {
"type": "geojson",
"data": geojson
});
//点
map.addLayer({
id: 'measure-points',
type: 'circle',
source: 'geojson',
paint: {
'circle-radius': 5,
'circle-color': '#000'
},
filter: ['in', '$type', 'Point']
});
//线
var linestring = {
"type": "Feature",
"geometry": {
"type": "LineString",
"coordinates": []
}
};
map.addLayer({
id: 'measure-lines',
type: 'line',
source: 'geojson',
layout: {
'line-cap': 'round',
'line-join': 'round'
},
paint: {
'line-color': '#000',
'line-width': 2.5,
'line-opacity': 0.8,
'line-gap-width':2
},
filter: ['in', '$type', 'LineString']
});
//面
var polygonjson = {
'type': 'geojson',
'data': {
'type': 'Feature',
'geometry': {
'type': 'Polygon',
'coordinates': [[[[112.9713, 32.37203],[[113.74496, 32.3837],[],[],[]
]]
}
}
};
map.addLayer({
'id': 'polygon',
'type': 'fill',
'source': polygonjson,
'layout': {},
'paint': {
'fill-color': 'red',
'fill-opacity': 0.8
}
});
//另外上测量的代码,供学习参考
//点击地图(测距)
map.on('click', function(e) {
var features = map.queryRenderedFeatures(e.point, { layers: ['measure-points'] });
if (geojson.features.length > 1) geojson.features.pop();
if (features.length) {
var id = features[0].properties.id;
geojson.features = geojson.features.filter(function(point) {
return point.properties.id !== id;
});
}else{
var point = {
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [
e.lngLat.lng,
e.lngLat.lat
]
},
"properties": {
"id": String(new Date().getTime())
}
};
geojson.features.push(point);
}
if (geojson.features.length > 1) {
linestring.geometry.coordinates = geojson.features.map(function(point) {
return point.geometry.coordinates;
});
geojson.features.push(linestring);
var value = document.createElement('pre');
value.textContent = 'Total distance: ' + turf.lineDistance(linestring).toLocaleString() + 'km';
distanceContainer.appendChild(value);
}
map.getSource('geojson').setData(geojson);
});
//鼠标滑过地图
map.on('mousemove', function (e) {
var features = map.queryRenderedFeatures(e.point, { layers: ['measure-points'] });
map.getCanvas().style.cursor = (features.length) ? 'pointer' : 'crosshair';
});
ps:如有写得不对的地方,还请探讨共同学习!