arcgis for javascript 笔记

lishihuan大约 55 分钟

arcgis for javascript 笔记

vue + 地图: https://www.cnblogs.com/6b7b5fc3/p/14248031.htmlopen in new window

https://blog.csdn.net/weixin_30911451/article/details/99762370open in new window

123456
123456

vue :https://blog.csdn.net/weixin_39839478/article/details/112264088open in new window

https://blog.csdn.net/D_bel/article/details/99290974open in new window

https://blog.csdn.net/qq_21785691/article/details/111478372open in new window

**待整理:**坐标转换(java,js) 坐标获取位置信息

笔记整理--> 离线下载,API 使用,离线部署,创建一个地图,几个常用概念(关于图形的说明),点线面,图层,图层中添加图形,鼠标事件,热力,轨迹,行政区域规划,其他(小部件,)

整理思路: 按理,用 xjb app 开发的新可视化,结合 js分公司 监造

​ 定好 图层切换(因为这个设计到 空间查询,如果定义的图层过多,明显不合理,也不方便)

​ 最好总结一下空间查询,,js分公司这一套 写法,是通过遍历每个图层的写法,,没有 自带的空间查询 好

js分公司 坐标转换changeGpsToBaidu

开发中用到的2个地图瓦片服务:

http://cache1.arcgisonline.cn/arcgis/rest/services/ChinaOnlineCommunity/MapServeropen in new windowhttps://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServeropen in new window

地图API 选型:https://www.136.la/nginx/show-115343.htmlopen in new window

https://blog.csdn.net/LYQHZ/article/details/80720279open in new window

https://lishihuan.maps.arcgis.com/home/organization.html#overviewopen in new window

全国GeoJSON数据(县级)https://malagis.com/gis-data-national-geojson-data-package-download.htmlopen in new window (搭配GeoJsonLayer 在地图中 以图层的形式描边)

GeoJSON中国 行政区域规划 全国坐标.json

自定义--离散GPS坐标点--全国

arcgis官网open in new window

3.x 版本open in new window

image-20210227224348685
image-20210227224348685

ArcGIS体系架构

image-20210206200457499
image-20210206200457499
image-20210206211632752
image-20210206211632752

ArcGIS API for JavaScript版本之间的差异

3.x和4.x详细对比open in new window

image-20210206212104843
image-20210206212104843

由图表可看出,3.X版本仅仅是缺少了三维相关的需求而已

说明

  • arcgis4.x 中1.10版本线路有问题,会被地形遮挡

  • arcgis3.x 不会出现跨域问题,但是4.x存在,会导致一些功能不能正常加载出来(体现在小部件)

常用的几个概念介绍

参考:https://zhuanlan.zhihu.com/p/33074260open in new window

1.View

View即视图,提供了查看和与地图组件交互的方法。地图仅仅是一个容器,存储了包含在基础层和操作层中的地理信息,而视图呈现地图及其各个层,使它们对用户可见。View是基类,它有两个子类,代表两种类型的视图:MapView和SceneView。

2.MapView

MapView显示一个二维视图的地图实例,MapView必须建立和参考至少两个对象:一个地图实例和一个DOM元素,每个分别设置在映射和容器属性中。

3. SceneView

SceneView显示3D查看地图或webscene实例,渲染3D技术采用的是WebGL。SceneView必须有有效的地图实例和一个DOM元素中的一个非零的高度和宽度来渲染。

4.Map

map类包含用于存储、管理和覆盖二维和三维视图共同的图层的属性和方法。图层可以添加和删除掉,但通过一个视图(在二维查看数据)或场景视图中能(在3D查看数据)。因此,地图的实例是一个简单的容器保存层,而视图显示与地图的层和基相互作用的方式。Map类有两个子类:WebMap以及WebScene,分别对应二维视图MapView和三维视图SceneView。

5.Basemap

Basemap用于创建自定义底图。这些底图创建可以从自己服务器发布瓦片服务或者由第三方发布的瓦片服务。

6.图形(graphic)

图形的构成由 图形(geometry) 和 样式(symbol)来组合的(其他属性:attrubutes和info template.)

attributes:属性字段值 geometry:定义一个几何图形 infoTemplate:infoWindow中显示的内容 symbol:图形的样式 visible:图形的可见性

6.1.图形(geometry) 是用来描述几何的构成形状、结构、位置。可以是point、multipoint、polyline、polygon

6.2.样式(symbol) 使用来描述几何的颜色、透明度、外观 等等 使用案例

​ geometry是point、multipoint的symbol可以是marker symbol,polyline的symbol可以是line symbol、polygon的symbol可以是fill symbol。

​ 图片:PictureMarkerSymbol

​ 点:SimpleMarkerSymbol

6.3.attributes 是描述graphic的名称-值对.就是在弹窗详情和选中时用到的 图形的属性值。其中Query.outFieldsopen in new window可以限制任务返回attributes。

6.4.info template定义当graphic被点击时的弹窗

6.5.实例化的方式

​ new Graphic(geometry,symbol,attributes,infoTemplate)

​ new Grpahic(json)

6.6其他属性说明

  • 隐藏显示 :show() ,hide() ,判断 用 graphic.visible。

graphic选中后闪烁

let temp = 0;
let handler = setInterval(function() {
    if (temp === 6) {
		if (handler) {
			if (!graphic.visible){
				graphic.show(); 
                //graphic.visible=false;// 不使用,因为直接修改 不能生效,需要调用 draw()重新绘制图形
			}
			clearInterval(handler);
			handler = null;
		}
		return;
    }
    if (graphic.visible){
		graphic.hide();
	}else{
		graphic.show();
	}
    temp++;
}, 500);
  • attr(name,value):修改属性值
  • draw():绘制图形 (针对 某些时候 修改属性但是 不成功,需要调用 graphic.draw()。正常使用arcgis提供的 方法例如 show(),hide(),set方法等,可以直接 修改成功。
  • getContent():返回内容的值
  • getInfoTemplate():返回信息模板
  • getLayer():返回一个图层的
  • getNode():返回节点用于绘制图层
  • getNodes():返回多个节点
  • getShape():返回一个esri图形
  • etATitle():获取标题
  • setAttributes(attributes):定义图形的属性
  • setGeometry(geometry):定义几何图形
  • setInfoTemplate(infoTempate):定义一个infoWindow
  • setSymbol(symbol):设置图形的象征
  • toJson():将对象转换为json标的是的gis服务器

7.ArcGIS API for JavaScript 屏幕坐标转换


基本属性

// 3.x  地图初始化完成 
map.on("load", function () {
});
// 4.x  地图初始化完成 
view.when(function () {
});


//1.获取图层
// 3.x
map.getLayer("layerId")
// 4.x
map.findLayerById("layerId")
//2.移除图层
// 3.x
map.removeLayer(map.getLayer("layerId"))
// 4.x
map.remove(map.findLayerById("layerId"))

//添加图形
const GeometryObject = {
        geometry: geometry,// geometry(point)对象
        symbol: symbol// symbol样式,可以是线、图片等
}

var layer = new Graphic(GeometryObject);
map.add(layer);
    
//定位到指定位置,并缩放图层    
//3.x 
if(geometry.type=="polygon"){// 多边形
	this.map.setExtent(geometry.getExtent().expand(1.5));  //定位并放大1.5倍
}
if(geometry.type=="point"){
    var cpoint=new esri.geometry.Point();
    cpoint.x=geometry.x;
    cpoint.y=geometry.y;
    cpoint.spatialReference=geometry.spatialReference;
    //this.map.centerAt(cpoint); 
    this.map.centerAndZoom(cpoint,8);
}
// 4.x
view.goTo({target: graphic.geometry,
           tilt: 70//倾斜
          },{
            duration: 2000,//设置动画的确切持续时间(以毫秒为单位)
            easing: "in-out-expo"//用于动画的缓动功能
        }
          
   view.goTo({
        // 看向一个可视区域 主要参数是geometry 或者 extent 
        target: polygon.extent,
        // 将摄像头移动到一个点上面
        center: point || [lon , lat] ,
        // 同上 用上面的center就行了
        position: point,
        // 这个是控制摄像头的水平方向
        heading: 0,
        // 这个是控制摄像头的垂直朝向
        tilt: 90,
        // 地图层级高度 一般最大是20  最小0   20的时候就已经贴着地面了几乎
        zoom: 18,
        // 焦距这个一般都不设置 直接使用target就好了, 一定要理解的话 这个就相当于焦距 也就是说 摄像头的位置设置焦距
        fov: 0
    },{
        // 指是否需要过度动画, 一般都会是true 默认也是true
        animate: true,
        // 动画速度系数 1就是正常速度  0.5就是一半速度 2就是一倍速度
        speedFactor: 1,
        // 持续速度  持续5秒达到  这个配置会覆盖上面的动画系数  
        duration: 5000,
        // 允许的最大持续时间, 有时候镜头移动距离太远了 如果设置的恒定速度 就会导致时间过长, 这个配置可以解决这个问题
        maxDuration: 5000,
        // 移动的模式  均速移动 还有很多配置 详情见api
        easing: "linear"
    })       
          
          
          
          

// 4.将几何添加到地图中( 几何是无法直接添加到地图中的,先将几何添加到layer中  然后将layer添加到map里)
var layer = new GraphcisLayer( { id: "唯一名称" } )
// 将几何添加到图层中
layer.add( graphic );
// 将图层添加到地图中
view.map.add( layer );

// 几何删除自己
graphic.layer.remove(graphic);
// 图层删除自己
view.map.remove(layer);
// 图层查询自己
view.map.findLayerById(id);    

1.当前互联网地图的坐标系现状

腾讯、高德是GCJ02坐标系,百度是BD09坐标系,谷歌、必应是WGS84坐标系,天地图是CGCS2000坐标系,瓦片地图都是平面墨卡托投影。WGS84和CGCS2000坐标系,近似认为它们相等就可以了。

地球坐标 (WGS84)

  • 国际标准,从 GPS 设备中取出的数据的坐标系

  • 国际地图提供商使用的坐标系

    注:谷歌地球

火星坐标 (GCJ-02)也叫国测局坐标系

  • 中国标准,从国行移动设备中定位获取的坐标数据使用这个坐标系

  • 国家规定: 国内出版的各种地图系统(包括电子形式),必须至少采用GCJ-02对地理位置进行首次加密。

    Google国内地图、高德、天地图、QQ地图、腾讯地图 使用

百度坐标 (BD-09)

  • 百度标准,百度 SDK,百度地图,Geocoding 使用
  • (本来就乱了,百度又在火星坐标上来个二次加密)

开发过程需要注意的事

  • 从设备获取经纬度(GPS)坐标

    注:目前我们公司的通过 app采集的是 GCJ02坐标系,应该是 通过高德sdk 获取的,而不是原生定位库,奥维地图采集就是WGS84)

      	如果使用的是百度sdk那么可以获得百度坐标(bd09)或者火星坐标(GCJ02),默认是bd09
      	如果使用的是ios的原生定位库,那么获得的坐标是WGS84
      	如果使用的是高德sdk,那么获取的坐标是GCJ02
    
  • 互联网在线地图使用的坐标系

      火星坐标系:
      		iOS 地图(其实是高德)
      		Google国内地图(.cn域名下)
      		搜搜、阿里云、高德地图、腾讯
      百度坐标系:
      		当然只有百度地图
      WGS84坐标系:
      		国际标准,谷歌国外地图、osm地图等国外的地图一般都是这个
    

公司: 谷歌地图:31.9344120986,117.2649120808 和 腾讯和高德坐标偏移很小 (手机获取到的GPS坐标就是这个坐标系) 百度地图:31.9405040000,117.2714210000 腾讯高德:31.9344119085,117.2649256012 **高德坐标系,国标 ** 图吧地图:31.9378224285,117.2620342812 谷歌地球:31.9364424285,117.2594242812 WGS84坐标系 (奥维地图采集的也是) 北纬N31°56′11.19″ 东经E117°15′33.93″

2.离线部署

离线部署案例:

2.1 注册账号,下载离线api

利用tomcat来部署离线地图api和离线文档sdk

image-20210224230425300
image-20210224230425300

sdk部署离线文档,对应访问的是 arcgis_js_v328_sdk/arcgis_js_v328_sdk/index.html

​ (例:http://localhost:8080/arcgis_js_api/arcgis_js_v415_sdk/index.htmlopen in new window)

image-20201112145630506
image-20201112145630506

2.2 更改init.js和dojo/dojo.js两个配置文件

将两份文件内的”[HOSTNAME_AND_PATH_TO_JSAPI]”更改为JS API在服务器目录下的路径 http://localhost:8080/arcgis_js_api/library/3.28/dojoopen in new window

image-20201112135440147
image-20201112135440147

在tomcat目录下新建文件夹arcgis_js_api,然后讲下载的api拷贝到当前新建的文件夹下(例如上面的图片,将3.28对应的文件夹直接拷贝到arcgis_js_api目录下)

注:最好把baseUrl 改为参数,方便后期修改

参考:https://blog.csdn.net/happy81997/article/details/105552047open in new window

把baseUrl后面的地址全部替换成mybaseUrl,如下图:

将参数放到最前头,设置一个全局变量,可以方便修改

2.3 验证是否部署成功

从官网拷贝一份初始化地图,放到tomcat下,验证浏览器访问是否能正常初始化地图

tomcat下创建demo文件夹,创建index.html 文件访问: http://localhost:8080/demo/index.htmlopen in new window

<!DOCTYPE html>
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <meta name="viewport" content="initial-scale=1, maximum-scale=1,user-scalable=no"/>
    <title>3.x版本 地图deom</title>
    <!-- <link rel="stylesheet" href="https://js.arcgis.com/3.35/esri/css/esri.css">-->
      <!-- 3.引入样式和js  -->
     <link rel="stylesheet" href="http://localhost:8080/arcgis_js_api/3.28/esri/css/esri.css">
      <!--2. 样式  -->
    <style>
      html, body, #map {
        height: 100%;
        margin: 0;
        padding: 0;
      }
    </style>
    <!--<script src="https://js.arcgis.com/3.35/"></script> -->
    <script src="http://localhost:8080/arcgis_js_api/3.28/init.js"></script>
      <!-- 4. 引入 所需要的模块 -->
    <script>
      var map;

      require(["esri/map", "dojo/domReady!"], function(Map) {
        map = new Map("map", {
          basemap: "topo",  // 官网提供了 17种 供选中,常用 satellite (影像图) 和 osm、(地形图、矢量图)
          center: [117.2649120808,31.9344120986], // longitude, latitude
          zoom: 13
        });
      });
    </script>
  </head>

  <body>
      <!-- 1.定义化地图 容器 -->
    <div id="map"></div>
  </body>
</html>
<html>
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no" />
    <title>4.x版本 地图deom</title>
	 <!--2. 样式  -->
    <style>
      html,
      body,
      #viewDiv {
        padding: 0;
        margin: 0;
        height: 100%;
        width: 100%;
      }
    </style>
    <!-- 3.引入样式和js  -->
    <!-- 
		<link rel="stylesheet" href="https://js.arcgis.com/4.18/esri/themes/light/main.css">
		<script src="https://js.arcgis.com/4.18/"></script> 
	-->
	<link rel="stylesheet" href="http://localhost:8080/arcgis_js_api/4.15/esri/themes/light/main.css">
	<script src="http://localhost:8080/arcgis_js_api/4.15/init.js"></script>

    <script>
	// 4. 引入 所需要的模块 
      require(["esri/config","esri/Map", "esri/views/MapView"], function (esriConfig,Map, MapView) {
        //esriConfig.apiKey = "AAPKa0dae5e7bc9e46e1932bea30bc8cf4d5sM5hEtslf394lsn08UY8tKU0SHAXvQEQFHRzId2BwDGf4QQZpsu6Qlk_MciVQRNC";
        // 4.1. 实例化 地图地图
          const map = new Map({
          basemap: "satellite"// // 官网提供了 17种 供选中,常用 satellite (影像图) 和 osm(地形图、矢量图)
        });
		//4.2.创建2D地图
        const view = new MapView({
          map: map,
          center: [117.2649120808,31.9344120986], // Longitude, latitude
          zoom: 13, // Zoom level
          container: "viewDiv" // Div element
        });
      });
	  //4.3. 创建3D地图
	  /*require(["esri/Map", "esri/views/SceneView"], function(Map, SceneView) {
        var map = new Map({
          basemap: "topo-vector",
          ground: "world-elevation"//3D提供的 地形地貌
        });
        var view = new SceneView({
          container: "viewDiv", // Reference to the scene div created in step 5
          map: map, // Reference to the map object created before the scene
          scale: 50000000, // Sets the initial scale to 1:50,000,000
          center: [-101.17, 21.78] // Sets the center point of view with lon/lat
        });
      });*/
    </script>

  </head>
  <body>
       <!-- 1.定义化地图 容器 -->
    <div id="viewDiv"></div>
  </body>
