• 基础聚合:只聚合,不显示聚合的数量
// Basic Clustering
require([
"esri/map",
"esri/layers/FeatureLayer",
"esri/dijit/PopupTemplate",
"dojo/domReady!"
], function(Map, FeatureLayer, PopupTemplate,
) {
var serviceUrl = "http://10.19.147.199:6080/arcgis/rest/services/GW_MAP_LF/MapServer/23";
var layer = new FeatureLayer(serviceUrl, {
outFields: [ "x", "y", "company ", "name " ],
featureReduction: {
type: "cluster"
},
infoTemplate: new PopupTemplate({
title: "{name}",
description: "{x} {y} {company}."
})
});
map.addLayer(layer,3);});
  • ClusterLayer:聚合并显示聚合的数量
require([
"esri/request", "esri/tasks/query", "esri/tasks/QueryTask",
"dojo/ready", "dojo/_base/array", "esri/Color", "dojo/dom-style",
"esri/SpatialReference","esri/geometry/webMercatorUtils",
"esri/graphic", "esri/geometry/Extent",
"esri/symbols/SimpleMarkerSymbol", "esri/symbols/SimpleFillSymbol", "esri/symbols/PictureMarkerSymbol",
"esri/renderers/ClassBreaksRenderer",
"esri/layers/GraphicsLayer", "esri/dijit/PopupTemplate",
"esri/geometry/Point",
"js/ClusterLayer",
"dijit/layout/ContentPane",
"dojo/domReady!"
], function(
esriRequest,
Query,QueryTask,
ready, arrayUtils, Color, domStyle,
SpatialReference,webMercatorUtils,
Graphic, Extent,
SimpleMarkerSymbol, SimpleFillSymbol, PictureMarkerSymbol,
ClassBreaksRenderer,
GraphicsLayer, PopupTemplate, Point,
ClusterLayer
) {
map.on('load', function () {
var clusterLayer;
console.log("mapLoaded!!!!!!!!!");
var queryTask = new QueryTask("http://10.19.147.199:6080/arcgis/rest/services/GW_MAP_LF/MapServer/23");
var query = new Query();
query.where = "1 = 1";
query.outSpatialReference = {wkid:3857};
query.returnGeometry = true;
// query.outSpatialReference = new SpatialReference(3857);
query.outFields = ["*"];//查询所有属性。
queryTask.execute(query, resultshow,errorback);
});
function errorback(error) {
console.log(error);
}
function resultshow(results) {
var data = [];//聚合数据源定义
if (results.features.length > 0) {
for (var i = 0; i < results.features.length; i++) {//遍历查询的图层结果集合,构造聚合效果的数据源
var info = {};
// var latlng = results.features[i].geometry;
// var webMercator = webMercatorUtils.geographicToWebMercator(latlng);//地理坐标系必须要转换摩卡托的投影坐标系,不然聚合没效果
info.x = results.features[i].attributes.x;
info.y = results.features[i].attributes.y;
info.attributes = results.features[i].attributes;//气泡窗口模型的属性 data.push(info);
} //小弹窗
var popupTemplate = new esri.dijit.PopupTemplate({//气泡窗口模型定义
"title": "",
"fieldInfos": [{
"fieldName": "name",//字段值
"label": "name:",//字段显示别名
visible: true//设置是否可见
}, {
"fieldName": "name1",//字段值
"label": "name1:",//字段显示别名
visible: true//设置是否可见
}, {
"fieldName": "name2",//字段值
"label": "name2:",//字段显示别名
visible: true//设置是否可见
}]
}); clusterLayer = new ClusterLayer({
"data": data,//绑定聚合数据源
"distance": 50,//设置聚合距离,根据地图分辨率来设置合适的值,默认是50
"id": "clusters",
"labelColor": "#fff",//图标字体颜色值,白色字体
"labelOffset": 10,//字体偏移位置
"resolution": map.extent.getWidth() / map.width,//计算当前地图的分辨率
"singleColor": "#888",
"singleTemplate": popupTemplate//绑定气泡窗口模型
}); var defaultSym = new esri.symbol.SimpleMarkerSymbol().setSize(100);
var renderer = new ClassBreaksRenderer(defaultSym, "clusterCount");
var picBaseUrl = "http://static.arcgis.com/images/Symbols/Shapes/";
var blue = new esri.symbol.PictureMarkerSymbol(picBaseUrl + "BluePin1LargeB.png", 32, 32).setOffset(0, 15);
var green = new esri.symbol.PictureMarkerSymbol(picBaseUrl + "GreenPin1LargeB.png", 64, 64).setOffset(0, 15);
var red = new esri.symbol.PictureMarkerSymbol(picBaseUrl + "RedPin1LargeB.png", 72, 72).setOffset(0, 15);
renderer.addBreak(0, 100, blue);
renderer.addBreak(100, 500, green);
renderer.addBreak(500, 1000, red);
//设置聚合图层的分级模板
clusterLayer.setRenderer(renderer);
map.addLayer(clusterLayer); // close the info window when the map is clicked
map.on("click", cleanUp);
// close the info window when esc is pressed
map.on("key-down", function (e) {
if (e.keyCode === 27) {
cleanUp();
}
}); function cleanUp() {
map.infoWindow.hide();
clusterLayer.clearSingles();
} window.showExtents = function() {
var extents = map.getLayer("clusterExtents");
if ( extents ) {
map.removeLayer(extents);
}
extents = new GraphicsLayer({ id: "clusterExtents" });
var sym = new SimpleFillSymbol().setColor(new Color([205, 193, 197, 0.5])); arrayUtils.forEach(clusterLayer._clusters, function(c, idx) {
var e = c.attributes.extent;
extents.add(new Graphic(new Extent(e[0], e[1], e[2], e[3], map.spatialReference), sym));
}, this);
map.addLayer(extents, 0);
};
}
}; });
  • 官方clusterlayer源码
