紧接上一篇的基本图层创建,本篇主要通过Graphic和layers/GraphicsLayer创建几何图形。
Graphic类
一个Graphic类包括四个基本的参数:一个geometer,一个symbol,attribute和infoTemplate。
- attributes:属性字段值
- geometry:定义一个几何图形
- infoTemplate:infoWindow中显示的内容
- symbol:图形的样式
- visible:图形的可见性
模块引用
- 在基础图层上添加layers/GraphicsLayer和Graphic类:
- Graphic用于创建图形,Grpaphic只能显示在GraphicsLayer对象中,即在GraphicLayer上监听Graphic对象。
require([
"esri/Map",
"esri/views/MapView",
"esri/Graphic",
"esri/layers/GraphicsLayer"
], function(Map, MapView, Graphic, GraphicsLayer) {}
定义图形(点)
// 点的位置,成都周边
var point = {
type: "point",
longitude: 104,
latitude: 30
};
// 点的样式属性
var simpleMarkerSymbol = {
type: "simple-marker",
color: [226, 119, 40], // orange
outline: {
color: [255, 255, 255], // white
width: 1
}
};
var pointGraphic = new Graphic({
geometry: point,
symbol: simpleMarkerSymbol
});
- 通过Graphic实例创建图形
- 通过GraphicLayer监听Graphic对象。
var graphicsLayer = new GraphicsLayer();
graphicsLayer.add(pointGraphic);
- 接下来就是上图,通过map.add()添加图形:
map.add(graphicsLayer)
完整代码及效果图
require([
"esri/Map",
"esri/views/MapView",
"esri/Graphic",
"esri/layers/GraphicsLayer"
], function(Map, MapView, Graphic, GraphicsLayer) {
var map = new Map({
basemap: "satellite", //light-gray-vector,dark-gray-vector,satellite,streets-relief-vector,和streets-navigation-vector
});
var view = new MapView({
container: "viewDiv",
map: map,
center: [104, 30.02700], // longitude, latitude
zoom: 13
});
var point = {
type: "point",
longitude: 104,
latitude: 30
};
var simpleMarkerSymbol = {
type: "simple-marker",
color: [226, 119, 40], // orange
outline: {
color: [255, 255, 255], // white
width: 1
}
};
var pointGraphic = new Graphic({
geometry: point,
symbol: simpleMarkerSymbol
});
graphicsLayer.add(pointGraphic);
map.add(graphicsLayer);
});
线条绘制
紧接点的绘制,线条就简单多了
- 定义line和simpleLineSymbol对象
var simpleLineSymbol = {
type: "simple-line",
color: [226, 119, 40], // orange
width: 2
};
var polyline = {
type: "polyline",
paths: [
[104, 30],
[114, 30],
[124, 30]
]
};
- 创建Graphic实例及监听Graphic
var polylineGraphic = new Graphic({
geometry: polyline,
symbol: simpleLineSymbol
});
graphicsLayer.add(polylineGraphic);
map.add(graphicsLayer);
-
效果图:
添加多边形
经过点和线的添加,你会发现不同的图形主要在于类型的差异,因此多边形我们只需修改其类型就可以完成
var polygon = {
type: "polygon",
rings: [
[-118.818984489994, 34.0137559967283],
[-118.806796597377, 34.0215816298725],
[-118.791432890735, 34.0163883241613],
[-118.79596686535, 34.008564864635],
[-118.808558110679, 34.0035027131376]
]
};
var simpleFillSymbol = {
type: "simple-fill",
color: [227, 139, 79, 0.8], // orange, opacity 80%
outline: {
color: [255, 255, 255],
width: 1
}
};
var polygonGraphic = new Graphic({
geometry: polygon,
symbol: simpleFillSymbol
});
graphicsLayer.add(polygonGraphic);
总的来说关于图形的添加无疑就是API和类的使用,本片需要关注Graphic和GraphicsLayer