</html>

3. 创建地图

说明: 实例化一个地图,需要 4步

  • 第一步:创建一个html页面,并 给地图添加一个div 容器 <body> <div id="viewDiv"></div> </body>

  • 第二步:设置地图容器样式 html,body,#viewDiv{padding:0;margin:0;height:100%;width:100%;}

  • 第三步:添加对CSS文件和JS库的引用

    <!-- 4.x版本 -->
    <link rel="stylesheet" href="http://localhost:8080/arcgis_js_api/4.15/esri/themes/light/main.css">
    <script src="http://localhost:8080/arcgis_js_api/4.15/init.js"></script>
    <!--3.x版本 -->
    <link rel="stylesheet" href="http://localhost:8080/arcgis_js_api/3.28/esri/css/esri.css">
    <script src="http://localhost:8080/arcgis_js_api/3.28/init.js"></script>
    
  • 第四步:引入 创建地图所用到的模块 (require语句以加载Map和MapView模块 )

    //====================# 4.x版本 下引入的模块 #====================
    require(["esri/Map", "esri/views/MapView"], function (Map, MapView) {
    	// 创建 地图 代码
    });
    
    //====================# 3.x版本 下引入的模块 #====================
    require(["esri/map", "dojo/domReady!"], function(Map) {
       // 创建 地图 代码
    });
    
  • 第五步:实例化 地图(3.x 只用到Map模块、 4.x版本 需要用到 Map实例化底图,然后通过MapView,SceneView 定义属性)

    • MapView :二维地图
    • SceneView:三维地图

    说明: map 有个 ground: "world-elevation" 属性,添加后可有看到地形起伏

    //====================# 4.x版本 下创建地图 #====================
    // 初始化底图
    const map = new Map({
        basemap: "satellite",// 官网提供了 17种 供选中,常用 satellite (影像图) 和 osm(地形图、矢量图)
        ground: "world-elevation" //属性,添加后可有看到地形起伏
    });
    // 4.x三维地图用到的 属性 MapView
    const view = new MapView({
        map: map,
        center: [-118.805, 34.027], // Longitude, latitude
        zoom: 13, // Zoom level
        container: "viewDiv" // Div element
    });
    /* 4.x 二维地图用到的 属性 SceneView
    var view = new SceneView({
      container: "viewDiv", // Reference to the scene div created in step 5
        map: map, // Reference to the map object created before the scene
        scale: 50000000, // Sets the initial scale to 1:50,000,000
        center: [-101.17, 21.78] // Sets the center point of view with lon/lat
    });*/
    //====================# 3.x版本 下创建地图 #====================
    map = new Map("map", {
        basemap: "topo",  // 官网提供了 17种 供选中,常用 satellite (影像图) 和 osm、(地形图、矢量图)
        center: [117.2649120808,31.9344120986], // longitude, latitude
        zoom: 13
    });
    

下面两个后期最为 小案例,其中3.x版本的可以,但是4.x版本的还需要补齐,否则和上面的案例重复了

3.1 创建一个2D\3D 地图(4.x 版本下)

Basemap底图


3.2 创建一个2D地图(3.x )

​ 一个比较全面的的一个案例,Search小部件,定位,鹰眼,比例尺,移动鼠标获取坐标信息,BasemapGallery_图层切换

https://blog.csdn.net/qq_42128407/article/details/80765664open in new window

注: 需要引入esri/css/esri.css 否则地图初始化时可能会出现 空白区域,目前4.x版本好像没有这个问题

 <!DOCTYPE html>  
<html>  
<head>  
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">  
    <meta name="viewport" content="initial-scale=1, maximum-scale=1,user-scalable=no" />  
    <title>final Map</title>  
    <link rel="stylesheet" href="http://localhost:8080/arcgis_js_api/3.28/esri/css/esri.css"> <!-- 需要引,否则可能会出现 地图初始化出现 部分空白 -->
 
    <style>  
        html, body, #map {  
            height: 100%;  
            margin: 0;  
            padding: 0;  
        }  
 
        body {  
            background-color: #FFF;  
            overflow: hidden;  
            font-family: "Trebuchet MS";  
        }  
 
        #BasemapToggle {  
            position: absolute;  
            right: 20px;  
            top: 20px;  
            z-index: 50;  
        }  
 
        #HomeButton {  
            left: 25px;  
            position: absolute;  
            top: 93px;  
            z-index: 50;  
        }  
 
        #LocateButton {  
            left: 25px;  
            position: absolute;  
            top: 130px;  
            z-index: 50;  
        }  
 
        #search {  
            display: block;  
            position: absolute;  
            z-index: 2;  
            top: 25px;  
            left: 75px;  
        }  
    </style>  
    <script src="http://localhost:8080/arcgis_js_api/3.28/init.js"></script>
    <script>  
        var map, mapCenter, selectionToolbar, featureLayer;  
        var visible = [], setLayerVisibility;;  
        require([  
			"esri/basemaps", "esri/map",  "esri/layers/ArcGISTiledMapServiceLayer",  
             "esri/layers/FeatureLayer",  
             "esri/layers/GraphicsLayer",  
             "esri/geometry/Point",  
 
             "esri/symbols/SimpleFillSymbol",  
             "esri/symbols/SimpleLineSymbol",  
             "esri/symbols/SimpleMarkerSymbol",  
             "esri/tasks/query",  
             "esri/toolbars/draw",  
 
             "esri/graphic",  
             "esri/dijit/Scalebar",  
             "esri/dijit/HomeButton",  
             "esri/dijit/LocateButton",  
             "esri/dijit/BasemapToggle",  
             "esri/dijit/OverviewMap",  
             "esri/dijit/Search",  
             "esri/geometry/webMercatorUtils",  
 
             "dojo/dom",  
             "dojo/on",  
             "dojo/_base/Color",  
             "dojox/charting/Chart2D",  
             "dojo/domReady!"],  
         function (  
              esriBasemaps,  
              Map,  
              Tiled,  
              FeatureLayer,  
              GraphicsLayer,  
              Point,  
 
              SimpleFillSymbol, SimpleLineSymbol, SimpleMarkerSymbol,  
              Query,  
              Draw,  
              Graphic,  
              Scalebar,  
              HomeButton,  
              LocateButton,  
              BasemapToggle,  
              OverviewMap,  
              Search,  
              webMercatorUtils,  
              dom,  
              on,  
              Color,  
              Chart2D,  
              domConstruct) {  
             esriBasemaps.delorme = {  
                 baseMapLayers: [  
                     //中国矢量地图服务  
                     { url: "http://cache1.arcgisonline.cn/arcgis/rest/services/ChinaOnlineCommunity/MapServer" }  
                 ],  
                 //缩略图  
                 thumbnailUrl: "shiliang.jpg",  // 对应的 切换图标,可以试url图片
                 title: "矢量图"  
             };  
 
             //初始化地图  
             map = new esri.Map("map", { basemap: "delorme", logo: false, });  

			 
             //var dynamicMapServiceLayer = new esri.layers.ArcGISDynamicMapServiceLayer("http://localhost:6080/arcgis/rest/services/MyMapService/MapServer");  
             //map.addLayer(dynamicMapServiceLayer, 1);
			 
			 // 添加GraphicsLayer图层
             //var chartLayer = new GraphicsLayer({ "id": "chartLayer" });  
             //map.addLayer(chartLayer, 2); 
			 
             mapCenter = new Point(103.847, 36.0473, map.spatialReference);  
             map.centerAndZoom(mapCenter, 4);  
             /*************************************************************************************/  
             //卫星底图  
             var toggle = new BasemapToggle({  
                 map: map,  
                 basemap: "satellite"  
             }, "BasemapToggle");  
            toggle.startup();  
             //返回主视图  
             var home = new HomeButton({  
                 map: map  
             }, "HomeButton");  
             home.startup();  
             //定位  
             var geoLocate = new LocateButton({  
                 map: map  
             }, "LocateButton");  
             geoLocate.startup();  
             //鹰眼  
             var overviewMapDijit = new OverviewMap({  
                 map: map,  
                 expandFactor: 2,  
                 attachTo: "bottom-left",  
                 visible: true  
             });  
             overviewMapDijit.startup();  
             //比例尺  
             var scalebar = new esri.dijit.Scalebar({  
                 map: map,//地图对象  
                 attachTo: "bottom-right",//控件的位置,右下角  
                 scalebarStyle: "ruler",//line 比例尺样式类型  
                 scalebarUnit: "metric"//显示地图的单位,这里是km  
             });  
//搜索  
             var search = new Search({  
                 map: map  
             }, "search");  
             search.startup();  
             //显示地图坐标  
             map.on("load", function () {  
                 //after map loads, connect to listen to mouse move & drag events  
                 map.on("mouse-move", showCoordinates);  
                 map.on("mouse-drag", showCoordinates);  
             });  
             function showCoordinates(evt) {  
                 //the map is in web mercator but display coordinates in geographic (lat, long)  
                 var mp = webMercatorUtils.webMercatorToGeographic(evt.mapPoint);  
                 //display mouse coordinates  
                 dom.byId("info").innerHTML = mp.x.toFixed(3) + ", " + mp.y.toFixed(3);  
             }  
        });
  </script>
  </head>
<body>  
    <div id="map">  
        <!--  返回初始化地图按钮-->  
        <div id="HomeButton"></div>  
        <!--  Html5定位按钮-->  
        <div id="LocateButton"></div>  
        <!--  切换底图-->  
        <div id="BasemapToggle"></div>  
        <!--  搜索栏-->  
        <div id="search"></div>  
        <!--  坐标-->  
        <span id="info" style="position:absolute; left:750px; bottom:5px; color:#000; z-index:50;"></span>  
 
        <button id="selectFieldsButton">选框查询</button>  
        <button id="clearSelectionButton" data-dojo-type="dijit/form/Button">清除选择</button><br>  
        <div id="toc" style="position: absolute; left: 10px; bottom: 20px; border: 1px solid #9c9c9c; background: #fff; width: 100px; height: auto; z-index: 99;padding: 10px;"></div>  
    </div>  
</body>  
</html>

4. 自定义底图 Basemap

https://blog.csdn.net/weixin_45622540/article/details/106923418open in new window

关于ArcGIS API for JavaScript中basemap的总结介绍open in new window

4.1 说明

注: 自定义图层时,需要注意的是,如果是使用的是baseLayers 来定义底图,根据 地图服务的不同使用不同的API

**目前主要区分为,切片服务用:TileLayer; 动态服务用:MapImageLayer **

服务类型服务说明需要的API备注
动态服务一般我们不作处理直接发布的服务通常都是动态服务,服务地址以MapServer结尾,服务信息中没有切片信息esri/layers/MapImageLayer此处仅供参考,详细使用请看官网文档open in new window
切片服务在发布服务的时候对服务做了切片,服务地址以MapServer结尾,服务信息中可以查看到切片信息esri/layers/TileLayer或者esri/layers/WebTileLayer此处仅供参考,详细使用请看官网文档open in new window
影像服务对tif这些数据发布后的服务,服务地址以ImageServer结尾esri/layers/ImageryLayer此处仅供参考,详细使用请看官网文档open in new window
要素服务发布服务的时候选择了服务类型为要素,可以实现对服务的数据要素进行编辑,服务地址以FeatureServer结尾esri/layers/FeatureLayer此处仅供参考,详细使用请看官网文档open in new window
// in this case the portalItem has to be a webmap
var basemap = new Basemap({
  portalItem: {
    id: "8dda0e7b5e2d4fafa80132d59122268c"  // WGS84 Streets Vector webmap
  }
});
  • 切片服务 (TileLayer)
var basemap = new Basemap({
  baseLayers: [
    new TileLayer(...)
  ],
  referenceLayers: [
    new TileLayer(...)
  ],
});
  • 动态服务(需要用MapImageLayer )
// create a basemap from a dynamic mapserver
var basemap = new Basemap({
  baseLayers: [
    new MapImageLayer({
      url: "url to your dynamic MapServer",
      title: "Basemap"
    })
  ],
  title: "basemap",
  id: "basemap"
});

var map = new Map({
  basemap: basemap
});

// create a TileInfo instance using the default settings and
// pass its resulting LOD's to a MapView's constraints
var view = new MapView({
  container: "viewDiv",
  map: map,
  constraints: {
    lods: TileInfo.create().lods
  }
});
  • 影像图 使用 ImageryLayer
  • 要素服务 使用 FeatureLayer
  • 地形 使用 ElevationLayer

**说明:**http://cache1.arcgisonline.cn/arcgis/rest/services/ChinaOnlineCommunity/MapServeropen in new window

一般以 MapServer 结尾的都是 动态服务,但是如果 图层说明中还有对 切片等级的描述,说明该图层 是切片服务

https://sampleserver6.arcgisonline.com/arcgis/rest/services/Wildfire/FeatureServeropen in new window

以 FeatureServer 结尾的服务是要素服务,需要使用 FeatureLayer

