由于AjaxMap上述的優(yōu)點,現(xiàn)在采用AjaxMap來進行開發(fā)的用戶在不斷的增多,對AjaxMap也就提出了更高的要求,但是目前AjaxMap提供的接口有限,通過什么手段來實現(xiàn)AjaxMap的功能呢?那就是.ashx 文件。
.ashx文件與.aspx文件類似,可以通過它來調(diào)用HttpHandler類,它免去了普通.aspx頁面的控件解析以及頁面處理的過程。.ashx文件適合產(chǎn)生供瀏覽器處理的、不需要回發(fā)處理的數(shù)據(jù)格式,例如用于生成動態(tài)圖片、動態(tài)文本等內(nèi)容。使用.ashx可以讓您專注于編程而不用管相關(guān)的WEB技術(shù)。下面的例子就是使用.ashx和Ajax技術(shù)來實現(xiàn)獲取地圖圖層名稱的功能。
具體流程是,先通過頁面的Xmlhttprequest對象,向layer.ashx發(fā)送請求,由這個頁面與地圖服務(wù)器進行交互,獲得地圖圖層名,然后通過返回一個字符串,從后臺得到,然后再進行解析,具體過程如圖1所示。是不是很像Ajax交互的過程?
下面按照如上思路來具體實現(xiàn)一下。
1、添加ashx文件,編寫代碼。
首先來打開AjaxMap的工程,添加一個Generic Handler的新項,名字叫l(wèi)ayer.ashx。在工程中添加引用,就是安裝目錄下SDK里面的所有內(nèi)容。部分代碼如下:
添加命名空間
using System.Web;
using SuperMap.IS.Utility;
using SuperMap.IS.Web;
編寫ProcessRequest函數(shù)代碼,接受前臺傳遞過來的方法名稱、地圖名稱。
public void ProcessRequest(HttpContext context)
{
m_map = TcpMap.Create("localhost", 8800, new Hashtable());
string strMethod = context.Request["method"];
string strMapName = context.Request["mapname"];
string strRequestText = string.Empty;
switch (strMethod)
{
case "getAllLayersName"://將獲取圖層的過程放到GetLayersName函數(shù)當(dāng)中,方便以后的擴展
strRequestText = GetLayersName(strMapName);
break;
}
context.Response.ContentType = "text/plain";
context.Response.Write(strRequestText);//將獲得的圖層名稱返回
編寫GetLayersName函數(shù),獲得圖層名稱
protected string GetLayersName(string mapName)
{
string strTmp = string.Empty;
MapImage mi = m_map.GetDefaultMapImage(mapName, 0, 0);
MapParam mp = m_map.GetCurrentMapParam();
Layer[] layers = mp.Layers;
strTmp = "layersname:";
for (int i = 0; i < layers.Length; i++)
{
strTmp += layers[i].Name + ",";
}
return strTmp;
}
和TcpMap的調(diào)用方式是一樣的。
2、腳本的代碼
定義Xmlhttprequest對象,使用異步調(diào)用方式。
var xmlhttprequest=null;
function getAllLayersName()
{
if (null==xmlhttprequest)
{
xmlhttprequest = _GetXmlHttpRequest();//使用AjaxMap中的_GetXmlHttpRequest方法來初始化xmlhttprequest對象。
}
xmlhttprequest.open("get","layer.ashx?method=getAllLayersName&mapname=changchun",false);//向layer.ashx發(fā)送參數(shù)
xmlhttprequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlhttprequest.onreadystatechange=onCompleteReturn;//定義回調(diào)的函數(shù)
xmlhttprequest.send(null);
}
編寫回調(diào)函數(shù)的代碼
function onCompleteReturn()
{
var readyState=xmlhttprequest.readyState;
if (readyState==4)//判斷對象狀態(tài),4為完成
{
var status=xmlhttprequest.status;
if(status==200)//信息已經(jīng)返回開始處理信息
{
var strLayersName= xmlhttprequest.responseText;//得到返回的字符串
if(strLayersName!= null)
{
alert(strLayersName);
}
}
else
{
if(onError)//出錯的處理
{
}
}
xmlhttprequest = null;
}
}
為了節(jié)省篇幅,這里就不對返回的值進行解析了。
整個實現(xiàn)過程就是這樣,大部分地圖功能都可以通過這種方式來實現(xiàn)。請注意,是大部分而不是全部,凡是涉及出圖方面的操作都不能使用這種方式來實現(xiàn),例如:制作專題圖等操作。AjaxMap就是通過這種方法來實現(xiàn)的,其中的出圖的操作已經(jīng)被封裝好了,沒有辦法對其進行修改,這也是出圖的操作不能實現(xiàn)的原因。