简单的geojson
文件
const geojson = {
"type": "Feature",
"properties": {
"name": "Coors Field",
"amenity": "Baseball Stadium",
"popupContent": "This is where the Rockies play!"
},
"geometry": {
type: "Point",
"coordinates": [-104.99404, 39.75621]
}
};
简单分析geojson文件,其大概可以分为三个大模块:type(类型)、properties(属性信息)、geometry(几何信息)
leaflet
与geojson
加载数据
- 直接加载
L.geoJSON(geojson).addTo(map);
- 先声明空图层再加载资源
const myLayer = L.geoJSON().addTo(map);
myLayer.addData(geojson);
设置geojson
的样式
- 简单设置样式
const myLines = [{
"type": "LineString",
"coordinates": [[-100, 40], [-105, 45], [-110, 55]]
}, {
"type": "LineString",
"coordinates": [[-105, 40], [-110, 45], [-115, 55]]
}];
// 样式
const myStyle = {
"color": "#ff7800", // 颜色
"weight": 5, // 线宽
"opcity": 0.65 // 透明度
};
L.geoJSON(myLines, {
style: myStyle
}).addTo(map);
- 通过属性选择性设置样式
const states = [{
"type": "Feature",
"properties": {"party": "Republican"},
"geometry": {
"type": "Polygon",
"coordinates": [[
[-104.05, 48.99],
[-97.22, 48.98],
[-96.58, 45.94],
[-104.03, 45.94],
[-104.05, 48.99]
]]
}
}, {
"type": "Feature",
"properties": {"party": "Democrat"},
"geometry": {
"type": "Polygon",
"coordinates": [[
[-109.05, 41.00],
[-102.06, 40.99],
[-102.03, 36.99],
[-109.04, 36.99],
[-109.05, 41.00]
]]
}
}];
L.geoJSON(states, {
style: function(feature) {
// 遍历每一个图形
switch (feature.properties.party) {
case 'Republican': return {color: "#ff0000"};
case 'Democrat': return {color: "#0000ff"};
}
}
}).addTo(map);
setStyle
设置样式的方法
layer.setStyle({
weight: 5,
color: '#666',
dashArray: '',
fillOpacity: 0.7
});
移除样式:geojson.resetStyle(layer)
常用的内部方法
onEachFeature
: onEachFeature(feature, layer)
feature: 是geojson中的每一个数据格式
layer: 是geojson转化而来的leaflet数据对象
feature是用来读取geojson中的一些属性数据、layer是用来挂载一些leaflet的一些方法
L.geoJSON(geojson, {
onEachFeature: onEachFeature
}).addTo(map);
function onEachFeature(feature, layer) {
console.log(feature,layer)
if (feature.properties && feature.properties.popupContent) {
layer.bindPopup(feature.properties.popupContent);
}
};
filter
过滤器
const someFeatures = [{
"type": "Feature",
"properties": {
"name": "Coors Field",
"show_on_map": true
},
"geometry": {
"type": "Point",
"coordinates": [-104.99404, 39.75621]
}
}, {
"type": "Feature",
"properties": {
"name": "Busch Field",
"show_on_map": true
},
"geometry": {
"type": "Point",
"coordinates": [-104.98404, 39.74621]
}
}];
L.geoJSON(someFeatures, {
filter: function(feature, layer) {
return feature.properties.show_on_map
}
}).addTo(map);
- 特殊的点图层
const geojsonMarkerOptions = {
radius: 8,
fillColor: "#ff7800",
color: "#000",
weight: 1,
opacity: 1,
fillOpacity: 0.8
};
L.geoJSON(geojson, {
pointToLayer: function (feature, latlng) {
return L.circleMarker(latlng, geojsonMarkerOptions);
}
}).addTo(map);