在自定义底图中,切片服务用:TileLayer; 动态服务用:MapImageLayer;要素服务: FeatureLayer

如果,使用图层API不对,则可能会出现,地图设置的zoom和container不起作用(直观的体现是,随着地图缩放,地图不能全屏显示)

20210330233110
20210330233110

4.2案例

4.x版本下自定义底图

<html>
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no" />
    <title>Basemap_4.x版本 地图deom</title>
	 <!--2. 样式  -->
    <style>
      html,
      body,
      #viewDiv {
        padding: 0;
        margin: 0;
        height: 100%;
        width: 100%;
      }
    </style>
    <!-- 3.引入样式和js  -->
	<link rel="stylesheet" href="http://localhost:8080/arcgis_js_api/4.15/esri/themes/light/main.css">
	<script src="http://localhost:8080/arcgis_js_api/4.15/init.js"></script>

    <script>
      /**
       * 自定义底图
       *  根据 地图服务的不同使用不同的API 
       * 目前主要区分为,切片服务用:MapImageLayer; 动态服务用:MapImageLayer
       */
	    // 4. 引入 所需要的模块 
      require(["esri/config","esri/Map", "esri/views/MapView","esri/Basemap","esri/layers/TileLayer","esri/layers/MapImageLayer"], 
        function (esriConfig,Map, MapView,Basemap,TileLayer,MapImageLayer) {
        //esriConfig.apiKey = "AAPKa0dae5e7bc9e46e1932bea30bc8cf4d5sM5hEtslf394lsn08UY8tKU0SHAXvQEQFHRzId2BwDGf4QQZpsu6Qlk_MciVQRNC";
        // 自定义底图服务(切片服务使用TileLayer 的API)
        var basemap = new Basemap({
          baseLayers: [
            new TileLayer({
              url: "http://cache1.arcgisonline.cn/arcgis/rest/services/ChinaOnlineCommunity/MapServer",
              title: "Basemap"
            })
          ],
          title: "basemap",
          id: "basemap"
        });
        /*
          http://cache1.arcgisonline.cn/arcgis/rest/services/ChinaOnlineCommunity/MapServer
          该地图服务存在 切片说明,所以为切片服务,故需要用 TileLayer来定义,如果使用MapImageLayer,则地图实例化会出现问题
         */ 
        // var basemap = new Basemap({
        //   baseLayers: [
        //     new MapImageLayer({
        //       url: "http://cache1.arcgisonline.cn/arcgis/rest/services/ChinaOnlineCommunity/MapServer",
        //       title: "Basemap"
        //     })
        //   ],
        //   title: "basemap",
        //   id: "basemap"
        // });

        var map = new Map({
          basemap: basemap
          //,ground: "world-elevation" //属性,添加后可有看到地形起伏
        });

        var view = new MapView({
          map: map,
          center: [117.2649120808,31.9344120986], // Longitude, latitude
          zoom: 13, // Zoom level
          container: "viewDiv" // Div element
        }); 
          
      });
    </script>
  </head>
  <body>
       <!-- 1.定义化地图 容器 -->
    <div id="viewDiv"></div>
  </body>
</html>

3.x 指定 底图

<!DOCTYPE html>
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <meta name="viewport" content="initial-scale=1, maximum-scale=1,user-scalable=no"/>
    <title>3.x版本 地图deom</title>
     
      <!--2. 样式  -->
    <style>
      html, body, #map {
        height: 100%;
        margin: 0;
        padding: 0;
      }
     </style>
     <!-- 3.引入样式和js  -->
     <link rel="stylesheet" href="http://localhost:8080/arcgis_js_api/3.28/esri/css/esri.css">
    <script src="http://localhost:8080/arcgis_js_api/3.28/init.js"></script>
      <!-- 4. 引入 所需要的模块 -->
    <script>
      var map;
      require(["esri/map","esri/basemaps", "dojo/domReady!"], function(Map,esriBasemaps) {
       esriBasemaps.delorme = {
            baseMapLayers: [
                //中国矢量地图服务
                { url: "http://cache1.arcgisonline.cn/arcgis/rest/services/ChinaOnlineCommunity/MapServer" }
            ],
            title: "矢量图"
        };
        map = new Map("map", {
            basemap: "delorme",
            center: [103.847, 36.0473],
            zoom: 5,
            logo:false
        });
      });
    </script>
  </head>

  <body>
      <!-- 1.定义化地图 容器 -->
    <div id="map" ></div>

  </body>
</html>

4.3 底图切换(一般用于影像图和地形图之间的切换)

主要通过:小部件 BasemapToggle来实现

常见分为:矢量图 影像图 地形图

https://www.cnblogs.com/HandyLi/p/11137367.htmlopen in new window

https://www.cnblogs.com/amadoGrowers/p/13631127.htmlopen in new window

//==================# 3.x 底图切换 #==================
 map = new Map("map", {
     basemap: "satellite",   // 官网提供了 17种 供选中,常用 satellite (影像图) 和 osm、topo(地形图、矢量图)
     center: [117.2649120808,31.9344120986], // longitude, latitude
     zoom: 13,
     logo: false //去除 logo
 });
//  6.
var toggle = new BasemapToggle({
    map: map,
    basemap: "topo"
}, "BasemapToggle");
toggle.startup();
/// 方法 二:通过 BasemapToggle 小部件,实现底图切换
// require(["esri/basemaps"], function(esriBasemaps) { /* code goes here */ });
 map = new Map("mapDiv",{
            basemap:"satellite",// 影像图
            spatialReference:{"wkid":4490},
            center: center,
            maxZoom:20,
            minZoom:3,
            logo:false,
            zoom: map_zoom,
            lider:false
        });
    // 自定义图层 添加 中国地形 矢量图 (esri/basemaps)
    esriBasemaps.delorme = {
        baseMapLayers: [
            //中国矢量地图服务
            { url: "http://cache1.arcgisonline.cn/arcgis/rest/services/ChinaOnlineCommunity/MapServer" }
        ],
        thumbnailUrl: ctxStatic+"/images/map/topo.jpg",//缩略图
        title: "矢量图"
    };
    var toggle = new BasemapToggle({
        map: map,
        basemap: "delorme"
    }, "BasemapToggle");
    toggle.startup();
//注意: 需要在 添加元素 <div id="BasemapToggle"></div>  定义位置,来显示 切换底图
//方法三:自定义切换
var map,sp;
var serviceLayer;
function changeBaseMap(){
	if(serviceLayer){
		map.removeLayer(serviceLayer);
	}
	if(typess){
		typess = false;
		$("#imgToggle").css("background-image", "url("+ctxStatic+"/images/map/topo.jpg");
		$("#spanToggle").text("平面图");
		serviceLayer = new esri.layers.ArcGISTiledMapServiceLayer("http://services.arcgisonline.com/arcgis/rest/services/World_Imagery/MapServer"); 
	}else{
		typess = true;
		$("#imgToggle").css("background-image", "url("+ctxStatic+"/images/map/satellite.jpg");
		$("#spanToggle").text("卫星图");
		serviceLayer = new esri.layers.ArcGISTiledMapServiceLayer("https://map.geoq.cn/arcgis/rest/services/ChinaOnlineCommunity/MapServer"); 
	}
	map.addLayer(serviceLayer);
}



//==================# 4.x 底图切换 #==================
 var myBasemaplayer = new TileLayer({
        url: "http://cache1.arcgisonline.cn/arcgis/rest/services/ChinaOnlineCommunity/MapServer"
    });
    var myBasemap = new Basemap({
        baseLayers: [myBasemaplayer],
        title: "Custom Basemap",
        id: "myBasemap"
    });
    var webscene = new WebScene({
        basemap: myBasemap,
        ground: "world-elevation"
    });
// 影像图 和 地形图 的切换
var basemapToggle = new BasemapToggle({
    view: view,
    container: "toggleDiv",
    nextBasemap: "osm"//streets
});
view.ui.add(basemapToggle, "bottom-right");

// 方法二
//创建并配置一个basemapGallery
var basemapGallery = new BasemapGallery({
        view: view,
        source: {
          portal: {
            url: "https://www.arcgis.com",
            useVectorBasemaps: true  // Load vector tile basemaps
          }
        }
      });
//在视图上添加basemapGallery配件
 view.ui.add(basemapGallery, "top-right");


4.x 底图切换 BasemapToggle https://blog.csdn.net/biu_bui_biu/article/details/107331691open in new window

BasemapToggle可以在页面上添加一个切换底图的功能配件,切换的basemap通过nextBasemap设置。

//创建一个并配置一个basemapToggle
 var basemapToggle = new BasemapToggle({
        view: view,
        nextBasemap: "satellite"
      });
 //在视图上添加basemaotoggle 配件
 view.ui.add(basemapToggle, "bottom-right");

4.3.Basemap 3.x 案例 底图切换(卫星图,地形图切换)

<!DOCTYPE html>
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <meta name="viewport" content="initial-scale=1, maximum-scale=1,user-scalable=no"/>
    <title>3.x版本 地图deom</title>
     
      <!--2. 样式  -->
    <style>
      html, body, #map {
        height: 100%;
        margin: 0;
        padding: 0;
      }
      /* 定义 BasemapToggle 底图切换按钮位置 */
      #BasemapToggle {  
            position: absolute;  
            right: 20px;  
            top: 20px;  
            z-index: 50;  
        }  
    </style>
     <!-- 3.引入样式和js  -->
     <link rel="stylesheet" href="http://localhost:8080/arcgis_js_api/3.28/esri/css/esri.css">
    <script src="http://localhost:8080/arcgis_js_api/3.28/init.js"></script>
      <!-- 4. 引入 所需要的模块 -->
    <script>
      var map;
      require(["esri/map","esri/dijit/BasemapToggle","esri/basemaps", "dojo/domReady!"], function(Map,BasemapToggle,esriBasemaps) {
          // 5.初始化地图
          // 方法一:
        map = new Map("map", {
          basemap: "satellite",   // 官网提供了 17种 供选中,常用 satellite (影像图) 和 osm、topo(地形图、矢量图)
          center: [117.2649120808,31.9344120986], // longitude, latitude
          zoom: 13,
          logo: false //去除 logo
        });
        //  6.
        var toggle = new BasemapToggle({
            map: map,
            basemap: "topo"
        }, "BasemapToggle");
        toggle.startup();
        // 方法二
        // // 自定义图层 添加 中国地形 矢量图 (esri/basemaps)
        // esriBasemaps.delorme = {
        //     baseMapLayers: [
        //         //中国矢量地图服务
        //         { url: "http://cache1.arcgisonline.cn/arcgis/rest/services/ChinaOnlineCommunity/MapServer" }
        //     ],
        //     thumbnailUrl: 'https://js.arcgis.com/3.15/esri/images/basemap/streets.jpg',//缩略图
        //     title: "矢量图"
        // };
        // var toggle = new BasemapToggle({
        //     map: map,
        //     basemap: "delorme"
        // }, "BasemapToggle");
        // toggle.startup();






      });
    </script>
  </head>

  <body>
      <!-- 1.定义化地图 容器 -->
    <div id="map" >
        <!-- BasemapToggle 底图切换 -->
        <div id="BasemapToggle"></div>

    </div>

  </body>
</html>

4.4.Basemap底图

官网提供的几种底图:https://developers.arcgis.com/javascript/latest/api-reference/esri-Map.html#basemapopen in new window

在下载的arcgis_js_api包中有一个basemaps.js文件(路径为arcgis_js_api\3.17\esri),里面定义了esri提供的全部的basemap

NameTypeSummary
dark-grayopen in new windowObjectThe Dark Gray Canvas basemap is designed to be used as a soothing background map for overlaying and focus attention on other map layers. https://services.arcgisonline.com/ArcGIS/rest/services/Canvas/World_Dark_Gray_Reference/MapServeropen in new window https://services.arcgisonline.com/ArcGIS/rest/services/Canvas/World_Dark_Gray_Base/MapServeropen in new window.
dark-gray-vectoropen in new windowObjectThe [Dark Gray Canvas v2]open in new window vector tile layer provides a detailed basemap for the world featuring a neutral background style with minimal colors, labels, and features.
grayopen in new windowObjectThe Light Gray Canvas basemap is designed to be used as a neutral background map for overlaying and emphasizing other map layers. https://services.arcgisonline.com/ArcGIS/rest/services/Canvas/World_Light_Gray_Reference/MapServeropen in new window https://services.arcgisonline.com/ArcGIS/rest/services/Canvas/World_Light_Gray_Base/MapServeropen in new window.
gray-vectoropen in new windowObjectThe [Light Gray Canvas v2]open in new window vector tile layer provides a detailed basemap for the world featuring a neutral background style with minimal colors, labels, and features.
hybridopen in new windowObjectThe World Imagery with Labels map is a detailed imagery map layer and labels that is designed to be used as a basemap for various maps and applications: https://services.arcgisonline.com/ArcGIS/rest/services/Reference/World_Boundaries_and_Places/MapServeropen in new window https://services.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServeropen in new window.
national-geographicopen in new windowObjectThe National Geographic basemap is designed to be used as a general reference map for informational and educational purposes: https://services.arcgisonline.com/ArcGIS/rest/services/NatGeo_World_Map/MapServeropen in new window.
oceansopen in new windowObjectThe Ocean Basemap is designed to be used as a basemap by marine GIS professionals and as a reference map by anyone interested in ocean data. https://services.arcgisonline.com/arcgis/rest/services/Ocean/World_Ocean_Reference/MapServeropen in new window https://services.arcgisonline.com/arcgis/rest/services/Ocean/World_Ocean_Base/MapServeropen in new window.
osmopen in new windowObjectThe OpenStreetMap is a community map layer that is designed to be used as a basemap for various maps and applications.
satelliteopen in new windowObjectThe World Imagery map is a detailed imagery map layer that is designed to be used as a basemap for various maps and applications: https://services.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServeropen in new window.
streetsopen in new windowObjectThe Streets basemap presents a multiscale street map for the world: https://services.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServeropen in new window.
streets-navigation-vectoropen in new windowObjectThe [World Navigation Map v2]open in new window vector tile layer provides a detailed basemap for the world featuring a custom navigation map style.
streets-night-vectoropen in new windowObjectThe [World Street Map (Night) v2]open in new window vector tile layer provides a detailed basemap for the world featuring a custom "night time" street map style.
streets-relief-vectoropen in new windowObjectThe [World Street Map (with Relief) v2]open in new window vector tile layer provides a detailed basemap for the world featuring a classic Esri street map style designed for use with a relief map.
streets-vectoropen in new windowObjectThe [World Street Map v2]open in new window vector tile layer provides a detailed basemap for the world featuring a classic Esri street map style.
terrainopen in new windowObjectThe Terrain with Labels basemap is designed to be used to overlay and emphasize other thematic map layers. https://services.arcgisonline.com/ArcGIS/rest/services/Reference/World_Reference_Overlay/MapServeropen in new window https://services.arcgisonline.com/ArcGIS/rest/services/World_Terrain_Base/MapServeropen in new window.
topoopen in new windowObjectThe Topographic map includes boundaries, cities, water features, physiographic features, parks, landmarks, transportation, and buildings: https://services.arcgisonline.com/ArcGIS/rest/services/World_Topo_Map/MapServeropen in new window. https://services.arcgisonline.com/arcgis/rest/services/Elevation/World_Hillshade/MapServeropen in new window.
topo-vectoropen in new windowObjectThe [World Topographic Map v2]open in new window vector tile layer provides a detailed basemap for the world featuring a classic Esri topographic map style designed for use with a relief map.
national-geographic
gray
hybrid
oceans
osm
satellite
streets
topo

