使用 SharpMap AJAX 控件 + NetTopologySuite (NTS) 實現:滑鼠點擊 → 取得地圖座標 → 空間查詢 → 顯示屬性資訊。
function MapClicked(event, obj) {
var mousePos = SharpMap_GetRelativePosition(event.clientX, event.clientY, obj.container);
var pnt = SharpMap_PixelToMap(mousePos.x, mousePos.y, obj);
GetData(pnt.x, pnt.y); // 呼叫後端 PageMethods
}
PageMethods.GetData(x, y, GetDataSuccess);
工具提示顯示邏輯(toolTip、moveToMouseLoc)略,需配合 <div id="toolTipLayer"> 初始化。
public string GetInfo(double x, double y) {
var oShape = (ShapeFile)GetShapeFile(filepath);
if (!oShape.IsOpen) oShape.Open();
uint iFeature = (uint)oShape.GetFeatureCount();
var oPoint = new SharpMap.Geometries.Point(x, y);
var oPt = GeometryConverter.ToNTSGeometry(oPoint, new GeometryFactory());
for (uint i = 0; i < iFeature; i++) {
var oPoly = GeometryConverter.ToNTSGeometry(oShape.GetFeature(i).Geometry, new GeometryFactory());
if (oPt.Within(oPoly)) { // NTS Within 方法判斷點在多邊形內
if (oShape.GetFeature(i)[someId].ToString().Length > 0) {
return BuildGraveInfoTable(name, value); // 組裝 HTML 回傳
}
}
}
return string.Empty;
}
關鍵點:SharpMap 幾何體轉 NTS 幾何體,使用 NTS Within 方法進行空間關係判斷(作者測試 SharpMap 內建方法不可靠)。
public SharpMap.Geometries.Point GetPointByID(string Id) {
var oShape = (ShapeFile)GetShapeFile(filePath);
oShape.Open();
for (uint i = 0; i < (uint)oShape.GetFeatureCount(); i++) {
var oPoly = GeometryConverter.ToNTSGeometry(oShape.GetFeature(i).Geometry, new GeometryFactory());
if (oShape.GetFeature(i)["Id"].ToString() == Id) {
return new SharpMap.Geometries.Point(oPoly.InteriorPoint.X, oPoly.InteriorPoint.Y);
}
}
return null;
}
// 前端置中
ajaxMap.Map.Center = pCenter;
遍歷所有 Feature 查詢屬於線性掃描,資料量大時效能不佳。後續將嘗試空間索引(R-Tree)、圖層快取等優化策略。
將介紹依屬性值著色、自定義樣式等專題圖製作技巧。