define([
"dojo/_base/declare",
"dojo/_base/array",
"esri/Color",
"dojo/_base/connect", "esri/SpatialReference",
"esri/geometry/Point",
"esri/graphic",
"esri/symbols/SimpleMarkerSymbol",
"esri/symbols/TextSymbol", "esri/dijit/PopupTemplate",
"esri/layers/GraphicsLayer"
], function (
declare, arrayUtils, Color, connect,
SpatialReference, Point, Graphic, SimpleMarkerSymbol, TextSymbol,
PopupTemplate, GraphicsLayer
) {
return declare([GraphicsLayer], {
constructor: function(options) {
// options:
// data: Object[]
// Array of objects. Required. Object are required to have properties named x, y and attributes. The x and y coordinates have to be numbers that represent a points coordinates.
// distance: Number?
// Optional. The max number of pixels between points to group points in the same cluster. Default value is 50.
// labelColor: String?
// Optional. Hex string or array of rgba values used as the color for cluster labels. Default value is #fff (white).
// labelOffset: String?
// Optional. Number of pixels to shift a cluster label vertically. Defaults to -5 to align labels with circle symbols. Does not work in IE.
// resolution: Number
// Required. Width of a pixel in map coordinates. Example of how to calculate:
// map.extent.getWidth() / map.width
// showSingles: Boolean?
// Optional. Whether or graphics should be displayed when a cluster graphic is clicked. Default is true.
// singleSymbol: MarkerSymbol?
// Marker Symbol (picture or simple). Optional. Symbol to use for graphics that represent single points. Default is a small gray SimpleMarkerSymbol.
// singleTemplate: PopupTemplate?
// PopupTemplate</a>. Optional. Popup template used to format attributes for graphics that represent single points. Default shows all attributes as "attribute = value" (not recommended).
// maxSingles: Number?
// Optional. Threshold for whether or not to show graphics for points in a cluster. Default is 1000.
// webmap: Boolean?
// Optional. Whether or not the map is from an ArcGIS.com webmap. Default is false.
// spatialReference: SpatialReference?
// Optional. Spatial reference for all graphics in the layer. This has to match the spatial reference of the map. Default is 102100. Omit this if the map uses basemaps in web mercator. this._clusterTolerance = options.distance || 50;
this._clusterData = options.data || [];
this._clusters = [];
this._clusterLabelColor = options.labelColor || "#000";
// labelOffset can be zero so handle it differently
this._clusterLabelOffset = (options.hasOwnProperty("labelOffset")) ? options.labelOffset : -5;
// graphics that represent a single point
this._singles = []; // populated when a graphic is clicked
this._showSingles = options.hasOwnProperty("showSingles") ? options.showSingles : true;
// symbol for single graphics
var SMS = SimpleMarkerSymbol;
this._singleSym = options.singleSymbol || new SMS("circle", 6, null, new Color("#888"));
this._singleTemplate = options.singleTemplate || new PopupTemplate({ "title": "", "description": "{*}" });
this._maxSingles = options.maxSingles || 1000; this._webmap = options.hasOwnProperty("webmap") ? options.webmap : false; this._sr = options.spatialReference || new SpatialReference({ "wkid": 102100 }); this._zoomEnd = null;
}, // override esri/layers/GraphicsLayer methods
_setMap: function(map, surface) {
// calculate and set the initial resolution
this._clusterResolution = map.extent.getWidth() / map.width; // probably a bad default...
this._clusterGraphics(); // connect to onZoomEnd so data is re-clustered when zoom level changes
this._zoomEnd = connect.connect(map, "onZoomEnd", this, function() {
// update resolution
this._clusterResolution = this._map.extent.getWidth() / this._map.width;
this.clear();
this._clusterGraphics();
}); // GraphicsLayer will add its own listener here
var div = this.inherited(arguments);
return div;
}, _unsetMap: function() {
this.inherited(arguments);
connect.disconnect(this._zoomEnd);
}, // public ClusterLayer methods
add: function(p) {
// Summary: The argument is a data point to be added to an existing cluster. If the data point falls within an existing cluster, it is added to that cluster and the cluster's label is updated. If the new point does not fall within an existing cluster, a new cluster is created.
//
// if passed a graphic, use the GraphicsLayer's add method
if ( p.declaredClass ) {
this.inherited(arguments);
return;
} // add the new data to _clusterData so that it's included in clusters
// when the map level changes
this._clusterData.push(p);
var clustered = false;
// look for an existing cluster for the new point
for ( var i = 0; i < this._clusters.length; i++ ) {
var c = this._clusters[i];
if ( this._clusterTest(p, c) ) {
// add the point to an existing cluster
this._clusterAddPoint(p, c);
// update the cluster's geometry
this._updateClusterGeometry(c);
// update the label
this._updateLabel(c);
clustered = true;
break;
}
} if ( ! clustered ) {
this._clusterCreate(p);
p.attributes.clusterCount = 1;
this._showCluster(p);
}
}, clear: function() {
// Summary: Remove all clusters and data points.
this.inherited(arguments);
this._clusters.length = 0;
}, clearSingles: function(singles) {
// Summary: Remove graphics that represent individual data points.
var s = singles || this._singles;
arrayUtils.forEach(s, function(g) {
this.remove(g);
}, this);
this._singles.length = 0;
}, onClick: function(e) {
// remove any previously showing single features
this.clearSingles(this._singles); // find single graphics that make up the cluster that was clicked
// would be nice to use filter but performance tanks with large arrays in IE
var singles = [];
for ( var i = 0, il = this._clusterData.length; i < il; i++) {
if ( e.graphic.attributes.clusterId == this._clusterData[i].attributes.clusterId ) {
singles.push(this._clusterData[i]);
}
}
if ( singles.length > this._maxSingles ) {
alert("Sorry, that cluster contains more than " + this._maxSingles + " points. Zoom in for more detail.");
return;
} else {
// stop the click from bubbling to the map
e.stopPropagation();
this._map.infoWindow.show(e.graphic.geometry);
this._addSingles(singles);
}
}, // internal methods
_clusterGraphics: function() {
// first time through, loop through the points
for ( var j = 0, jl = this._clusterData.length; j < jl; j++ ) {
// see if the current feature should be added to a cluster
var point = this._clusterData[j];
var clustered = false;
var numClusters = this._clusters.length;
for ( var i = 0; i < this._clusters.length; i++ ) {
var c = this._clusters[i];
if ( this._clusterTest(point, c) ) {
this._clusterAddPoint(point, c);
clustered = true;
break;
}
} if ( ! clustered ) {
this._clusterCreate(point);
}
}
this._showAllClusters();
}, _clusterTest: function(p, cluster) {
var distance = (
Math.sqrt(
Math.pow((cluster.x - p.x), 2) + Math.pow((cluster.y - p.y), 2)
) / this._clusterResolution
);
return (distance <= this._clusterTolerance);
}, // points passed to clusterAddPoint should be included
// in an existing cluster
// also give the point an attribute called clusterId
// that corresponds to its cluster
_clusterAddPoint: function(p, cluster) {
// average in the new point to the cluster geometry
var count, x, y;
count = cluster.attributes.clusterCount;
x = (p.x + (cluster.x * count)) / (count + 1);
y = (p.y + (cluster.y * count)) / (count + 1);
cluster.x = x;
cluster.y = y; // build an extent that includes all points in a cluster
// extents are for debug/testing only...not used by the layer
if ( p.x < cluster.attributes.extent[0] ) {
cluster.attributes.extent[0] = p.x;
} else if ( p.x > cluster.attributes.extent[2] ) {
cluster.attributes.extent[2] = p.x;
}
if ( p.y < cluster.attributes.extent[1] ) {
cluster.attributes.extent[1] = p.y;
} else if ( p.y > cluster.attributes.extent[3] ) {
cluster.attributes.extent[3] = p.y;
} // increment the count
cluster.attributes.clusterCount++;
// attributes might not exist
if ( ! p.hasOwnProperty("attributes") ) {
p.attributes = {};
}
// give the graphic a cluster id
p.attributes.clusterId = cluster.attributes.clusterId;
}, // point passed to clusterCreate isn't within the
// clustering distance specified for the layer so
// create a new cluster for it
_clusterCreate: function(p) {
var clusterId = this._clusters.length + 1;
// console.log("cluster create, id is: ", clusterId);
// p.attributes might be undefined
if ( ! p.attributes ) {
p.attributes = {};
}
p.attributes.clusterId = clusterId;
// create the cluster
var cluster = {
"x": p.x,
"y": p.y,
"attributes" : {
"clusterCount": 1,
"clusterId": clusterId,
"extent": [ p.x, p.y, p.x, p.y ]
}
};
this._clusters.push(cluster);
}, _showAllClusters: function() {
for ( var i = 0, il = this._clusters.length; i < il; i++ ) {
var c = this._clusters[i];
this._showCluster(c);
}
}, _showCluster: function(c) {
var point = new Point(c.x, c.y, this._sr);
this.add(
new Graphic(
point,
null,
c.attributes
)
);
// code below is used to not label clusters with a single point
if ( c.attributes.clusterCount == 1 ) {
return;
} // show number of points in the cluster
var label = new TextSymbol(c.attributes.clusterCount.toString())
.setColor(new Color(this._clusterLabelColor))
.setOffset(0, this._clusterLabelOffset);
this.add(
new Graphic(
point,
label,
c.attributes
)
);
}, _addSingles: function(singles) {
// add single graphics to the map
arrayUtils.forEach(singles, function(p) {
var g = new Graphic(
new Point(p.x, p.y, this._sr),
this._singleSym,
p.attributes,
this._singleTemplate
);
this._singles.push(g);
if ( this._showSingles ) {
this.add(g);
}
}, this);
this._map.infoWindow.setFeatures(this._singles);
}, _updateClusterGeometry: function(c) {
// find the cluster graphic
var cg = arrayUtils.filter(this.graphics, function(g) {
return ! g.symbol &&
g.attributes.clusterId == c.attributes.clusterId;
});
if ( cg.length == 1 ) {
cg[0].geometry.update(c.x, c.y);
} else {
console.log("didn't find exactly one cluster geometry to update: ", cg);
}
}, _updateLabel: function(c) {
// find the existing label
var label = arrayUtils.filter(this.graphics, function(g) {
return g.symbol &&
g.symbol.declaredClass == "esri.symbol.TextSymbol" &&
g.attributes.clusterId == c.attributes.clusterId;
});
if ( label.length == 1 ) {
// console.log("update label...found: ", label);
this.remove(label[0]);
var newLabel = new TextSymbol(c.attributes.clusterCount)
.setColor(new Color(this._clusterLabelColor))
.setOffset(0, this._clusterLabelOffset);
this.add(
new Graphic(
new Point(c.x, c.y, this._sr),
newLabel,
c.attributes
)
);
// console.log("updated the label");
} else {
console.log("didn't find exactly one label: ", label);
}
}, // debug only...never called by the layer
_clusterMeta: function() {
// print total number of features
console.log("Total: ", this._clusterData.length); // add up counts and print it
var count = 0;
arrayUtils.forEach(this._clusters, function(c) {
count += c.attributes.clusterCount;
});
console.log("In clusters: ", count);
} });
});