5. 地图控件(esri/widgets、esri/dijit)

5.1 案例:

<html>
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no" />
    <title>4.x版本 widgets_地图控件</title>
	 <!--2. 样式  -->
    <style>
      html,
      body,
      #viewDiv {
        padding: 0;
        margin: 0;
        height: 100%;
        width: 100%;
      }
      /* 自定义zoom 位置 */
      #zoomWidgets {
        position:absolute;
        top:1%;
        right: 5%;
      }
    </style>
    <!-- 3.引入样式和js  -->
	  <link rel="stylesheet" href="http://localhost:8080/arcgis_js_api/4.15/esri/themes/light/main.css">
	  <script src="http://localhost:8080/arcgis_js_api/4.15/init.js"></script>

    <script>
	    //4. 引入 所需要的模块 
      require(["esri/config","esri/Map", "esri/views/MapView","esri/widgets/Home","esri/widgets/Legend","esri/widgets/ScaleBar","esri/widgets/Zoom"
        ], function (esriConfig,Map, MapView,Home,Legend,ScaleBar,Zoom ) {
        //esriConfig.apiKey = "AAPKa0dae5e7bc9e46e1932bea30bc8cf4d5sM5hEtslf394lsn08UY8tKU0SHAXvQEQFHRzId2BwDGf4QQZpsu6Qlk_MciVQRNC";
        const map = new Map({
          basemap: "satellite", // 官网提供了 17种 供选中,常用 satellite (影像图) 和 osm(地形图、矢量图)
          ground: "world-elevation" //属性,添加后可有看到地形起伏
        });

        const view = new MapView({
          map: map,
          center: [117.2649120808,31.9344120986], // Longitude, latitude
          zoom: 13, // Zoom level
          container: "viewDiv" // Div element
        });
        /**
         * 5.添加控件
         */ 
         view.ui.components = [];/// 清空 控件(主要用于 清空放大缩小zoom控件,同时也可以去掉 底部的logo)
        // 5.1 添加home
        var homeWidget = new Home({
          view: view
        });
        view.ui.add(homeWidget, "top-left");
        // 5.2 添加 图例
        var legend = new Legend({
          view: view
        });
        view.ui.add(legend, "bottom-right");
        // 5.3 添加 比例尺
        var scaleBar = new ScaleBar({
          view: view,
          unit :"metric"// 设置比例尺的 单位  ("non-metric"|"metric"|"dual")
        });
        view.ui.add(scaleBar, {
          position: "bottom-left"
        });
        // 5.4 自定义zoom
        // 5.4.1 利用  view.ui.add 指定 元素位置(相对不怎么灵活,只能设置为地图的四个角 top-right、top-left、bottom-right、bottom-left)
        // var zoom = new Zoom({
        //   view: view
        // });
        // view.ui.add(zoom, "top-right");
        // 5.4.2 通过 创建dom元素,指定css属性实现自定义下控件位置
        //   1) 通过container 属性指定 dom元素,在单独设置 dom元素的样式 
        // var zoom = new Zoom({
        //   view: view,
        //   container:"zoomWidgets"// 通过container 属性指定 dom元素
        // });
        // view.ui.add(zoom);
        //    2) 给Zoom 指定id属性值,在单独设置 dom元素的样式 
        var zoom = new Zoom({
          view: view
        },"zoomWidgets");
        view.ui.add(zoom);
      });
    </script>

  </head>
  <body>
       <!-- 1.定义化地图 容器 -->
    <div id="viewDiv"></div>
    <!-- 自定义 zomm 位置,通过创建dom元素,指定css属性从而实现 -->
    <div id = "zoomWidgets"></div>
  </body>
</html>

5.2 控件添加 位置的两种方式

  • 利用 view.ui.add(homeWidget, "top-left"); 指定位置 (top-right、top-left、bottom-right、bottom-left)
  • 创建dom,设置样式,然后 通过Zoom属性,或者指定container
// 通过 创建dom元素,指定css属性实现自定义下控件位置
//   1 通过container 属性指定 dom元素,在单独设置 dom元素的样式 
// var zoom = new Zoom({
//   view: view,
//   container:"zoomWidgets"// 通过container 属性指定 dom元素
// });
// view.ui.add(zoom);
//   2 给Zoom 指定id属性值,在单独设置 dom元素的样式 
var zoom = new Zoom({
	view: view
},"zoomWidgets");
view.ui.add(zoom);

<div id = "zoomWidgets"></div>

 /* 自定义zoom 位置 */
 #zoomWidgets {
     position:absolute;
     top:1%;
     right: 5%;
 }

5.3 补充

//去除 logo 和zoom 控件
view.ui.components = [];/// 清空 控件(主要用于 清空放大缩小zoom控件,同时也可以去掉 底部的logo)

//4.x
//地图放大缩小控件
view.ui.remove("zoom");
//地图底部的一串英文,去掉,影响地图美观
view.ui.remove("attribution");
//指南针,用于地图位置复原
//view.ui.remove("compass");
//地图平移和旋转来回切换控件
//view.ui.remove("navigation-toggle");
//["attribution", "navigation-toggle", "compass", "zoom"]
//view.ui.components = [ "zoom","navigation-toggle","compass" ];
//view.ui.padding = { top:1000, left:2650, right:-850, bottom:20 };

// 讲 地图中 的常用小插件,移到  左侧
view.ui.move(['navigation-toggle', "compass"], "top-right");//"bottom-left"  "zoom",

6. 添加服务图层(业务图层)

当前案例区别于 自定义底图(Basemap) ,是将图层 添加到map上,两个图层共存的

  • 切片服务 (TileLayer)

  • 动态服务(需要用MapImageLayer )

  • 影像图 使用 ImageryLayer

  • 要素服务 使用 FeatureLayer

  • 地形 使用 ElevationLayer

  • 要素服务: FeatureLayer

案例:

<html>
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no" />
    <title>layer_4.x版本 地图deom</title>
	 <!--2. 样式  -->
    <style>
      html,
      body,
      #viewDiv {
        padding: 0;
        margin: 0;
        height: 100%;
        width: 100%;
      }
    </style>
    <!-- 3.引入样式和js  -->
	<link rel="stylesheet" href="http://localhost:8080/arcgis_js_api/4.15/esri/themes/light/main.css">
	<script src="http://localhost:8080/arcgis_js_api/4.15/init.js"></script>
    <script>
      /**
       * 自定义底图
       *  根据 地图服务的不同使用不同的API 
       * 目前主要区分为,切片服务用:MapImageLayer; 动态服务用:MapImageLayer
       */
	    // 4. 引入 所需要的模块 
      require(["esri/config","esri/Map", "esri/views/MapView","esri/layers/TileLayer","esri/layers/FeatureLayer"], 
        function (esriConfig,Map, MapView,TileLayer,FeatureLayer) {
        // 5.初始化地图 底图用官网提供的 osm  中国地形图
        var map = new Map({
          basemap: "osm"
          //,ground: "world-elevation" //属性,添加后可有看到地形起伏
        });
        var view = new MapView({
          map: map,
          center: [117.2649120808,31.9344120986], // Longitude, latitude
          zoom: 5, // Zoom level
          container: "viewDiv" // Div element
        });
        // 6. 添加 切片服务 http://map.geoq.cn/arcgis/rest/services/ChinaOnlineStreetPurplishBlue/MapServer
        var tileLayer = new TileLayer({
          url: "http://map.geoq.cn/arcgis/rest/services/ChinaOnlineStreetPurplishBlue/MapServer"
        });
        map.add(tileLayer);
        // 7. 添加 要素图层 http://www.arcgisonline.cn/server/rest/services/Hosted/XZQH/FeatureServer  该服务 总共提供了3种类别,0表示省级行政区域规划,1表示市级 2表示县级行政区域规划
        var featureLayer = new FeatureLayer({
          url: "http://www.arcgisonline.cn/server/rest/services/Hosted/XZQH/FeatureServer/0" //省级行政区域规划
        });
        map.add(featureLayer);
      });
    </script>
  </head>
  <body>
       <!-- 1.定义化地图 容器 -->
    <div id="viewDiv"></div>
  </body>
</html>

7. 绘制点、线、面

  • esri/widgets下有个 小工具中有个 Sketch控件,将 Sketch添加到 GraphicsLayer图形里面
<html>
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no" />
    <title>绘制点线面_4.x版本 地图deom</title>
	 <!--2. 样式  -->
    <style>
      html,
      body,
      #viewDiv {
        padding: 0;
        margin: 0;
        height: 100%;
        width: 100%;
      }
    </style>
    <!-- 3.引入样式和js  -->
	<link rel="stylesheet" href="http://localhost:8080/arcgis_js_api/4.15/esri/themes/light/main.css">
	<script src="http://localhost:8080/arcgis_js_api/4.15/init.js"></script>

    <script>
      /**
       * 自定义底图
       *  根据 地图服务的不同使用不同的API 
       * 目前主要区分为,切片服务用:MapImageLayer; 动态服务用:MapImageLayer
       */
	    // 4. 引入 所需要的模块 
      require(["esri/config","esri/Map", "esri/views/MapView","esri/layers/TileLayer","esri/layers/FeatureLayer","esri/layers/MapImageLayer","esri/layers/GraphicsLayer","esri/widgets/Sketch"], 
        function (esriConfig,Map, MapView,TileLayer,FeatureLayer,MapImageLayer,GraphicsLayer,Sketch) {
        // 5.初始化地图 底图用官网提供的 osm  中国地形图
        var map = new Map({
          basemap: "satellite"
          //,ground: "world-elevation" //属性,添加后可有看到地形起伏
        });
        var view = new MapView({
          map: map,
          center: [117.2649120808,31.9344120986], // Longitude, latitude
          zoom: 5, // Zoom level
          container: "viewDiv" // Div element
        });
        var graphicsLayer = new GraphicsLayer();
        map.add(graphicsLayer);// 注意图层 是加载到 map对象中,而不是view
        var sketch = new Sketch({
          layer: graphicsLayer,
          view: view
        });

        view.ui.add(sketch, "top-right");

      });
    </script>
  </head>
  <body>
       <!-- 1.定义化地图 容器 -->
    <div id="viewDiv"></div>
  </body>
</html>
  • esri/views/draw/Draw

8. 添加点,线,面 (重要) 待完善

图形的构成由 图形(geometry) 和 样式 符号(symbol)来组合的(其他属性:attrubutes和info template.)

8.1 说明:

图形构造需要 分4步:

  • 定义 geometry : 点 对应的 type: "point" 线 对应的 type: "polyline" ;面 type: "polygon"
  • 定义 符号(symbol) : 点 对应的 type: "simple-marker" 线 对应的 type: "simple-line" ;面 type: "simple-fill"
  • 实例化 图形 (Graphic )
  • 将图形 添加到 地图中 view.graphics.add(pointGraphic);
var polylineGraphic = new Graphic({
  // 这里是图形
  geometry: polyline,
  // 这里是样式
  symbol: polylineSymbol,
  // 这个是属性 对象是一个json 是用来保存这个几何数据的
  attributes: {  }
});
// 4.将几何添加到地图中( 几何是无法直接添加到地图中的,先将几何添加到layer中  然后将layer添加到map里)
var layer = new GraphcisLayer( { id: "唯一名称" } )
// 将几何添加到图层中
layer.add( graphic );
// 将图层添加到地图中
view.map.add( layer );

// 几何删除自己
graphic.layer.remove(graphic);
// 图层删除自己
view.map.remove(layer);
// 图层查询自己
view.map.findLayerById(id);
  • 3.x ========================待完善
var gysGraphicsLayer=new GraphicsLayer({
        id:"gysGraphicsLayer",
        visible:true,
        className:'ceshi'
    });
    map.addLayer(gysGraphicsLayer);


//1.添加点
var point = new Point(Number(item.longitude),Number(item.latitude),sp);//sp最好空着,如果使用
var markerSymbol = new SimpleMarkerSymbol(SimpleMarkerSymbol.STYLE_CIRCLE, 18, // 点的大小
    new SimpleLineSymbol(SimpleLineSymbol.STYLE_SOLID, new Color([242, 8, 8]), 2),// 外圈线的颜色和大小
    new Color([158.184,71,0.85]) // 点的颜色
    );
var pointAttributes = {name:item.supplierName,id:item.id , longitude:item.longitude,latitude:item.latitude};
var pointInfoTemplate = new InfoTemplate ("Geocoding Results");
var pointGraphic = new Graphic(point,markerSymbol,pointAttributes).setInfoTemplate (pointInfoTemplate);
map.graphics.add (pointGraphic);// 添加到地图中

//2. 添加 图片
var suppliersMarkerSymbol  =	{
    url: ctxStatic+"/map/arcgis3.x/images/ionic_001.png", // url
    w:20,h:20
};


var point = new Point(Number(item.longitude),Number(item.latitude),sp);//sp最好空着,如果使用
var pointAttributes = {name:item.supplierName,id:item.id , longitude:item.longitude,latitude:item.latitude};
var pointInfoTemplate = new InfoTemplate (item.supplierName);
var pointGraphic = new Graphic(point,pictureMarkerSymbol,pointAttributes).setInfoTemplate (pointInfoTemplate);
gysGraphicsLayer.add(pointGraphic);// 添加到图层中,比上面好处在于,能快速实现对 同类型下的 图形 控制(显示,隐藏)





///=========符号汇总(待完善)=======/////
//定义线符号
var lineSymbol=new SimpleLineSymbol(SimpleLineSymbol.STYLE_DASH, new Color([255, 0, 0]), 3);
//定义点符号l
var pSymbol=new SimpleMarkerSymbol(SimpleMarkerSymbol.STYLE_CIRCLE,10, lineSymbol, new Color([255, 0, 0]));
//定义面符号
var fill=SimpleFillSymbol(SimpleFillSymbol.STYLE_SOLID, lineSymbol,  new Color([255, 0, 0]));



// 添加线
var startPoint = new Point(parseFloat(item.longGps),parseFloat(item.latGps),sp);
var endPoint = new Point(parseFloat(item.nowLongGps),parseFloat(item.nowLatGps),sp);
var path = [];
path.push(startPoint);
path.push(endPoint);
var pline = new Polyline(sp);
pline.addPath(path);
var tempPolyline = new Graphic(pline,new SimpleLineSymbol(SimpleLineSymbol.STYLE_SOLID,"#BFEFFF",1));
mapFilter50Marker.push(tempPolyline);

