基于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("https://localhost:6443/arcgis/rest/services/SampleWorldCities/MapServer");
      map.addLayer(layer1);
      var clickQuery ,_clickUrl,_clickTree;
      var _clickIds;
      pointQueryClick();


      map.on("click",function(evt){
        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);
              } else {
                alert("当前点未查询到任何元素");
              }
            });
        }

      });

        /**
         * 点击查询
         */
        function pointQueryClick(){
          _clickUrl = "https://localhost:6443/arcgis/rest/services/SampleWorldCities/MapServer";
          _clickIds = [0,1,2];
          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) {
          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 = _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差不多,无非就是多了个字段名的比较。

  • 5
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
第1章Web GIS基础 1.1GIS及相关技术的发展 1.1.1Web开发技术的发展 1.1.2GIS的发展 1.1.3Web服务的发展 1.1.4Web GIS的发展 1.2OGC的Web服务规范 1.2.1OWS服务体系 1.2.2空间信息Web服务的角色与功能 1.2.3空间信息Web服务的系统框架 1.2.4OWS中的常用服务 1.2.5服务的请求与响应 1.3REST及REST风格的Web服务 1.3.1REST中的基础知识 1.3.2REST风格的Web服务 1.3.3REST风格的Web服务实例 1.4Web GIS的组成 1.5ArcGIS Server REST风格的Web服务 1.5.1ArcGIS S erver站点的架构 1.5.2ArcGIS Server发布的服务类型 1.5.3服务发布 1.5.4Web服务的URL及元数据 1.5.5查看地图 1.5.6使用ArcGIS Server REST风格Web服务的过程 1.5.7支持的输出格式 第2章ArcGIS API for JavaScript基础 2.1ArcGIS API for JavaScript版的Hello World 2.2ArcGIS API for JavaScript与Dojo 2.2.1ArcGIS API for JavaScript的构成 2.2.2ArcGIS API for JavaScript与Dojo的关系 2.3开发与调试工具 2.3.1集成开发环境 2.3.2调试工具 2.3.3Firebug 2.3.4其他工具软件 2.4Dojo基础知识 2.4.1JavaScript对象 2.4.2函数也是对象 2.4.3模拟类与继承 2.4.4使用模块与包管理源代码 第3章页面布局设计 3.1使用布局小部件设计页面框架 3.1.1小部件与布局小部件简介 3.1.2使用面板组织页面元素 3.1.3使用容器小部件设计页面布局 3.2可移动的小部件微架构 3.2.1自定义小部件的基础知识 3.2.2内容小部件的基类实现 3.2.3可移动的框架小部件 3.2.4测试 3.3集中控制的小部件微架构 3.3.1可集中控制的框架小部件 3.3.2小部件容器 3.3.3测试 3.3.4订阅/发布模式的事件处理机制 3.4使用菜单组织功能 3.4.1菜单容器小部件 3.4.2菜单项小部件 3.4.3菜单小部件 3.4.4测试 第4章地图与图层 4.1图层操作 4.1.1图层类及其之间的继承关系 4.1.2切片地图图层 4.1.3动态地图图层 4.1.4图形图层 4.1.5带地理参考的影像图层 4.1.6 KML图层 4.2自定义图层 4.2.1自定义动态图层——热度图图层 4.2.2自定义切片地图图层——百度地图 4.2.3自定义图层——三维建筑图 4.3地图操作 4.3.1地图口操作 4.3.2地图属性获取 4.3.3事件处理 4.4地图参数的基本配置 4.4.1漫游与缩放动画的参数配置 4.4.2比例滚动条的参数配置 4.4.3跨域访问参数配置 4.5图层控制器 4.5.1图层控制器小部件模板 4.5.2图层控制器小部件类 4.5.3图层控制器小部件的使用 第5章空间参考系统与几何对象 5.1空间参考系统 5.1.1空间参考系统类 5.1.2参考系统转换 5.2几何对象 5.2.1几何对象类及其之间的继承关系 5.2.2几何对象的绘制 5.2.3几何对象相关的功能模块 第6章符号与图形 6.1符号 6.1.1标记符号 6.1.2线符号 6.1.3填充符号 6.1.4文本符号 6.2图形 6.2.1图形对象的构成
以下是一个基于 ArcGIS JS API 的点查询搜索框的代码示例: ```html <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="initial-scale=1, maximum-scale=1,user-scalable=no"> <title>点查询搜索框</title> <link rel="stylesheet" href="https://js.arcgis.com/4.16/esri/themes/light/main.css"> <script src="https://js.arcgis.com/4.16/"></script> <style> #viewDiv { height: 100%; width: 100%; margin: 0; padding: 0; } .search { position: absolute; z-index: 2; top: 20px; left: 20px; background-color: white; border-radius: 5px; padding: 10px; box-shadow: 0px 3px 6px rgba(0, 0, 0, 0.3); } .search input { width: 200px; padding: 5px; border-radius: 5px; border: none; box-shadow: 0px 3px 6px rgba(0, 0, 0, 0.3); } .search button { background-color: #0079c1; color: white; padding: 5px 10px; border-radius: 5px; border: none; margin-left: 5px; cursor: pointer; box-shadow: 0px 3px 6px rgba(0, 0, 0, 0.3); } .search button:hover { background-color: #005fa3; } </style> </head> <body> <div id="viewDiv"></div> <div class="search"> <input type="text" id="searchInput" placeholder="输入关键字搜索"> <button id="searchButton">搜索</button> </div> <script> require([ "esri/Map", "esri/views/MapView", "esri/layers/FeatureLayer", "esri/widgets/Search" ], function(Map, MapView, FeatureLayer, Search) { // 创建一个地图对象 var map = new Map({ basemap: "gray" }); // 创建一个地图视图对象 var view = new MapView({ container: "viewDiv", map: map, center: [-118.244, 34.052], zoom: 12 }); // 创建一个要素图层对象 var featureLayer = new FeatureLayer({ url: "https://services.arcgis.com/V6ZHFr6zdgNZuVG0/arcgis/rest/services/LA_County_cities/FeatureServer/0" }); // 添加要素图层到地图中 map.add(featureLayer); // 创建一个搜索组件对象 var searchWidget = new Search({ view: view }); // 将搜索组件添加到页面上的搜索框中 searchWidget.container = document.getElementById("searchInput"); // 创建搜索按钮点击事件 document.getElementById("searchButton").addEventListener("click", function() { // 获取搜索框中的关键字 var searchValue = document.getElementById("searchInput").value; // 设置要素图层的查询参数 featureLayer.definitionExpression = "CITY_NAME LIKE '%" + searchValue + "%'"; }); }); </script> </body> </html> ``` 运行该示例,即可在页面上看到一个包含搜索框的地图界面。当输入关键字并点击搜索按钮时,代码会根据输入的关键字在要素图层中进行查询,并将查询结果显示在地图上。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值