利用GeoJSON和一些自定义控件创建一个彩色交互式美国各州人口密度分布图的案例。
GeoJSON数据(us-states.js)的每个要素结构如下:
{
"type": "Feature",
"properties": {
"name": "Alabama",
"density": 94.65
},
"geometry": ...
...
}
使用自定义的Mapbox样式的将各州的数据展示到地图上,灰色瓦片是可视化处理时非常合适的背景色
Interactive Choropleth Map
//定义颜色判断方法
function getColor(d){
return d>1000?'#800026':
d>500 ?'#BD0026':
d>200 ?'#E31A1C':
d>100 ?'#FC4E2A':
d>50 ?'#FD8D3C':
d>20 ?'#FEB24C':
d>10 ?'#FED976':
'#FFEDA0';
}
//定义渲染方法
function style(feature){
return {
fillColor:getColor(feature.properties.density);,
weight:2,
opacity:1,
color:'white',
dashArray:'3',
fillOpacity:0.7
};
}
//将颜色设置到图层
L.geoJson(statesData,{style:style}).addTo(map);
//定义要素突出显示方法
function highlightFeature(e){
var layer = e.target;
layer.setStyle({
weight:5,
color:'#666',
dashArray:'',
fillOpacity:0.7
});
if(!L.Browser.ie&&!L.Browser.opera&&!L.Browser.edge){
layer.bringToFront();
}
}
var geojson;
//重置方法
function resetHighlight(e){
geojson.resetStyle(e.target);
}
//跳转到所选州
function zoomToFeature(e){
map.fitBounds(e.target.getBounds());
}
//绑定事件
function onEachFeature(feature,layer){
layer.on({
mouseover:highlightFeature,
mouseout:resetHighlight,
click:zoomToFeature
});
}
geojson = L.geoJson(statesData,{
style:style,
onEachFeature:onEachFeature
}).addTo(map);
var info = L.control();
info.onAdd = function(map){
this._div=L.DomUtil.create('div','info');//创建一个div class为info
this.update();
return this._div;
};
info.update = function(props){
this._div.innerHTML = 'US Population Density
'+(props?
''+props.name+'
'+props.density+'people/ mi2'
:'Hover over a state');
};
info.addTo(map);
更新事件监听
//定义要素突出显示方法
function highlightFeature(e){
...
info.update(layer.feature.properties);
}
var geojson;
//重置方法
function resetHighlight(e){
...
info.update();
}
添加样式
.info{
padding: 6px 8px;
font:14px/16px Arial,Helvetica,sans-serif;
background:white;
background: rgba(255, 255,255, 0.8);
box-shadow: 0 0 15px rgna(0,0,0,0,2);
border-radius: 5px;
}
.info h4{
margin: 0 0 5px;
color: #777;
}
var legend = L.control({position:'bottomright'});
legend.onAdd = function(map){
var div = L.DomUtil.create('div','info legend'),
grades = [0,10,20,50,100,200,500,1000],
labels=[];
for(var i=0;i'+
grades[i]+(grades[i+1]?'–'+grades[i+1]+'
':'+');
}
return div;
}
legend.addTo(map);
样式
.legend{
line-height: 18px;
color: #555;
}
.legend i{
width: 18px;
height: 18px;
float: left;
margin-right: 8px;
opacity: 0.7;
}