ArcGIS api for JavaScript 3.27 聚合(cluster)的更多相关文章

  1. ArcGIS api for JavaScript 3.27 FindTask查询功能

    在ArcGIS API中查询功能是经常使用的,常用的三个查询分别是FindTask,QueryTask,IdentifyTask.它们各自都有自己的特点. 查询功能分为属性查询和空间查询 FindTa ...

  2. ArcGIS api for JavaScript 3.27 按需显示需要的图层

    实例:现有一图层服务,现需要动态显示该图层中的一部分内容:点击一个图例,只显示这个图例的内容,再点击别的图例,原来的内容不消失,再次点击已被点击的图例才会消失. 思路:setLayerDefiniti ...

  3. ArcGIS api for JavaScript 3.27 在线浏览的一些小部件

    var navOption; var navToolbar;// 当前选择的操作 require( [ "esri/toolbars/navigation", "esri ...

  4. ArcGIS API for JavaScript 4.2学习笔记[0] AJS4.2概述、新特性、未来产品线计划与AJS笔记目录

    放着好好的成熟的AJS 3.19不学,为什么要去碰乳臭未干的AJS 4.2? 4.2全线基础学习请点击[直达] 4.3及更高版本的补充学习请关注我的博客. ArcGIS API for JavaScr ...

  5. ArcGIS API for JavaScript开发初探——基础知识

    1.前言 在ArcGIS Web API开发体系中一共有四大类,分别为: ArcGIS API for Flex ArcGIS API for JavaScript ArcGIS API for RE ...

  6. 基于ArcGIS API for Javascript的地图编辑工具

    最近工作上需要用ArcGIS API for Javascript来开发一个浏览器上使用的地图编辑工具,分享一下一些相关的开发经验. 我开发的地图编辑工具是根据ESRI提供的例子修改而来的,参考的例子 ...

  7. ArcGIS API for JavaScript(2)-ArcGIS Server发布要素图层服务

    1.前言 上一篇该系列的文章我们主要讲了一下基础Web地图搭建,这篇我们主要讲一下ArcGIS Server发布服务,并且如何调用服务.将自己的数据加载到Web地图当中来,实现Web端浏览数据. 2. ...

  8. ArcGIS API for JavaScript 4.0(一)

    原文:ArcGIS API for JavaScript 4.0(一) 最近ArcGIS推出了ArcGIS API for JavaScript 4.0,支持无插件3D显示,而且比较Unity和Sky ...

  9. ArcGIS API for JavaScript开发环境搭建及第一个实例demo

    原文:ArcGIS API for JavaScript开发环境搭建及第一个实例demo ESRI公司截止到目前已经发布了最新的ArcGIS Server for JavaScript API v3. ...

