arcgis for javascript 之 clone()问题小计
- 情景再现:
用户点击一个featurelayer的图斑,(属性信息从mysql中获取),同时高亮此地块,点击一下个地块时候,取消高亮。(请忽略跨域造成的图标错误,jetty试了好久不能跨域·······)
效果如下:
1 var pgraphic;//被点击的graphic 2 mapViewInstance.on("click", function (evt) { 3 gLayer.removeAll(); 4 pgraphic=null; 5 var data=null; 6 var screenPoint = { 7 x: evt.x, 8 y: evt.y 9 }; 10 mapViewInstance.hitTest(screenPoint).then(function (response) { 11 // debugger; 12 data = response.results[0].graphic.attributes; 13 pgraphic = response.results[0].graphic; 14 // console.log("data: " + data); 15 // console.log("data.FID: " + data.FID); 16 setGraphicAttrbute(data.FID, pgraphic); 17 18 // pgraphic.attributes ={ 19 // "Acadimic": "1111", 20 // "Years": "Pinaceae", 21 // "UserName": 126 22 // } 23 pgraphic.popupTemplate = { // autocasts as new PopupTemplate() 24 title: "{Name}信息", 25 content: [{ 26 type: "fields", 27 fieldInfos: fieldInfoData, 28 }] 29 }; 30 var sym = SimpleFillSymbol({ 31 color: "red", 32 outline: { 33 color: [128, 128, 128, 0.5], 34 width: "0.5px" 35 } 36 }); 37 pgraphic.symbol=new SimpleFillSymbol(SimpleFillSymbol.STYLE_SOLID, new SimpleLineSymbol(SimpleLineSymbol.STYLE_DASH, new dojo.Color([255, 0, 0]), 3)); 40 gLayer.add(pgraphic); 41 45 46 }); 47 });
这样处理后,气泡和信息都能正常显示,但是出现一个奇怪的问题,第二次点击时候,第一次点击所产生的样式,并没有被完全remove掉。。

难道是,gLayer.removeAll() 没起作用?于此同时,各种refresh也不起作用。。。
我又回看了一次代码发现了端倪,
data = response.results[0].graphic.attributes;
pgraphic = response.results[0].graphic;
这里获取的graphic来自featurelayer,只是赋值给一个新变量而已,还是指向了featurelayer中那个graphic。。
pgraphic.symbol=new SimpleFillSymbol(SimpleFillSymbol.STYLE_SOLID, new SimpleLineSymbol(SimpleLineSymbol.STYLE_DASH, new dojo.Color([255, 0, 0]), 3));;
所以,在给pgraphic设置样式的时候,同时也把样式设置到featurelayer上去了。
怎么解决这问题呢?两种解决思路,
1.获得一个全新的pgraphic
2在featurelayer上去除样式,(这个好像不行吧)
突然想起java中的深复制,js不熟悉,我现实不了,翻了翻api看到有 clone这个方法:Creates a deep clone of the graphic object. 这不就是“”深复制么”···
于是修改代码
pgraphic = response.results[0].graphic.clone();
得到一个全新的graphic,再次运行,问题不在啦。。。。。。

setGraphicAttrbute代码如下:
function setGraphicAttrbute(id, pgraphic) { $.ajax({ type: "POST", async: false, url: server_context + "/gisBlock/queryid/" + id, dataType: "json", success: function (msg) { console.log("Data Saved: " + msg.nameId); var jsonData = ""; if (msg != null) { pgraphic.attributes = { "FID":msg.id, "nameId": msg.nameId, "academy": msg.academy, "year": msg.year, "userName": msg.userName, "crops": msg.crops, "area": msg.area, "month":msg.month, } } else { pgraphic.attributes = { "Acadimic": "未查询到相关结果" } } } }); }
初次学习,有什么不对请指正!

浙公网安备 33010602011771号