8.2 添加点

///1 定义 geometry
var point = {
    type: "point",// 添加类型 point
    longitude: 117.2649120808,
    latitude: 31.9344120986
};
///2 定义 符号(symbol)
var markerSymbol = {
    type: "simple-marker", 
    color: [226, 119, 40],
    outline: { // 边线配置 [255, 255, 255] 的边框 宽度2
        color: [255, 255, 255],
        width: 2
    }
};
// 3 实例化 图形 (Graphic )
var pointGraphic = new Graphic({
    geometry: point,
    symbol: markerSymbol
});
// 4 将图形 添加到 地图中
view.graphics.add(pointGraphic);// 将 当前点 添加到 地图中
//addMany支持 传递 数组 一次可以实例化 多个图形
//view.graphics.addMany([pointGraphic, pointGraphic2]);

8.3 添加线

///7.1 定义 geometry
var polyline = {
    type: "polyline", 
    paths: [[118.2659120808,31.9344120986], [117.4659120808,31.9345120986], [117.2559120808,32.9344120986]]
};
//7.2 定义 符号(symbol)
var lineSymbol = {
    type: "simple-line", // autocasts as SimpleLineSymbol()
    color: [226, 119, 40],
    width: 4
};
// 7.3 定义属性,attrubutes
var lineAtt = {
    Name: "Keystone Pipeline",
    Owner: "TransCanada",
    Length: "3,456 km"
};
// 7.4 实例化 图形 (Graphic )
var polylineGraphic = new Graphic({
    geometry: polyline,
    symbol: lineSymbol,
    attributes: lineAtt,
    popupTemplate: { /// 定义弹窗
        title: "{Name}",
        content: [
            {
                type: "fields",
                fieldInfos: [
                    {
                        fieldName: "Name"
                    },
                    {
                        fieldName: "Owner"
                    },
                    {
                        fieldName: "Length"
                    }
                ]
            }
        ]
    }
});
// 7.5 将图形 添加到 地图中
view.graphics.add(polylineGraphic);// 将 当前点 添加到 地图中

8.4 添加面

面:rings 收尾相连,形成一个闭环

 /// 8.1 定义 geometry
var polygon = {
    type: "polygon", // autocasts as new Polygon()
    rings: [
        [119.2659120808,31.9344120986], [119.2659120808,33.9344120986], [117.2559120808,32.9344120986],[119.2659120808,31.9344120986]
    ]
};

//8.2 定义 符号(symbol)
var fillSymbol = {
    type: "simple-fill", 
    color: [227, 139, 79, 0.8],
    outline: {
        color: [255, 255, 255],
        width: 1
    }
};

// 8.3 实例化 图形 (Graphic )
var polygonGraphic = new Graphic({
    geometry: polygon,
    symbol: fillSymbol
});
// 8.4 将图形 添加到 地图中
view.graphics.add(polygonGraphic);// 将 当前点 添加到 地图中
//view.graphics.addMany([pointGraphic, polylineGraphic, polygonGraphic]);

8.5 弹窗

8.6 案例 (添加点\线\面)

<html>
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no" />
    <title>添加点线面_4.x版本 地图deom</title>
	 <!--2. 样式  -->
    <style>
      html,
      body,
      #viewDiv {
        padding: 0;
        margin: 0;
        height: 100%;
        width: 100%;
      }
    </style>
    <!-- 3.引入样式和js  -->
	<link rel="stylesheet" href="http://localhost:8080/arcgis_js_api/4.15/esri/themes/light/main.css">
	<script src="http://localhost:8080/arcgis_js_api/4.15/init.js"></script>

    <script>
	    // 4. 引入 所需要的模块 
      require(["esri/config","esri/Map", "esri/views/MapView","esri/layers/FeatureLayer","esri/layers/GraphicsLayer","esri/Graphic"], 
        function (esriConfig,Map, MapView,FeatureLayer,GraphicsLayer,Graphic) {
        // 5.初始化地图 底图用官网提供的 osm  中国地形图
        var map = new Map({
          basemap: "satellite"//osm  satellite
          //,ground: "world-elevation" //属性,添加后可有看到地形起伏
        });
        var view = new MapView({
          map: map,
          center: [117.2649120808,31.9344120986], // Longitude, latitude
          zoom: 8, // Zoom level
          container: "viewDiv" // Div element
        });
        // 6. 添加点(point)
        ///6.1 定义 geometry
        var point = {
          type: "point",// 添加类型 point
          longitude: 117.2649120808,
          latitude: 31.9344120986
        };
        ///6.2 定义 符号(symbol)
        var markerSymbol = {
          type: "simple-marker", 
          color: [226, 119, 40],
          outline: { // 边线配置 [255, 255, 255] 的边框 宽度2
            color: [255, 255, 255],
            width: 2
          }
        };
        // 6.3 实例化 图形 (Graphic )
        var pointGraphic = new Graphic({
          geometry: point,
          symbol: markerSymbol
        });
        // 6.4 将图形 添加到 地图中
        view.graphics.add(pointGraphic);// 将 当前点 添加到 地图中
        //addMany支持 传递 数组 一次可以实例化 多个图形
        //view.graphics.addMany([pointGraphic, pointGraphic2]);

        // 7.添加 线(polyline)
        ///7.1 定义 geometry
        var polyline = {
          type: "polyline", 
          paths: [[118.2659120808,31.9344120986], [117.4659120808,31.9345120986], [117.2559120808,32.9344120986]]
        };
        //7.2 定义 符号(symbol)
        var lineSymbol = {
          type: "simple-line", // autocasts as SimpleLineSymbol()
          color: [226, 119, 40],
          width: 4
        };
        // 7.3 定义属性,attrubutes
        var lineAtt = {
          Name: "Keystone Pipeline",
          Owner: "TransCanada",
          Length: "3,456 km"
        };
        // 7.4 实例化 图形 (Graphic )
        var polylineGraphic = new Graphic({
          geometry: polyline,
          symbol: lineSymbol,
          attributes: lineAtt,
          popupTemplate: {
            title: "{Name}",
            content: [
              {
                type: "fields",
                fieldInfos: [
                  {
                    fieldName: "Name"
                  },
                  {
                    fieldName: "Owner"
                  },
                  {
                    fieldName: "Length"
                  }
                ]
              }
            ]
          }
        });
         // 7.5 将图形 添加到 地图中
         view.graphics.add(polylineGraphic);// 将 当前点 添加到 地图中

         // 8. 添加 面
         /// 8.1 定义 geometry
         var polygon = {
          type: "polygon", // autocasts as new Polygon()
          rings: [[119.2659120808,31.9344120986], [119.2659120808,33.9344120986], [117.2559120808,32.9344120986],[119.2659120808,31.9344120986]]
        };

        //8.2 定义 符号(symbol)
        var fillSymbol = {
          type: "simple-fill", // autocasts as new SimpleFillSymbol()
          color: [227, 139, 79, 0.8],
          outline: {
            // autocasts as new SimpleLineSymbol()
            color: [255, 255, 255],
            width: 1
          }
        };

        // 8.3 实例化 图形 (Graphic )
        var polygonGraphic = new Graphic({
          geometry: polygon,
          symbol: fillSymbol
        });
        // 8.4 将图形 添加到 地图中
        view.graphics.add(polygonGraphic);// 将 当前点 添加到 地图中
        //view.graphics.addMany([pointGraphic, polylineGraphic, polygonGraphic]);
      });
    </script>
  </head>
  <body>
       <!-- 1.定义化地图 容器 -->
    <div id="viewDiv"></div>
  </body>
</html>

9.空间查询&属性查询

https://blog.csdn.net/yangbolg/article/details/52197908open in new window

https://blog.csdn.net/KK_bluebule/article/details/82222650open in new window

https://blog.csdn.net/weixin_40184249/article/details/80949351open in new window

arcgis js api 有三种常见的查询:QueryTask、FindTask、IdentifyTask

三者的区别:

FIndTask 只能进行属性查询,QueryTask和IdentityTask既可以进行属性查询也可以进行空间查询 对于QueryTask,IdentityTask两个类,QueryTask只可应用于一个单独的图层,IdentityTask可应用于地图服务和多个图层 QueryTask可以进行简单的统计功能。

20210407233916
20210407233916

https://developers.arcgis.com/javascript/latest/sample-code/sandbox/index.html?sample=featurelayerview-queryopen in new window

https://wenku.baidu.com/view/6ed51d34f042336c1eb91a37f111f18582d00c15.htmlopen in new window

https://blog.csdn.net/qq_35732147/article/details/79895145open in new window

https://blog.csdn.net/weixin_30826095/article/details/98809689open in new window

https://blog.csdn.net/weixin_40184249/article/details/80949351open in new window


10 符号化 renderer

第一张图是图形的默认样式,通过renderer 定义属性,从而统一对图形进行渲染,效果如第二张图片

<html>
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no" />
    <title>渲染器_4.x版本 地图deom</title>
	 <!--2. 样式  -->
    <style>
      html,
      body,
      #viewDiv {
        padding: 0;
        margin: 0;
        height: 100%;
        width: 100%;
      }
    </style>
    <!-- 3.引入样式和js  -->
	<link rel="stylesheet" href="http://localhost:8080/arcgis_js_api/4.15/esri/themes/light/main.css">
	<script src="http://localhost:8080/arcgis_js_api/4.15/init.js"></script>

    <script>
	    // 4. 引入 所需要的模块 
      require(["esri/config","esri/Map", "esri/views/MapView","esri/layers/FeatureLayer","esri/layers/GraphicsLayer","esri/Graphic"], 
        function (esriConfig,Map, MapView,FeatureLayer,GraphicsLayer,Graphic) {
        // 5.初始化地图 底图用官网提供的 osm  中国地形图
        var map = new Map({
          basemap: "osm"//osm  satellite
          //,ground: "world-elevation" //属性,添加后可有看到地形起伏
        });
        var view = new MapView({
          map: map,
          center: [117.2649120808,31.9344120986], // Longitude, latitude
          zoom: 5, // Zoom level
          container: "viewDiv" // Div element
        });
        // 6.添加 要素图层,并且 通过自定义渲染器 来对 要素图层中的对象 进行重新渲染
        // var layer=new FeatureLayer({
        //   url:"http://www.arcgisonline.cn/server/rest/services/Hosted/pointData/FeatureServer",
        //   //6.1 创建 layer 时 作为属性添加进来
        //   renderer :{
        //     type: "simple",  
        //     symbol: {
        //       type: "simple-marker", 
        //       size: 6,
        //       color: "black",
        //       outline: { 
        //         width: 0.5,
        //         color: "white"
        //       }
        //     }
        //   }
        // });
        // map.add(layer);

        // 6.2 通过 layer.renderer 进行赋值
        // var layer=new FeatureLayer({
        //   url:"http://www.arcgisonline.cn/server/rest/services/Hosted/pointData/FeatureServer"
        // });
        // layer.renderer = {
        //   type: "simple", 
        //   symbol: {
        //     type: "simple-marker", 
        //     size: 6,
        //     color: "black",
        //     outline: {  
        //       width: 0.5,
        //       color: "white"
        //     }
        //   }
        // };
        // map.add(layer);
        // 6.3 通过官网提供的2D样式 https://developers.arcgis.com/javascript/latest/esri-web-style-symbols-2d/
        // var renderer = {
        //   type: "simple", // autocasts as new SimpleRenderer()
        //   symbol: {
        //     type: "web-style", // autocasts as new WebStyleSymbol()
        //     name: "tear-pin-2",
        //     styleName: "Esri2DPointSymbolsStyle"
        //   },
        //   label: "tree"
        // };
        // var layer=new FeatureLayer({
        //   url:"http://www.arcgisonline.cn/server/rest/services/Hosted/pointData/FeatureServer",
        //   renderer: renderer
        // });
        // map.add(layer);
        // 6.4 利用图片 进行渲染
        var renderer = {
          type: "simple",
          symbol: {
            type: "picture-marker",  // autocasts as new PictureMarkerSymbol()
            url: "https://static.arcgis.com/images/Symbols/Shapes/BlackStarLargeB.png",
            width: "12px",
            height: "12px"
          }
        };
        var layer=new FeatureLayer({
          url:"http://www.arcgisonline.cn/server/rest/services/Hosted/pointData/FeatureServer",
          renderer: renderer
        });
        map.add(layer);


      });
    </script>
  </head>
  <body>
       <!-- 1.定义化地图 容器 -->
    <div id="viewDiv"></div>
  </body>
</html>

11. 实例化二维地图


12. 热力图