随机推荐

  1. 在 C# 中使用变量

    目录 变量的声明 数据类型 变量的赋值 变量的使用 总结 程序离不开数据.把数字.字母和文字输入计算机,就是希望它利用这些数据完成某些任务.例如,需要计算双十一怎么买才最省钱或者显示购物车里面的商品列 ...

  2. Ubuntu Server 16.04 LTS上怎样安装下载安装Nginx并启动

    场景 Linux-安装 Ubuntu Server 16.04 X64(图文教程详细版): https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/deta ...

  3. 渗透测试初学者的靶场实战 2--墨者学院SQL注入—报错盲注

    墨者SQL注入-MYSQL数据库实战环境 实践步骤 1. 决断注入点 输入单引号,提示错误信息: 输入and 1=1 返回页面正常: 输入 and 1=2 返回正常 输入-1,返回异常: 2. 带入s ...

  4. 《Hands-On System Programming with Go》之写文件的代码模板

    使用了buffer,这个神奇东东. var w io.WriteCloser // initialise writer defer w.Close() b := bufio.NewWriter(w) ...

  5. SpringBoot FatJar启动原理

    目录 SpringBoot FatJar启动原理 背景 储备知识 URLStreamHandler Archive 打包 SpringBoot启动 扩展 SpringBoot FatJar启动原理 背 ...

  6. Yii2中多表关联查询

    准备条件: 1.首先准备两张表: customer(用户表)(id, name) order(订单表)(id, customer_id, price) customer 表和 order 表之间是一对 ...

  7. webpack动态加载打包chunk命名

    最近,遇到复杂h5页面开发,为了优化H5首屏加载速度,想到使用按需加载的方式,减少首次加载的JavaScript文件体积,于是将处理过程在这里记录一下,涉及到的主要是以下三点: 使用Webpack如何 ...

  8. spring-boot 再添加mysql启动器的时候报错, The driver is automatically registered via the SPI and manual loading of the driver class....

    mysql驱动更新迭代之后驱动,稍微有点变化: com.mysql.jdbc.Driver (变化为) --> driver-class-name: com.mysql.cj.jdbc.Driv ...

  9. C# 结合 PInvoke 对接 IP 摄像头的笔记

    最近做项目的时候,需要对接厂商提供的 IP 摄像头.但是他们只提供了 C++ 的 SDK,没办法,只能开始撸 C# 的 SDK Helper 类.本篇文章主要记录了对接 C++ DLL 需要注意的几个 ...

  10. TensorFlow实现图像卷积并可视化示例

    图片尺寸要自己修改. 看起来好像没啥意思,不知道下一步能干什么,先卷了再说.由于weights是随机生成的(tf.random_normal作用:用于从服从指定正太分布的数值中取出随机数),所以每次卷 ...