基于ArcGIS JS API 的点击查询功能

应用场景:

         点击地图要素,弹出信息窗,左边显示点击要素的图层树(因为是查询的多个图层),右边显示当前所选要素的所有属性数据,可通过树插件实现动态控制要显示的要素。如果不想把属性表里面的所有属性全部显示出来(因为包含一些ObjectId之类的无用字段),可以与后台数据库交互,获取需要显示的字段。

效果图:

详细代码:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>点击查询</title>
  <link rel="stylesheet" href="http://localhost/arcgis_js_api/library/3.25/3.25/dijit/themes/tundra/tundra.css">
  <link rel="stylesheet" type="text/css" href="http://localhost/arcgis_js_api/library/3.25/3.25/esri/css/esri.css" />
  <script type="text/javascript" src="http://localhost/arcgis_js_api/library/3.25/3.25/init.js"></script>

  <style type="text/css">
    *{
      margin:0px;
      padding:0px;
    }
    html,body{
      height:100%;
      width:100%;
      position: relative;
      overflow: hidden;
    }
  </style>

  <script type="text/javascript">
    require([
      'dojo/on',
        "dojo/dom",
        "dojo/dom-attr",
        "dojo/_base/declare",
        "dojo/_base/lang",
        "dojo/_base/array",
      'esri/map',
      'esri/layers/ArcGISDynamicMapServiceLayer',
        "dojo/_base/xhr",
        "esri/InfoTemplate",
        "esri/dijit/InfoWindow",
        "esri/tasks/IdentifyTask",
        "esri/tasks/IdentifyParameters",
        "esri/tasks/IdentifyResult",
        "esri/tasks/QueryTask",
        "esri/tasks/query",
        "esri/tasks/FeatureSet",
        "dojox/collections/Dictionary",
        "dojo/data/ItemFileReadStore",
        "dijit/tree/ForestStoreModel",
        "dijit/Tree",
        "esri/symbols/SimpleLineSymbol",
        "esri/geometry/Polyline",
        "esri/geometry/Polygon",
        "esri/geometry/geometryEngine",
        "esri/symbols/SimpleMarkerSymbol",
        "esri/Color",
        "esri/graphic",
    ],function(
      on,
      dom,
      domAttr,
      declare,
      lang,
      arrayUtil,
      Map,
      ArcGISDynamicMapServiceLayer,
      xhr,
      InfoTemplate,
      InfoWindow,
      IdentifyTask,
      IdentifyParameters,
      IdentifyResult,
      QueryTask,
      Query,
      FeatureSet,
      Dictionary,
      ItemFileReadStore,
      ForestStoreModel,
      Tree,
      SimpleLineSymbol,
      Polyline,
      Polygon,
      geometryEngine,
      SimpleMarkerSymbol,
      Color,
      Graphic
    ) {
      var map = new Map('mapDiv');
      var layer1 = new ArcGISDynamicMapServiceLayer("http://10.200.223.191:6080/arcgis/rest/services/SDKD/MapServer");
      map.addLayer(layer1);
      var clickQuery ,_clickUrl,_clickTree;
      var _clickIds;
      pointQueryClick();


      map.on("click",function(evt,me){
        if(clickQuery){
          identifyQuery(_clickUrl, _clickIds,
            evt.mapPoint, function(results, map) {
              if (results.length > 0) {
                // 利用hashtable进行对应的生成,获取相同名称的属性值,并放到同一个key对应的value中
                var hashtable = new Dictionary();
                // 这里生成新的数组,获取名字相同的图层名
                for (var i = 0; i < results.length; i++) {
                  if (!hashtable
                    .containsKey(results[i].layerName)) {
                    hashtable.add(
                      results[i].layerName,
                      [results[i].feature]);
                  } else {
                    var arrayFeature = hashtable
                      .item(results[i].layerName);
                    arrayFeature
                      .push(results[i].feature);
                  }
                  addGraphicsToMap(results[i].feature.geometry,null,null,null,null,null);
                }
                if (_clickTree) {
                  _clickTree.destroy();
                }
                handler_click_query(hashtable, evt,
                  me);
              } else {
                alert("当前点未查询到任何元素");
              }
            });
        }

      });

        /**
         * 点击查询
         */
        function pointQueryClick(){
          _clickUrl = "http://10.200.223.191:6080/arcgis/rest/services/SDKD/MapServer";
          _clickIds = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15];
          clickQuery = true;
        }
        function identifyQuery(url, layerIds, geometry,bufferCallback) {
          var identifyTask = new IdentifyTask(url);
          var identifyParams = new IdentifyParameters();
          identifyParams.returnGeometry = true;
          identifyParams.tolerance = 5;
          identifyParams.layerIds = layerIds;
          identifyParams.layerOption = IdentifyParameters.LAYER_OPTION_VISIBLE;
          identifyParams.geometry = geometry;
          identifyParams.width = map.width;
          identifyParams.height = map.height;
          identifyParams.mapExtent = map.extent;
          identifyParams.spatialReference = map.spatialReference;
          identifyTask.execute(identifyParams, lang.hitch(this,
            function(results) {
              if (lang.isFunction(bufferCallback)) {
                bufferCallback(results, map);
              }
            }), function(err) {
          });
        }
        /**
         * 处理点击查询 hashtable key 为图层名称 value 为 feature数组
         */
        function handler_click_query (hashtable, evt, me) {
          var table_tree = "<div style=\"height:280px;overflow:hidden;\"><div id=\"pointQueryResult\" style=\"padding-left:0px;overflow:visible\" > <table width=\"375\" cellpadding=\"0\" style=\"border-width: 1px;border-color: #666666;border-collapse: collapse;\"><tr><th style=\"border:1px solid #666666;\">图层列表</th><th style=\"border:1px solid #666666;\">详细信息</th></tr><tr valign=\"top\">"
            + "<td style=\"width:140px;height:242px;vertical-align: top;border:1px solid #666666;\">"
            + "<div id=\"showLayerResult\" style=\"overflow:auto;width:100%;height:100%;margin:0px;padding:0px;\">";
          var treeData = [];
          hashtable.forEach(function(entry) {
            var item = {};
            item.id = entry.key;
            item.name = entry.key;
            item.type = "test";
            item.children = [];
            treeData.push(item);
            for (var i = 0; i < entry.value.length; i++) {
              var featureId = entry.value[i].attributes['FID']
                ? entry.value[i].attributes['FID']
                : entry.value[i].attributes['OBJECTID'];
              item.children.push({
                _reference : entry.key
                  + featureId
              });
              treeData.push({
                id : entry.key + featureId,
                name : featureId,
                type : "feature"
              });
            }
          });
          var data = {
            identifier : 'id',
            label : 'name',
            items : treeData
          };
          var store = new ItemFileReadStore({
            data : data
          });
          var treeModel = new ForestStoreModel({
            store : store,
            query : {
              type : "test"
            },
            childrenAttrs : ["children"]
          });

          table_tree += "<div id='treeThree'></div>";
          table_tree += "</div>";
          table_tree += "</div>";
          table_tree += "<td style=\"width:290px;height:245px;vertical-align: top;border: 1px solid #666666;\"><div style=\"overflow:auto;width:100%;height:100%;margin:0px;padding:0px;\" id='show_panel_attributes'>";
          table_tree += "</div></td></tr></table><div></div></div></div><div style=\"display:inline-block\"><input id=\"errorInfo\" style=\"display:none;\" type=\"button\" value=\"错误信息\"/><input id=\"errorSub\" style=\"float: right; display: none;\" type=\"button\" value=\"错误上报\"/></div>";
          map.infoWindow.setTitle("点击选择查询");
          map.infoWindow.setContent(table_tree);
          var tree = new Tree({
            model : treeModel,
            autoExpand : true,
            showRoot : false
          }, "treeThree");
          tree.startup();
          tree.on("click", function(item, node, evt) {
            // 获取当前点击的tree的id值
            if (!node.hasChildren()) {// 判断有没有子节点
              var selectId = item.id[0];// 当前的objectid
              var selectName = item.name[0];
              var parentId = node.getParent(selectId).item.id[0];// 图层名称
              var featureArray = hashtable.item(parentId);
              for (var i = 0; i < featureArray.length; i++) {
                if (selectName == (featureArray[i].attributes['FID'] ? featureArray[i].attributes['FID']: featureArray[i].attributes['OBJECTID'])) {
                    // 然后调用对应的单击事件方法
                    var content = me
                      ._doFeatureForClickQuery(featureArray[i]);
                    domAttr.set('show_panel_attributes',
                      'innerHTML', content);
                    break;
                }
              }
            }
          });
          tree.on("load", function() {
            var childrenArray = tree.rootNode.getChildren();
            if (childrenArray.length > 0) {
              var key = childrenArray[0].item.id[0];
              var featureArray = hashtable.item(key);
              if (featureArray.length > 0) {
                  var content = _doFeatureForClickQuery(featureArray[0]);
                  domAttr.set('show_panel_attributes','innerHTML', content);
              }
            }
          });
          _clickTree = tree;
          map.infoWindow.resize(400, 360);
          map.infoWindow.show(evt.screenPoint, map
            .getInfoWindowAnchor(evt.screenPoint));
        }

        /**
         * 点击查询展示属性表里的所有字段
         */
        function _doFeatureForClickQuery (feature) {
          var contents = "";
          contents += "<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" style=\"border-collapse: collapse;\">";
          var flag = 0;
          for (var p in feature.attributes) {
            if (p.toString().toLowerCase().indexOf('shape') != -1
              || p.toString().toLowerCase()
                .indexOf('objectid') != -1
              || p.toString().toLowerCase()
                .indexOf('enabled') != -1)
              continue;
            contents += "<tr>";
            if (flag == 0) {
              contents += "<td height=\"20\" width=\"70\" style=\"border-bottom:1px solid #666666;border-right:1px solid #666666;text-align:right;\">";
            } else {
              contents += "<td height=\"20\" width=\"70\" style=\"border-top:1px solid #666666;border-bottom:1px solid #666666;border-right:1px solid #666666;text-align:right;\">";
            }
            contents += p;
            contents += "</td>";
            if (flag == 0) {
              contents += "<td width=\"125\" style=\"border-bottom:1px solid #666666;border-left:1px solid #666666;border-right:1px solid #666666;padding-left:2px;\">";
            } else {
              contents += "<td width=\"125\" style=\"border:1px solid #666666;padding-left:2px;\">";
            }
            flag++;
            contents += feature.attributes[p].toString()
              .toLowerCase() == "null"
              ? ""
              : feature.attributes[p];
            contents += "</td>";
            contents += "</tr>";
          }
          contents += "</table>";
          return contents;
        }

        function addGraphicsToMap (geometry) {
          var symbol = null;
          switch (geometry.type) {
            case "point" :
              symbol = new SimpleMarkerSymbol(
                SimpleMarkerSymbol.STYLE_CIRCLE, 10,
                new SimpleLineSymbol(
                  SimpleLineSymbol.STYLE_SOLID,
                  new Color([255, 0, 0]), 1),
                new Color([0, 255, 0, 0.25]));
              break;
            case "polyline" :
              symbol = new SimpleLineSymbol(
                SimpleLineSymbol.STYLE_SOLID, new Color([
                  255, 0, 0, 0.8]), 4);
              break;
          }
          var _graphic = new Graphic(geometry,symbol);
          map.graphics.add(_graphic);
        }
    }
    )
  </script>