[3.x热力图](file:///D:/software/apache-tomcat-8.5.47/webapps/demo/3.x热力2.html)

热力:https://blog.csdn.net/sunlianglong/article/details/79773663open in new window

​ 4.x https://blog.csdn.net/lipiaozeng8359/article/details/109473282open in new window

3D 集成Echarts https://xiaozhuanlan.com/topic/4683297150open in new window

https://github.com/xcsf/ArcGIS-API-for-JS-with-Echartsopen in new window (已经下载,3D集成echats)

https://github.com/dksgis/Echarts3Layer-jsapi4xopen in new window

https://blog.csdn.net/yy284872497/article/details/85228643open in new window

目前官网提供的是 3.x 的渲染,可以实现 热力。4.x目前不支持,需要自己实现

3D 热力目前实现的3种办法:

​ 1.Echarts3Layer 实现,利用 坐标。

​ 2.HeatMap实现,需要用屏幕坐标,所以需要每次移动位置都需要重新 讲每个坐标点转换,效率低,浏览器压力大

​ 3.canvas在三维地图实现热力图

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no">
    <title>热力图</title>
    <link rel="stylesheet" type="text/css"
          href="http://localhost:8080/arcgis_js_api/3.28/dijit/themes/tundra/tundra.css"/>
    <link rel="stylesheet" type="text/css" href="http://localhost:8080/arcgis_js_api/3.28/esri/css/esri.css"/>
    <script type="text/javascript" src="http://localhost:8080/arcgis_js_api/3.28/init.js"></script>
    <style>
        html, body, #map {
            width: 100%;
            height: 100%;
            margin: 0;
            padding: 0;
        }
    </style>
    <script>
        var map;
        var featureLayer;
        require([
                "esri/map",
                "esri/layers/FeatureLayer",
                "esri/renderers/HeatmapRenderer",
                "esri/symbols/SimpleMarkerSymbol",
                "esri/symbols/SimpleLineSymbol",
                "esri/symbols/SimpleFillSymbol",
                "esri/Color"],
            function (Map, FeatureLayer, HeatmapRenderer, SimpleMarkerSymbol, SimpleLineSymbol, SimpleFillSymbol, Color) {
                map = new Map("map", {
                    basemap: "osm",
                    center: [106, 29],
                    zoom: 8
                });
                var geodata = [
                    {value: 800, pnt: [106, 29]},
                    {name: '酉阳县', value: 32, pnt: [108.8196, 28.8666]},
                    {name: '奉节县', value: 232, pnt: [109.3909, 30.9265]},
                    {name: '巫溪县', value: 354, pnt: [109.3359, 31.4813]},
                    {name: '开县', value: 87, pnt: [108.4131, 31.2561]},
                    {name: '彭水县', value: 87, pnt: [108.2043, 29.3994]},
                    {name: '云阳县', value: 364, pnt: [108.8306, 31.0089]},
                    {name: '万州区', value: 164, pnt: [108.3911, 30.6958]},
                    {name: '城口县', value: 61, pnt: [108.7756, 31.9098]},
                    {name: '江津区', value: 12, pnt: [106.2158, 28.9874]},
                    {name: '石柱县', value: 52, pnt: [108.2813, 30.1025]},
                    {name: '巫山县', value: 43, pnt: [109.8853, 31.1188]},
                    {name: '涪陵区', value: 94, pnt: [107.3364, 29.6796]},
                    {name: '丰都县', value: 57, pnt: [107.8418, 29.9048]},
                    {name: '武隆县', value: 124, pnt: [107.655, 29.35]},
                    {name: '南川区', value: 157, pnt: [107.1716, 29.1302]},
                    {name: '秀山县', value: 18, pnt: [109.0173, 28.5205]},
                    {name: '黔江区', value: 67, pnt: [108.7207, 29.4708]},
                    {name: '合川区', value: 84, pnt: [106.3257, 30.108]},
                    {name: '綦江县', value: 147, pnt: [106.6553, 28.8171]},
                    {name: '忠县', value: 184, pnt: [107.8967, 30.3223]},
                    {name: '梁平县', value: 214, pnt: [107.7429, 30.6519]},
                    {name: '巴南区', value: 244, pnt: [106.7322, 29.4214]},
                    {name: '潼南县', value: 268, pnt: [105.7764, 30.1135]},
                    {name: '永川区', value: 18, pnt: [105.8643, 29.2566]},
                    {name: '垫江县', value: 48, pnt: [107.4573, 30.2454]},
                    {name: '渝北区', value: 85, pnt: [106.7212, 29.8499]},
                    {name: '长寿区', value: 35, pnt: [107.1606, 29.9762]},
                    {name: '大足县', value: 249, pnt: [105.7544, 29.6136]},
                    {name: '铜梁县', value: 154, pnt: [106.0291, 29.8059]},
                    {name: '荣昌县', value: 257, pnt: [105.5127, 29.4708]},
                    {name: '璧山县', value: 95, pnt: [106.2048, 29.5807]},
                    {name: '北碚区', value: 108, pnt: [106.5674, 29.8883]},
                    {name: '万盛区', value: 204, pnt: [106.908, 28.9325]},
                    {name: '南岸区', value: 181, pnt: [106.6663, 29.5367]},
                    {name: '江北区', value: 192, pnt: [106.8311, 29.6191]},
                    {name: '双桥区', value: 50, pnt: [105.7874, 29.4928]},
                    {name: '渝中区', value: 10, pnt: [106.5344, 29.5477]}
                ];
                var features = [];
                var style1 = new SimpleMarkerSymbol(SimpleMarkerSymbol.STYLE_CIRCLE, 10, new SimpleLineSymbol(SimpleLineSymbol.STYLE_SOLID, new Color([255, 0, 0]), 0.5), new Color([0, 0, 255, 1]));

                for (var i = 0; i < geodata.length; i++) {
                    var point = new esri.geometry.Point(geodata[i].pnt[0], geodata[i].pnt[1], new esri.SpatialReference({wkid: 4326}));

                    var graphic = new esri.Graphic(point, style1);
                    graphic.setAttributes({"FID": i, "name": geodata[i].name, "value": geodata[i].value});
                    features.push(graphic);
                }

                var featureSet = new esri.tasks.FeatureSet();
                featureSet.features = features;
                featureSet.geometryType = 'esriGeometryPoint';
                featureSet.fieldAliases = {
                    "FID": "FID",
                    "name": "name",
                    "value": "value"
                };
                featureSet.spatialReference = new esri.SpatialReference({wkid: 4326});
                var layerDefinition = {
                    "objectIdField": "FID",
                    "geometryType": "esriGeometryPoint",
                    "fields": [
                        {
                            "name": "FID",
                            "type": "esriFieldTypeOID",
                            "alias": "FID",
                            "sqlType": "sqlTypeOther"
                        },
                        {
                            "name": "name",
                            "type": "esriFieldTypeInteger",
                            "alias": "name"
                        },
                        {
                            "name": "value",
                            "type": "esriFieldTypeInteger",
                            "alias": "value"
                        }
                    ]
                }

                var featureCollection = {
                    layerDefinition: layerDefinition,
                    featureSet: featureSet
                };
                featureLayer = new FeatureLayer(featureCollection, {
                    mode: FeatureLayer.MODE_SNAPSHOT,
                    outFields: ["name", "value"],
                });
                var heatmapRenderer = new HeatmapRenderer({
                    field: "value",
                    blurRadius: 10,
                    //颜色设置
                    colorStops: [
                        {ratio: 0, color: "rgba(0, 255, 150, 0)"},
                        {ratio: 0.6, color: "rgb(250, 250, 0)"},
                        {ratio: 0.85, color: "rgb(250, 150, 0)"},
                        {ratio: 0.95, color: "rgb(255, 50, 0)"}],
                    maxPixelIntensity: 500,
                    minPixelIntensity: 0
                });
                featureLayer.setRenderer(heatmapRenderer);
                console.log(featureLayer);
                map.addLayer(featureLayer,1);
                console.log(map.getLayer(featureLayer.id));
                var featureHotspotLayer = map.getLayer(featureLayer.id)
                console.log(map.layerIds)
                console.log(map.graphicsLayerIds)
                console.log(map.getLevel())



            });

        function removelayer() {
            featureLayer.hide();
        }

        function add() {
            featureLayer.show();
        }
    </script>
</head>
<body>
<div id="map">
    <button onclick="removelayer()">隐藏</button>
    <button onclick="add()">显示</button>
</div>
</body>
</html>

14.开发案例

14.1 tips提示 (3.x)

图形 获取光标 tips提示,或者单击 图形 显示弹窗 ("dojo/dom", "dojo/dom-construct" "dojo/dom-attr","dojo/dom-style" 可以实现对dom的操作, 实现tips 提示,)

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <meta name="viewport" content="initial-scale=1, maximum-scale=1,user-scalable=no"/>
    <title>Simple Map</title>
    <link rel="stylesheet" type="text/css" href="http://localhost:8080/arcgis_js_api/3.28/dijit/themes/tundra/tundra.css"/>
    <link rel="stylesheet" type="text/css" href="http://localhost:8080/arcgis_js_api/3.28/esri/css/esri.css" />
    <script type="text/javascript" src="http://localhost:8080/arcgis_js_api/3.28/init.js"></script>
    <style>
        html, body, #map {
            height: 100%;
            margin: 0;
            padding: 0;
        }
        body {
            background-color: #FFF;
            overflow: hidden;
            font-family: "Trebuchet MS";
        }
        #text{
            position: absolute;
            z-index: 99;
            background-color: rgb(215, 221, 221,0.84);
            font-size: 12px;
            border: 1px solid rgb(0, 150, 255);
            padding: 0.2em 0.5em;
            border-radius: 5px;
            box-shadow: rgb(119, 119, 119) 0px 0px 0.75em;
            transition: all 0.6s;
        }
    </style>
    <script>
        var cityInfo = [
            {"id":0,"name":"北京","X":116.068276,"Y":39.892225},
            {"id":1,"name":"乌鲁木齐","X":87.575829,"Y":43.782212},
            {"id":2,"name":"拉萨","X":91.162998,"Y":29.71042},
            {"id":3,"name":"西宁","X":101.797303,"Y":36.593642},
            {"id":4,"name":"兰州","X":103.584297,"Y":36.119086},
            {"id":5,"name":"成都","X":104.035508,"Y":30.714179},
            {"id":6,"name":"重庆","X":106.519115,"Y":29.478925},
            {"id":7,"name":"贵阳","X":106.668071,"Y":26.457312},
            {"id":8,"name":"昆明","X":102.726775,"Y":24.969385},
            {"id":9,"name":"银川","X":106.167225,"Y":38.598524},
            {"id":10,"name":"西安","X":108.967128,"Y":34.276112},
            {"id":11,"name":"南宁","X":108.233931,"Y":22.748296},
            {"id":12,"name":"海口","X":110.346181,"Y":19.96992},
            {"id":13,"name":"广州","X":113.226683,"Y":23.18307},
            {"id":14,"name":"长沙","X":112.947928,"Y":28.169916},
            {"id":15,"name":"南昌","X":115.893715,"Y":28.652363},
            {"id":16,"name":"福州","X":119.246768,"Y":26.070765},
            {"id":17,"name":"台北","X":121.503567,"Y":25.008274},
            {"id":18,"name":"杭州","X":120.183046,"Y":30.330584},
            {"id":19,"name":"上海","X":121.449707,"Y":31.253361},
            {"id":20,"name":"武汉","X":114.216597,"Y":30.579253},
            {"id":21,"name":"合肥","X":117.262302,"Y":31.838353},
            {"id":22,"name":"南京","X":118.805692,"Y":32.085022},
            {"id":23,"name":"郑州","X":113.6511,"Y":34.746308},
            {"id":24,"name":"济南","X":117.048331,"Y":36.60841},
            {"id":25,"name":"石家","X":114.478215,"Y":38.033276},
            {"id":26,"name":"太原","X":112.483066,"Y":37.798404},
            {"id":27,"name":"呼和浩特","X":111.842806,"Y":40.895751},
            {"id":28,"name":"天津","X":117.351094,"Y":38.925719},
            {"id":29,"name":"沈阳","X":123.296299,"Y":41.801604},
            {"id":30,"name":"长春","X":125.26142,"Y":43.981984},
            {"id":31,"name":"哈尔","X":126.567138,"Y":45.69381},
            {"id":33,"name":"香港","X":114.093117,"Y":22.427852},
            {"id":34,"name":"澳门","X":113.552482,"Y":22.184495}];

        var map,sr;
        var index = 0,t=0;
        require([               "esri/basemaps",   

                "esri/map",
                "esri/layers/ArcGISDynamicMapServiceLayer",
                "esri/layers/GraphicsLayer",
                "esri/symbols/PictureMarkerSymbol",
                "esri/symbols/SimpleLineSymbol", //简单线符号
                "esri/symbols/SimpleMarkerSymbol",
                "esri/symbols/SimpleFillSymbol",
                "esri/geometry/Circle",
                "esri/geometry/Polyline",
                "esri/graphic",
                "dojo/_base/Color",
                "esri/geometry/Point",
                "dojo/on",
                "dojo/dom",
                "dojo/dom-construct",
                "dojo/dom-attr",
                "dojo/dom-style",
                "dojo/domReady!"],
            function(esriBasemaps, Map,
                     ArcGISDynamicMapServiceLayer,
                     GraphicsLayer,
                     PictureMarkerSymbol,
                     SimpleLineSymbol,
                     SimpleMarkerSymbol,
                     SimpleFillSymbol,
                     Circle,
                     Polyline,
                     Graphic,
                     Color,
                     Point,
                     on,
                     dom,
                     domConstruct,
                     domAttr,
                     domStyle
            ) {
                 // 自定义图层 添加 中国地形 矢量图 (esri/basemaps)
    esriBasemaps.delorme = {
        baseMapLayers: [
            //中国矢量地图服务
            { url: "http://cache1.arcgisonline.cn/arcgis/rest/services/ChinaOnlineCommunity/MapServer" }
        ],
        
        title: "矢量图"
    };
				map = new Map("map", {
					  basemap: "delorme",
					  center: [103.847, 36.0473],
					  zoom: 5,
					  logo:false
					});
                //var tiled = new ArcGISDynamicMapServiceLayer("http://localhost:6080/arcgis/rest/services/firstTest/firstService/MapServer");
                //map.addLayer(tiled, 0);
                sr = map.spatialReference;
                var mapCenter = new Point(103.847, 36.0473, sr);
                map.centerAndZoom(mapCenter);

                var popupLayer = new GraphicsLayer({"id":"popupLayer"});
                map.addLayer(popupLayer, 10);
                map.on("load",function(){
                    addReadPopup(cityInfo);
                });
                function addReadPopup(data){
                    for(var i= 0;i<data.length;i++){
                        var pms = new PictureMarkerSymbol('images/red.png', 14, 16);
                        var pt=new Point(data[i].X,data[i].Y,sr);
                        var graphic = new Graphic(pt, pms, data[i]);
                        popupLayer.add(graphic);
                    }
                }
                popupLayer.on("click",popupLayerClick);
                popupLayer.on("mouse-over",popupLayerOver);
                popupLayer.on("mouse-out",popupLayerOut);
                function popupLayerClick(evt){
                    var graphic = evt.graphic;
                    map.infoWindow.setTitle(graphic.attributes.name);
                    map.infoWindow.setContent(graphic.attributes.name);
                    map.infoWindow.show(graphic.geometry);
                }
                function popupLayerOver(e){
                    map.setMapCursor("pointer");
                    console.log(e.graphic.attributes);
                    var scrPt = map.toScreen(e.graphic.geometry);
                    var textDiv = domConstruct.create("div");
                    domAttr.set(textDiv,{
                        "id":"text"
                    });
                    domStyle.set(textDiv, {
                        "left": scrPt.x+10 + "px",
                        "top": scrPt.y+10 + "px",
                        "position": "absolute",
                        "z-index":99,
                        "background":"rgb(215, 221, 221,0.84)",
                        "font-size":"12px",
                        "border":"1px solid #0096ff",
                        "padding": "0.2em 0.5em",
                        "border-radius": "5px",
                        "box-shadow": "0 0 0.75em #777777"
                    });
                    textDiv.innerHTML ="当前是:"+e.graphic.attributes.name;
                    dom.byId("map").appendChild(textDiv);
                }
                function popupLayerOut(e){
                    map.setMapCursor("default");
                    dom.byId("map").removeChild(dom.byId("text"));
                }

            });
    </script>
</head>

<body>
    <div id="map">
    </div>
</body>
</html>

14.2 案例:js分公司 监造可视化开发-- 创建 分包商

思路:

  • 供应商 下面 承建 工程,根据工程的多少,在地图中画圈,以凸显 其承建的项目的多少。需要用到d3 自定义 比例尺。实现步骤:将所有的供应商下面的项目数量提到一个数组中,然后 定义 比例尺 区间,这样可以定义每个 数量 对应的比例数值
  • 图形实际上是包含 图形+label,但是地图中实际

利用 d3 实现 自定义比例尺 <script type="text/javascript" src="http://d3js.org/d3.v5.min.js">

