概述:
在上一篇文章(Arcgis for js之GP實現緩衝區計算)介紹了Arcgis for js實現緩衝區計算,但是很多時候,我們不會用Arcgis的東西卻想調用GP來實現對應的功能,怎麼做呢,沒錯,本文將講述如何通過ajax的方式去執行GP並返回結果。
思路:
按下F12打開谷歌的調試工具,切換到網絡,再執行,可以看到GP執行時請求的url,如下:
在瀏覽器中分別打開1,2,3,可以開到各自的請求結果如下:
1、
{"jobId":"j75ee9938cd9b450fb76eb0f603040fbc","jobStatus":"esriJobSubmitted"}
2、
{"jobId":"j123084f770754cf6b76892d2fa44b80e","jobStatus":"esriJobSucceeded","results":{"output":{"paramUrl":"results/output"}},"inputs":{"input":{"paramUrl":"inputs/input"},"Distance__value_or_field_":{"paramUrl":"inputs/Distance__value_or_field_"}},"messages":[]}
3、
說明:
從2中,可以看到,編號爲2的URL執行了三遍,在此,我個人的理解是2的請求有時候返回不了結果,所以一直請求,直到請求成功。
關鍵代碼:
var gpUrl = 'http://localhost:6080/arcgis/rest/services/erase/GPServer/erase';
說明:
這個GP服務是計算erase分析的,沒有輸入,即數據的參數已經定義好了,爲兩個shp文件,只是將計算的結果作爲輸出結果輸出。
1、
$("#calGP").on("click",function(){ $.messager.progress({ text:"計算中,請稍後..." }); $.ajax({ type: "POST", cache: false, url: gpUrl+"/submitJob?f=json", async: true, success: function (result) { result = eval("("+result+")"); var jobId = result.jobId; if(jobId){ submitJob(jobId); } else{ $.messager.progress('close'); $.messager.alert("提示","計算失敗!"); } } }); });
說明:
url1請求成功後,返回的是一個jobid。
2、
function submitJob(jobId){ $.ajax({ type: "POST", cache: false, url: gpUrl+"/jobs/"+jobId+"?f=json", async: true, success: function (result1) { result1 = eval("("+result1+")"); if(result1.jobStatus==="esriJobSucceeded"){ showResult(jobId); } else{ submitJob(jobId); } } }); }
說明:
請求不成功,在此提交請求,直到請求成功。
3、
function showResult(jobId){ $.ajax({ type: "POST", cache: false, url: gpUrl + "/jobs/" + jobId + "/results/erase_shp?f=json&returnType=data", async: true, success: function (result2) { result2 = eval("(" + result2 + ")"); $.messager.progress('close'); $.messager.alert("提示", "計算完成!"); var features = result2.value.features; if (features.length > 0) { for (var i = 0, length = result2.length; i != length; ++i) { var feature = features[i]; if(feature==undefined){ return; } else { var polySymbolRed = new esri.symbol.SimpleFillSymbol(); polySymbolRed.setOutline(new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_SOLID, new dojo.Color([0, 0, 0, 0.5]), 1)); polySymbolRed.setColor(new dojo.Color([255, 0, 0, 0.5])); var g = new esri.Graphic(new esri.geometry.Polygon(feature.geometry), polySymbolRed, feature.attributes) map.graphics.add(g); } } } } }); }
說明:
請求成功,將結果展示。