今天呢,我们说说如何在OL3+的版本中实现链家的地图找房功能。
看看链家的地图找房功能,其实比较简单,主要包涵: 1)基于行政区划的统计展示; 2)分级别展示,逐级钻取。
首先,打开链家地图找房连接,按下F12进入调试,切换到“网络”选项卡,选择“js”,在过滤中输入关键字“callback=J”,这个时候逐个点一下,就能看到我们想要的数据了,如下图:
说明: 1、通过抓取到的数据,验证了我刚开始的功能分析; 2、想获取更多,可逐级点看看看,在本demo中只取了两级。
function addZoneStatic(result) {
var _features = [];
for(var code in result){
var _result = result[code];
var _coord = ol.proj.fromLonLat([_result.longitude, _result.latitude]);
var _geom = new ol.geom.Point(_coord);
var _feature = new ol.Feature({
geometry: _geom,
attr: _result
});
_features.push(_feature);
}
source.addFeatures(_features);
}
var select = new ol.interaction.Select({
condition: ol.events.condition.pointerMove,
layers:[vector],
style: selectStyle
});
map.addInteraction(select);
map.on("click", function (e) {
select.setActive(false);
if(map.hasFeatureAtPixel(e.pixel)){
source.clear();
var _feature = map.getFeaturesAtPixel(e.pixel)[0];
var _attr = _feature.get("attr");
var _border = dealBorder(_attr.border);
var _bGeom = new ol.geom.Polygon([_border]);
_bGeom.transform("EPSG:4326", "EPSG:3857");
var _extent = _bGeom.getExtent();
map.getView().fit(_extent, map.getSize());
$.get("data/haidian.json", function (result) {
addZoneStatic(result);
select.setActive(true);
});
}
});
function getStyle(feature, isselect) {
var styles = [];
var _attr = feature.get("attr");
var _price = (_attr.unit_price/10000).toFixed(1)+"万",
_count = _attr.count.toString(),
_name = _attr.name,
_lon = _attr.longitude,
_lat = _attr.latitude;
var _coord = ol.proj.fromLonLat([_lon, _lat]);
var _geom = new ol.geom.Point(_coord);
var _color = isselect?"rgba(200, 0, 0, .75)":"rgba(0, 200, 0, .75)";
var _font = "normal 12px 微软雅黑",
_offset = 17;
styles.push(new ol.style.Style({
image: new ol.style.Circle({
radius: 45,
fill: new ol.style.Fill({
color: _color
})
}),
text: new ol.style.Text({
text: _price,
textAlign:"center",
textBaseline:"middle",
offsetY:"0",
font: _font,
fill: new ol.style.Fill({
color: '#fff'
})
})
}));
styles.push(new ol.style.Style({
geometry: _geom,
text: new ol.style.Text({
text: _name,
textAlign: "center",
textBaseline: "middle",
font: _font,
offsetY: -_offset,
fill: new ol.style.Fill({
color: '#fff'
})
})
}));
styles.push(new ol.style.Style({
geometry: _geom,
text: new ol.style.Text({
text: _count,
textAlign:"center",
textBaseline:"middle",
font: _font,
offsetY: _offset,
fill: new ol.style.Fill({
color: '#fff'
})
})
}));
return styles;
}
//选中样式
function selectStyle(feature) {
var _attr = feature.get("attr"),
_styles = getStyle(feature, true);
var _border = dealBorder(_attr.border);
var _bGeom = new ol.geom.Polygon([_border]);
_bGeom.transform("EPSG:4326", "EPSG:3857");
_styles.push(new ol.style.Style({
geometry: _bGeom,
stroke: new ol.style.Stroke({
color: "rgba(200, 0, 0, .75)",
width: 2
}),
fill: new ol.style.Fill({
color: "rgba(200, 0, 0, .1)"
})
}));
return _styles;
}