效果图

//2. 供应商 图层
var supplierGraphicsLayer=new GraphicsLayer({
    id:"supplierGraphicsLayer",
    visible:true,
    className:'供应商图层',
    title:"供应商图层"
});
//将供应商 图层 添加到地图中
map.addLayer(supplierGraphicsLayer,2);

initSupplierMarker = function(data){
        jQuery.each(data, function (index, item) {
            xmSumArr.push(item.xmSum);// 拿到每个 供应商 承建的 工程数量 ,d3自定义 比例尺 用到 
        });
        // 自定义 比例尺  确定 分包商 对应的 图形 大小
        var min = d3.min(xmSumArr);
        var max = d3.max(xmSumArr);
        linear = d3.scale.linear()
            .domain([min, max])
            .range([20, 40]);
        //console.log(linear(18));
        jQuery.each(data, function (index, item) {
            if(!item.latitude || !item.longitude){
                return;
            }
            // 1. 根据 供应商 承接的 项目 多少,决定 在地图中 描点 的大小
            var point = new Point(Number(item.longitude),Number(item.latitude),sp);
            var simpleMarkerSymbol = new SimpleMarkerSymbol(SimpleMarkerSymbol.STYLE_CIRCLE, linear(item.xmSum),
                new SimpleLineSymbol(SimpleLineSymbol.STYLE_SOLID, new Color([63, 66, 244,0.1]), 1),
                new Color([63, 66, 244,0.3])
            );
            var pointGraphic = new Graphic(point,simpleMarkerSymbol);
            supplierGraphicsLayer.add(pointGraphic);
            //2. 供应商  图形
            // 2.1 创建 供应商图形 对象
            var pictureMarkerSymbol =  new PictureMarkerSymbol({
                "url":suppliersMarkerSymbol.url,
                "height":suppliersMarkerSymbol.h,
                "width":suppliersMarkerSymbol.w
                //,"angle": -30,
            });
            var pointAttributes = {name:item.supplierName,id:item.id , longitude:item.longitude,latitude:item.latitude,type:'supplier'};
            var pointInfoTemplate = new InfoTemplate (item.supplierName);
            var pointGraphic = new Graphic(point,pictureMarkerSymbol,pointAttributes).setInfoTemplate (pointInfoTemplate);

            // 2.2 为实现选中 效果,图形对象中保存 默认图形对象的Symbol(符号)和 选中时的符号 记录
            pointGraphic.defaultSymbol = pictureMarkerSymbol;
            pointGraphic.hoverSymbol = new PictureMarkerSymbol(hoverSuppliersMarkerSymbol.url,hoverSuppliersMarkerSymbol.w,hoverSuppliersMarkerSymbol.h);  //(url, width, height)
            //2.3 保存一些 对象的属性
            pointGraphic.type='supplier';
            pointGraphic.id=item.id;
            ///2.3 添加 标题 ,实际上标题和 图形  是一体的 ,不能纯粹的用 图层的显示 和隐藏 来 实现 图例的 切换(初始 想 将 标题 单独 放到nameGraphicsLayer图层,然后通过 hide和show 来实现快速切换,但是不合理)
            var textSymbol = new TextSymbol(item.supplierName,"宋体","white").setOffset(0, -22);
            var lableGraphic = new Graphic(point,textSymbol);
            lableGraphic.visible=false;// 默认隐藏
            lableGraphic.type='supplier_label';
            if ($("#menu3").hasClass('map_button_menu_check')) {// 名称是否选中
                lableGraphic.visible=true;// 显示名称
            }
            pointGraphic.label=lableGraphic;// 将 label 作为  图形的属性 记录下来
            supplierGraphicsLayer.add(pointGraphic);// 添加图形
            supplierGraphicsLayer.add(pointGraphic.label);// 添加 label
        });
        finishSupplierData=true;// 分包商 实例化完成
        checkFinishData(); // 校验是否实例化完成
    }



//  图例控制  

var indexArr = [1,2];
var layerEmum= {
    "1":'persionGraphicsLayer',
    "2":'supplierGraphicsLayer'
}
    addOrRemoveMapPoint = function (index, type) {
        var graphicsLayer = map.getLayer(layerEmum[index]);/// 通过id 取对应 图层
        if (indexArr.indexOf(index) != -1) {
            if(type=='add'){
                graphicsLayer.show();
            }else{
                graphicsLayer.hide();
            }
            // 考虑 图层 中  图形 对应的名称是否 显示
            checkNameMarker([graphicsLayer],type);
        } else if (index == 3) {//名称控制
            var persionGraphicsLayer = map.getLayer('persionGraphicsLayer');
            var supplierGraphicsLayer = map.getLayer('supplierGraphicsLayer');
            checkNameMarker([persionGraphicsLayer,supplierGraphicsLayer],type);// 名称
        }
    }
    /**
     * 5.2 名称 控制
     *  名称的显示要根据 图形 是否 显示(名称和图形 是一起的)
     * @param graphicsLayerArr : 需要添加名称的图形,对应的 图层(数组),目前只有 人员和 供应商 图层
     * @param type:添加还是隐藏
     */
    checkNameMarker=function(graphicsLayerArr,type){
        jQuery.each(graphicsLayerArr, function (index, graphicsLayer) {
            var graphicArr = graphicsLayer.graphics;// 获取该图层中 的 所有图形,返回 Graphic[]
            jQuery.each(graphicArr, function (index, graphic) {// 每个图层对应的  图形对象(现在需要剔出 主对象,供应商或者 人员)
                if(graphic.id){//  说明是 主对象,供应商或者 人员(只有著主对象 才 添加了id属性)
                    var graphicLabel = graphic.label;
                    if ($("#menu3").hasClass('map_button_menu_check')) {// 名称是否选中
                        graphicLabel.show();// 显示名称  (注:graphicLabel.visible等于true,false,不能立刻生效,需要 graphicLabel.draw(); 重新绘图 才能生效 )
                    }else{
                        graphicLabel.hide();// 显示名称
                    }
                }
            });
        });
    }

14.10 自定义弹窗(待整理)

3.x 自定义弹窗

案例场景展示 监造可视化 信息,页面 图形主要有 供应商 和人员 ,特别需求:需要自定义 弹窗信息和样式


14.11 获取行政区域

行政区域规划 的2种形式(存在坐标系不统一问题)

调用百度api https://www.cnblogs.com/milkmap/archive/2012/04/11/2442430.htmlopen in new window

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>获取地区轮廓线</title>
<script type="text/javascript" src="http://api.map.baidu.com/api?v=1.3">
</script>
<style type="text/css">
body{font-size:13px;margin:10px}
#container{width:800px;height:500px;border:1px solid gray}
</style>
</head>
<body>
<div id="container"></div>
<br />
输入省、直辖市或县名称:<input type="text" id="districtName" style="width:80px" value="重庆市">
<input type="button" onclick="getBoundary()" value="获取轮廓线">

<script type="text/javascript">
var map = new BMap.Map("container");
map.centerAndZoom(new BMap.Point(116.403765, 39.914850), 5);
map.addControl(new BMap.NavigationControl({type: BMAP_NAVIGATION_CONTROL_SMALL}));
map.enableScrollWheelZoom();

function getBoundary(){       
    var bdary = new BMap.Boundary();
    var name = document.getElementById("districtName").value;
    bdary.get(name, function(rs){       //获取行政区域
        map.clearOverlays();        //清除地图覆盖物       
        var count = rs.boundaries.length; //行政区域的点有多少个
        for(var i = 0; i < count; i++){
            var ply = new BMap.Polygon(rs.boundaries[i], {strokeWeight: 2, strokeColor: "#ff0000"}); //建立多边形覆盖物
            map.addOverlay(ply);  //添加覆盖物
            map.setViewport(ply.getPath());    //调整视野         
        }                
    });   
}

</script>
</body>
</html>

引入相应的模块,其中包括: dojo/on(用于绑定事件的模块) esri/symbols/SimpleMarkerSymbol(点符号类) esri/symbols/SimpleLineSymbol(线符号类) esri/symbols/SimpleFillSymbol(面符号类) esri/geometry/Point(点类) esri/geometry/Polyline(折线类) esri/geometry/Polygon(面类) esri/geometry/Circle(圆类) dojo/query(dojo的选择器,用于选择DOM元素) esri/graphic(图形类) esri/layers/GraphicsLayer(客户端图层类)

//<script type="text/javascript" src="http://api.map.baidu.com/api?v=1.3">
map.on("load", function () {
    getBoundary('安徽');//行政区域,
});
    // 勾勒边界 描边安徽
    function getBoundary(name){
        var graphic;
        if(BMap){// 通过百度地图 获取省份边界
            var bdary = new BMap.Boundary();
            bdary.get(name, function(rs) {
                points = rs; //获取行政区域
                var rslength = rs.boundaries.length;
                for (i = 0; i < rslength; i++) {
                    var triangleCoords = [];
                    var temp = rs.boundaries[i];
                    console.log(temp)
                    var latLngs = temp.split(";");
                    for (j = 1; j < latLngs.length - 1; j++) {
                        var postion = latLngs[j].indexOf(",");
                        var lat = parseFloat(latLngs[j].substr(0, postion));//经度
                        var lng = parseFloat(latLngs[j].substr(postion + 1));//纬度
                        //加入经纬度
                        triangleCoords.push(new Point(lat,lng));
                    }
                    console.log(triangleCoords)
                    // 创建多边形
                    var geometry = new Polygon();
                    geometry.addRing(triangleCoords);
                    var color = Color.fromHex("#14B3E0");
                    color.a = 0.05;//透明度
                    //定义面符号
                    var fill=SimpleFillSymbol(SimpleFillSymbol.STYLE_SOLID, new SimpleLineSymbol(SimpleLineSymbol.STYLE_SOLID, "#14B3E0",2),color);
                    graphic = new Graphic(geometry, fill,{},null);
                    map.graphics.add(graphic);
                }
            });
        }
    }

14.12 arcgis引入第三方js文件&引入定义的模块

通过 配置dojoConfig,再请求各种需要的第三方js文件

例如:Echarts ,GeoJsonLayer(添加GeoJson数据,一般用于地图描边)等都要引入arcgis 的插件,所有导包不能像引入js的方式

需要注意的是:当需要配置dojoConfig的时候,最好是放在<head>内容里的前面,并且引用的arcgis js api的init.js切忌要放在dojoConfig配置的后面

<script>
        /**
         * 这个配置必须写在加载arcgis api之前,否则不能生效
         * location是一个绝对路径,第一个斜杠前面会默认添加一级域名,所以后面要填上二级域名等等,
         * 比如:http://localhost:8065/index.html,这种只需要写"/js"即可;
         * 而http://localhost:8065/EchartsHeatmapInArcgis/index.html这种就需要写"/../js"或者"/EchartsHeatmapInArcgis/js"
         require里面调用的时候require(["src/.."]即可,或者require(["./src/**.js"]
         */
        var dojoConfig = {
            parseOnLoad: true,
            packages: [{
                "name": "src",
                //"location": location.pathname.replace(/\/[^/]+$/, '') + "/js"
                "location": ctxStatic + "/map/arcgis/js"   /// 和本地引入js一样,先找到路径,定义为src .后面地图引入模块时用"src/xx",
            }]
        };
    </script>
    <!--"src/InfoWindow",  本质是 arcgis 引入 ctxStatic + "/map/arcgis/js/InfoWindow.js"  -->
    <script>
    require([
    "esri/basemaps","esri/map",
    "src/InfoWindow",
    "dojo/domReady!"
], function (esriBasemaps, Map,InfoWindow){


});
    
    
    </script>
    
    

14. 13 arcgis 操作dom 对象

image-20201215102022370
image-20201215102022370
require([
    "esri/basemaps","esri/map",
    "esri/Color", 
    "dojo/on",
    "dojo/dom","dojo/dom-construct","dojo/dom-attr","dojo/dom-style",
    "dojo/domReady!"
], function (esriBasemaps, Map,
             Color,
             on,
             dom,domConstruct,domAttr,domStyle
){
	map = new Map("mapDiv",{
            basemap:"satellite",// 影像图
            spatialReference:{"wkid":4490},
            center: center,
            maxZoom:20,
            minZoom:3,
            logo:false,
            zoom: map_zoom,
            lider:false,
            sliderPosition:"top-right",
            infoWindow : infoWindow
        });
        
        
        
        
     map.graphic.on("mouse-over",popupLayerOver);   
     // 定义图形获取 鼠标 事件 ,实现 tips 提示   
    function popupLayerOver(e){
        map.setMapCursor("pointer");
        // 自定义tips 提示
        var scrPt = map.toScreen(e.graphic.geometry);// 坐标 转 屏幕坐标
        var textDiv = domConstruct.create("div");
        domAttr.set(textDiv,{
            "id":"text"
        });
        // 样式可以迁移到css中同意 定义,这里只用定义 坐标(left和 top)
        domStyle.set(textDiv, {
            "left": scrPt.x+10 + "px",
            "top": scrPt.y+10 + "px",
            "position": "absolute",
            "z-index":99,
            "background":"#fcffd1",
            "font-size":"10px",
            "border":"1px solid #0096ff",
            "padding": "0.1em 0.3em 0.1em",
            "border-radius": "3px",
            "box-shadow": "0 0 0.75em #777777"
        });
        textDiv.innerHTML = e.graphic.attributes.name;
        dom.byId("mapDiv").appendChild(textDiv);
    }
})

14.14 GeoJSON 数据在地图中 创建(主要用于 对区域的描边)

4.x-GeoJSONLayeropen in new window

https://blog.csdn.net/weixin_43747076/article/details/106238416open in new window

3.x -GeoJSONLayer

https://blog.csdn.net/huangli0/article/details/80147212open in new window

​ (说明:3.x 的实现需要 通过 geojsonlayer.js、 terraformer.min.js 、terraformer-arcgis-parser.min.js)

15 开发记录

15.1 图层覆盖

现象:图形定义了事件,但是无法触发。可能就是图层直接的覆盖

**现象描述:**当时做接地线时 现有的图形都是添加在map中,接地线添加在GraphicsLayer ,同时也添加了行政区域规划,并且该行政区域 对于的Polygon(面)

是直接添加到map对象的,所以导致,地图其他图形的单击事件都能生效,但是接地线 图形对于的事件无法生效,因为接地线图形被行政区域规规划遮挡,解决方法是 把 政区域规规划 对于的对象 添加到 GraphicsLayer 中。

注: 需要注意的是利用 GraphicsLayer ,然后自定义事件,如果事件没有生效,则可能是图层顺序的原因导致的,尤其是 Polygon(面),如果直接用map.graphics.add(tempPolyline); 则会使 Polygon存在图层覆盖GraphicsLayer 图层,所以解决的方法是 讲 Polygon 也踢到 GraphicsLayer 图层中,同时将其放到底层,防止覆盖