</head>
<body class="tundra">
  <div id="mapDiv" style="float:left;width: 100%;height: 100%;"></div>
</body>
</html>

上面的代码中是把属性表中所有的属性全部都显示出来了,要实现控制显示字段的话可自行修改。主要用到dojo 里面的xhr。下面的代码可以参考一下:

function fieldsAliansHandler(feature,parentId){
  var content = {"layerAlias": parentId};
  xhr.post({
    url :  "/clickQuer/showfields",   //后台访问地址
    handleAs : 'json',
    content:content,
    load : lang.hitch(this, function(response){
      pointFieldsAlians(feature,response);
    }),
    error : function(response, ioArgs) {
    }
  });
}
function pointFieldsAlians(feature,response){
  addGraphicsToMap(feature.geometry);
  var contents = "";
  contents += "<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" style=\"border-collapse: collapse;\">";
  var flag = 0;
  for(var i=0;i<response.length;i++){
    for (var p in feature.attributes) {
      if (p.toString().toLowerCase().indexOf('shape') != -1
        || p.toString().toLowerCase()
          .indexOf('objectid') != -1
        || p.toString().toLowerCase()
          .indexOf('enabled') != -1)
        continue;
      if(p.toString().toLowerCase() == response[i]["fieldName"] || p.toString() == response[i]["aliasName"]){
        contents += "<tr>";
        if (flag == 0) {
          contents += "<td height=\"20\" width=\"80\" style=\"border-bottom:1px solid #666666;border-right:1px solid #666666;text-align:right;\">";
        } else {
          contents += "<td height=\"20\" width=\"80\" style=\"border-top:1px solid #666666;border-bottom:1px solid #666666;border-right:1px solid #666666;text-align:right;\">";
        }
        contents += response[i]["aliasName"];
        contents += "</td>";
        if (flag == 0) {
          contents += "<td width=\"150\" style=\"border-bottom:1px solid #666666;border-left:1px solid #666666;border-right:1px solid #666666;padding-left:2px;\">";
        } else {
          contents += "<td width=\"150\" style=\"border:1px solid #666666;padding-left:2px;\">";
        }
        flag++;
        contents += feature.attributes[p].toString()
          .toLowerCase() == "null"
          ? ""
          : feature.attributes[p];
        contents += "</td>";
        contents += "</tr>";
      }

    }
  }
  contents += "</table>";
  domAttr.set('show_panel_attributes','innerHTML', contents);
}

要显示指定字段的话,其实跟上面的doFeatureForClickQuery差不多,无非就是多了个字段名的比较。

猜你喜欢

转载自blog.csdn.net/wml00000/article/details/83025322
今日推荐