想必各位開發者在使用cesium過程中,點擊選中一個模型時候會出現一個正方形邊框,效果不錯。但是能不能在二維地圖中也實現這個效果呢?
答案是肯定的。先上效果圖,該效果圖是模仿船訊網效果做的,基本一致:
近來在使用openlayers API時發現有一個類叫做ol.style.RegularShape,規則多邊形樣式,通過查閱樣例以及API屬性發現,該類可以實現規則多邊形樣式的繪制與顯示,如五角星、正五邊形、六邊形等等,通過閱讀源碼發現該類繼承ol.style.Image,是通過canvas繪制的規則多邊形,既然是使用canvas繪制,那就好辦了,我們知道canvas可以通過傳入的路徑繪制各種形狀要素,我們可以自定義一個類繼承ol.style.RegularShape,重寫繪制方法,根據不規則多邊形路徑繪制,這樣就達到了我們的目的。
ol.style.RegularShape.call(this, {
radius: radius,
points: 0,
opacity: 1,
rotateWithView: rotateWithView,
rotation: options.rotation !== undefined ? options.rotation : 0,
stroke: options.stroke !== undefined ? options.stroke : null,
fill: options.fill !== undefined ? options.fill : null,
scale: 1,
size: options.size !== undefined ? options.size : null,
snapToPixel: snapToPixel,
atlasManager: options.atlasManager
});
ol.inherits(ol.style.IrregularShape, ol.style.RegularShape);
首先,在canvas中定義一個正方形邊框的路徑信息如下:[5, 44], [0, 35], [0, 5], [2.5, 0], [7.5, 0], [10, 5], [10, 35], [5, 44],設置邊框寬度為1,顏色為紅色,當然你也可以自定義正方形的大小、顏色等屬性。
其次,ol要素樣式設置成樣式組,這樣既可以實現圖片、文字、ol自帶多邊形樣式的顯示,也可以實現自定義正方形邊框的顯示。
var style=[new ol.style.Style({
image: new ol.style.IrregularShape({
fill: oImgStyle.getFill(),
size: ship[status].size,
offset: ship[status].offset,
paths: ship[status].path,
snapToPixel: oImgStyle.getSnapToPixel(),
stroke: oImgStyle.getStroke(),
rotation: oImgStyle.getRotation(),
rotateWithView: oImgStyle.getRotateWithView()
})
}), new ol.style.Style({
image: new ol.style.IrregularShape({
size: textStyle.getOrginSize(),//獲取原始設置大小
offset: textStyle.getOffset(),
paths: textStyle.getPaths(),
snapToPixel: textStyle.getSnapToPixel(),
stroke: textStyle.getStroke(),
rotation: textStyle.getRotation(),
text: "",//設置為空,隱藏標注
rotateWithView: textStyle.getRotateWithView()
})
}), new ol.style.Style({
image: new ol.style.IrregularShape({//自定義正方形邊框
fill: new ol.style.Fill({ color: color }),
stroke: new ol.style.Stroke({ color: 'black', width: 1 }),
size: [12, 50],
offset: [22, 5],
paths: [[[5, 44], [0, 35], [0, 5], [2.5, 0], [7.5, 0], [10, 5], [10, 35], [5, 44]]]
})
})];
Feature.setStyle(style);
最后,使用開源GIS做開發一點好處就是,當你遇到問題無法解決時候,多看看代碼,沒有效果,自己造,沒有想要的功能,自己寫,總會實現自己想要的。