15.2 自定义图层 中 图层的事件(自定义图层事件)

//利用 GraphicsLayer 图层存储 Graphics,从而 实现快速的 显示,隐藏
var jdxlowGraphicsLayer = new GraphicsLayer({
    id:"jdxlowGraphicsLayer",
    visible:false,
    className:'接地线重叠汇总展开图层',
    title:'接地线重叠汇总展开图层',
    //infoTemplate:true// 禁用 弹窗框
    //,opacity:1
});
map.addLayer(jdxlowGraphicsLayer,2);
// 自定义 事件
jdxHighGraphicsLayer.on("click",popupLayerClick);
jdxHighGraphicsLayer.on("mouse-over",popupLayerOver);
jdxHighGraphicsLayer.on("mouse-out",popupLayerOut);

15.3 光标样式

// 光标 样式
function popupLayerOver(e){
    if(!e.graphic){
        return;
    }
    map.setMapCursor("pointer");
}
// 4.3.3 图形 鼠标移除事件
function popupLayerOut(e){
	map.setMapCursor("default");
}

15.4 定位到点,线、面 (待整理)

15.5 坐标转换

待确定:屏幕坐标 和 toScreen获取的 left、top 应该不是一个概念。

地理坐标系:lontitude latitude 投影坐标系:x y

  • 屏幕坐标和地理坐标之间的转换

    var screenPoint = {x: evt.x,y: evt.y};// 需要定义弹窗的位置 (其中 x:表示 left y:表示top)
    // 3.x 
    var mapPoint = map.toMap(screenPoint);
    // 4.x
    var mapPoint = view.toMap(screenPoint);
    
  • 地理坐标转换屏幕坐标

    /**
    	graphic.geometry 等同于 var mapPoint = view.toMap(screenPoint);中的 mapPoint
    	返回的结果是 屏幕坐标
    	 creenCoordinates.x--->left
      	 creenCoordinates.y--->top
    */
    var creenCoordinates = map.toScreen(graphic.geometry)// 转为屏幕坐标(对应css属性中的left、top)
    
  • 火星坐标,84坐标,百度地图坐标相互转换(js)

//定义一些常量
var x_PI = 3.14159265358979324 * 3000.0 / 180.0;
var PI = 3.1415926535897932384626;
var a = 6378245.0;
var ee = 0.00669342162296594323;

/**
 * 百度坐标系 (BD-09) 与 火星坐标系 (GCJ-02)的转换
 * 即 百度 转 谷歌、高德
 * @param bd_lon
 * @param bd_lat
 * @returns {*[]}
 */
function bd09togcj02(bd_lon, bd_lat) {
    var x_pi = 3.14159265358979324 * 3000.0 / 180.0;
    var x = bd_lon - 0.0065;
    var y = bd_lat - 0.006;
    var z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * x_pi);
    var theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * x_pi);
    var gg_lng = z * Math.cos(theta);
    var gg_lat = z * Math.sin(theta);
    return [gg_lng, gg_lat]
}

/**
 * 火星坐标系 (GCJ-02) 与百度坐标系 (BD-09) 的转换
 * 即谷歌、高德 转 百度
 * @param lng
 * @param lat
 * @returns {*[]}
 */
function gcj02tobd09(lng, lat) {
    var z = Math.sqrt(lng * lng + lat * lat) + 0.00002 * Math.sin(lat * x_PI);
    var theta = Math.atan2(lat, lng) + 0.000003 * Math.cos(lng * x_PI);
    var bd_lng = z * Math.cos(theta) + 0.0065;
    var bd_lat = z * Math.sin(theta) + 0.006;
    return [bd_lng, bd_lat]
}

/**
 * WGS84转GCj02
 * @param lng
 * @param lat
 * @returns {*[]}
 */
function wgs84togcj02(lng, lat) {
    if (out_of_china(lng, lat)) {
        return [lng, lat]
    }
    else {
        var dlat = transformlat(lng - 105.0, lat - 35.0);
        var dlng = transformlng(lng - 105.0, lat - 35.0);
        var radlat = lat / 180.0 * PI;
        var magic = Math.sin(radlat);
        magic = 1 - ee * magic * magic;
        var sqrtmagic = Math.sqrt(magic);
        dlat = (dlat * 180.0) / ((a * (1 - ee)) / (magic * sqrtmagic) * PI);
        dlng = (dlng * 180.0) / (a / sqrtmagic * Math.cos(radlat) * PI);
        var mglat = lat + dlat;
        var mglng = lng + dlng;
        return [mglng, mglat]
    }
}

/**
 * GCJ02 转换为 WGS84
 * @param lng
 * @param lat
 * @returns {*[]}
 */
function gcj02towgs84(lng, lat) {
    if (out_of_china(lng, lat)) {
        return [lng, lat]
    }
    else {
        var dlat = transformlat(lng - 105.0, lat - 35.0);
        var dlng = transformlng(lng - 105.0, lat - 35.0);
        var radlat = lat / 180.0 * PI;
        var magic = Math.sin(radlat);
        magic = 1 - ee * magic * magic;
        var sqrtmagic = Math.sqrt(magic);
        dlat = (dlat * 180.0) / ((a * (1 - ee)) / (magic * sqrtmagic) * PI);
        dlng = (dlng * 180.0) / (a / sqrtmagic * Math.cos(radlat) * PI);
        mglat = lat + dlat;
        mglng = lng + dlng;
        return [lng * 2 - mglng, lat * 2 - mglat]
    }
}

function transformlat(lng, lat) {
    var ret = -100.0 + 2.0 * lng + 3.0 * lat + 0.2 * lat * lat + 0.1 * lng * lat + 0.2 * Math.sqrt(Math.abs(lng));
    ret += (20.0 * Math.sin(6.0 * lng * PI) + 20.0 * Math.sin(2.0 * lng * PI)) * 2.0 / 3.0;
    ret += (20.0 * Math.sin(lat * PI) + 40.0 * Math.sin(lat / 3.0 * PI)) * 2.0 / 3.0;
    ret += (160.0 * Math.sin(lat / 12.0 * PI) + 320 * Math.sin(lat * PI / 30.0)) * 2.0 / 3.0;
    return ret
}

function transformlng(lng, lat) {
    var ret = 300.0 + lng + 2.0 * lat + 0.1 * lng * lng + 0.1 * lng * lat + 0.1 * Math.sqrt(Math.abs(lng));
    ret += (20.0 * Math.sin(6.0 * lng * PI) + 20.0 * Math.sin(2.0 * lng * PI)) * 2.0 / 3.0;
    ret += (20.0 * Math.sin(lng * PI) + 40.0 * Math.sin(lng / 3.0 * PI)) * 2.0 / 3.0;
    ret += (150.0 * Math.sin(lng / 12.0 * PI) + 300.0 * Math.sin(lng / 30.0 * PI)) * 2.0 / 3.0;
    return ret
}

/**
 * 判断是否在国内,不在国内则不做偏移
 * @param lng
 * @param lat
 * @returns {boolean}
 */
function out_of_china(lng, lat) {
    return (lng < 72.004 || lng > 137.8347) || ((lat < 0.8293 || lat > 55.8271) || false);
}

15.6 js计算坐标之间距离

// js 坐标之间距离
function toRad(d) {
    return d * Math.PI / 180;
}
function getDisance(lng1,lat1,lng2 , lat2) { //lat为纬度, lng为经度, 一定不要弄错
    var dis = 0;
    var radLat1 = toRad(lat1);
    var radLat2 = toRad(lat2);
    var deltaLat = radLat1 - radLat2;
    var deltaLng = toRad(lng1) - toRad(lng2);
    var dis = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(deltaLat / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(deltaLng / 2), 2)));
    return dis * 6378137;//WGS1984坐标系:6378137.0;现在80坐标系: 6378140.0 ;北京54坐标系:6378245.0;
}
alert(  getDisance(119.84411419,29.98447129,119.84419419,29.98447129) );

16.7 手动控制 弹窗显示和自定义弹窗位置

map.infoWindow.setTitle(graphic.attributes.name);
map.infoWindow.setContent(graphic.attributes.name);
    if(graphic.geometryType=='point'){
    map.infoWindow.show(graphic.geometry);
}else{
    var mapPoint = map.toMap(e.screenPoint);
    map.infoWindow.show(mapPoint);
}


16.8 设置旋转角度(4.x)

view.goTo({
    /*position: view.camera.position,*/
    center:view.center,
    tilt: val
    }, {
    animate: false
});

16.9 动画加载 定位到中心点 ,初始化 和home用到

// Home
var homeWidget = new Home({
    view: view
});
view.ui.add(homeWidget, "top-right");
homeWidget.on("go", function(event){
    event.target.goToOverride=function(){
        animationGoToCenter();
    }
});
// 动画加载 定位到中心点 ,初始化 和home用到
var animationGoToCenter=function(){
    var cam = new Camera({
        position: new Point({
            x: 116.327348, // lon
            y: 26.4218886,      // lat
            z: 400000   // elevation in meters
        }),
        zoom:8,
        heading: 10, // facing due south
        tilt: 52      // bird's eye view
    });
    view.goTo(cam);
}

说明:

1. 如何在线查看地图服务

image-20210329231520529
image-20210329231520529

2.要素服务

// 6. 添加 切片服务 http://map.geoq.cn/arcgis/rest/services/ChinaOnlineStreetPurplishBlue/MapServer
var tileLayer = new TileLayer({
	url: "http://map.geoq.cn/arcgis/rest/services/ChinaOnlineStreetPurplishBlue/MapServer"
});
map.add(tileLayer);
// 7. 添加 要素图层 http://www.arcgisonline.cn/server/rest/services/Hosted/XZQH/FeatureServer  该服务 总共提供了3种类别,0表示省级行政区域规划,1表示市级 2表示县级行政区域规划
var featureLayer = new FeatureLayer({
	url: "http://www.arcgisonline.cn/server/rest/services/Hosted/XZQH/FeatureServer/0" //省级行政区域规划
});
map.add(featureLayer);

3. 动态服务

4. 注意事项

  • 初始化地图时,出现部分空白
<!--同时按钮区域也乱了,是因为需要 引入js的同时也需要css,目前能确定的是3.28需要 4.x不确定-->
<link rel="stylesheet" href="https://js.arcgis.com/3.28/esri/css/esri.css">
<script src="https://js.arcgis.com/3.28/"></script>
image-20201123084135231
image-20201123084135231
  • argis4.10 有点问题,当 FeatureLayer 中添加 线 时 ,如果 会出现无法选中该对象,同时 线路 可能被遮挡

    elevationInfo: {
        mode: "on-the-ground",
        unit: "meters"
    },
    
  • 4.15 在信息弹窗中无法自定义单击事件

10 常用的地图地址:

高德

高德地图瓦片分析

参考网址:https://blog.csdn.net/fredricen/article/details/77189453open in new window

lang可以通过zh_cn设置中文,en设置英文,size基本无作用,scl设置标注还是底图,scl=1代表注记,scl=2代表底图(矢量或者影像),style设置影像和路网,style=6为影像图,style=7为矢量路网,style=8为影像路网

目前主要有

wprd0 是高德的新版地址,webst0 是老版服务

参数说明:

  • lang 设置 标注文字
    • zh_cn 中文
    • en 英文
  • size基本无作用
  • scl设置标注还是底图
    • scl=1代表注记
    • scl=2代表底图(矢量或者影像)
  • style设置影像和路网
    • style=6为影像图
    • style=7为矢量路网
    • style=8为影像路网
  • ltype 线性控制,增加后,只对地图要素进行控制,没有文字注记,要素多少,是否透明
变量说明
域名(wprd,wpst)目前还没有找出规律
lang可以通过zh_cn设置中文,en设置英文
size基本无作用
style地图类型控制,6卫星(st),7简图(st rd),8详图(不透明rd,透明图st)
scl尺寸控制,1=256,2=512
ltype线性控制,增加后,只对地图要素进行控制,没有文字注记,要素多少,是否透明
http://wprd0{1-4}.is.autonavi.com/appmaptile?x={x}&y={y}&z={z}&lang=zh_cn&size=1&scl=1&style=7 为矢量图(含路网、含注记)
http://wprd0{1-4}.is.autonavi.com/appmaptile?x={x}&y={y}&z={z}&lang=zh_cn&size=1&scl=2&style=7 为矢量图(含路网,不含注记)
http://wprd0{1-4}.is.autonavi.com/appmaptile?x={x}&y={y}&z={z}&lang=zh_cn&size=1&scl=1&style=6 为影像底图(不含路网,不含注记)
http://wprd0{1-4}.is.autonavi.com/appmaptile?x={x}&y={y}&z={z}&lang=zh_cn&size=1&scl=2&style=6 为影像底图(不含路网、不含注记)
http://wprd0{1-4}.is.autonavi.com/appmaptile?x={x}&y={y}&z={z}&lang=zh_cn&size=1&scl=1&style=8 为影像路图(含路网,含注记)
http://wprd0{1-4}.is.autonavi.com/appmaptile?x={x}&y={y}&z={z}&lang=zh_cn&size=1&scl=2&style=8 为影像路网(含路网,不含注记)

二:ArcGIS上对外开放的瓦片地址网站

https://blog.csdn.net/qq_38181949/article/details/103423766open in new window

ChinaOnlineCommunity_Mobile 格式地址:
	https://map.geoq.cn/arcgis/rest/services/ChinaOnlineCommunity_Mobile/MapServer/tile/{z}/{y}/{x}
ChinaOnlineCommunityENG 格式地址:
	https://map.geoq.cn/arcgis/rest/services/ChinaOnlineCommunityENG/MapServer/tile/{z}/{y}/{x}
ChinaOnlineStreetGray 格式地址
	https://map.geoq.cn/arcgis/rest/services/ChinaOnlineStreetGray/MapServer/tile/{z}/{y}/{x}
ChinaOnlineStreetPurplishBlue 格式地址
	https://map.geoq.cn/arcgis/rest/services/ChinaOnlineStreetPurplishBlue/MapServer/tile/{z}/{x}/{y}
ChinaOnlineStreetWarm 格式地址
	https://map.geoq.cn/arcgis/rest/services/ChinaOnlineStreetWarm/MapServer/tile/{z}/{x}/{y}

三:百度地图瓦片地址:

百度个性化地图模板(个性化地图网站点我) 只需要修改customid参数分别为:midnight、light、normal、grassgreen等待。

参数说明 x={x}&y={y}&z={z}均为占位符,需要替换为相应图层的数字如: x=5&y=6&z=7

黄色底图
	http://api0.map.bdimg.com/customimage/tile?&x={x}&y={y}&z={z}&udt=20191205&scale=1&ak=5ieMMexWmzB9jivTq6oCRX9j
夜深色地图,蓝色地图
	http://api0.map.bdimg.com/customimage/tile?&x={x}&y={y}&z={z}&udt=20191205&scale=1&ak=5ieMMexWmzB9jivTq6oCRX9j&customid=midnight