需求:在地图上,鼠标点击的第一次标记起点,点击第二次标记终点,并立马显示起点与终点之间的直线距离
实现:
1.新建页面,创建map 、view等基本操作;
2.给view添加监听事件,监听click;
this.view.on('click', event => {
if (this.view.graphics.length === 0) {
// 添加第一个点
this.addPoint( 'original', event.mapPoint)
} else if (this.view.graphics.length === 1) {
// 添加终点
this.addPoint( 'destination', event.mapPoint)
// 添加连线及显示距离
this.addDistance()
} else {
// 添加一个新的起点
this.view.graphics.removeAll()
this.addPoint('original', event.mapPoint)
}
}
3.实现函数addPoint和addDistance
//添加起点和终点
addPoint(type, point) {
this.view.graphics.add(new Graphic({
geometry: point,
symbol: {
type: 'point',
color: type === 'original' ? 'white':'black'
size: '8px'
}
}))
}
// 添加连线和终点
addDistance(){
const p1 = this.view.graphics.items[0].geometry
const p2 - this.veiw.graphics.items[1].geometry
const polyline = new Polyline()
polyline.addPath([[p1.x, p1.y],[p2.x, p2.y]])
const dis = this.getDistance(p1.x, p2.x, p1.y, p2.y)
const textSymbol = {
type: 'text',
color: 'white',
text: dis + '米'
}
const lineSymbol = {
type: 'simple-line',
color: 'white',
width: 2
}
this.view.graphics.add(new Graphic({
geometry: polyline,
symbol: lineSymbol
})
this.view.graphics.add(new Graphic({
geometry: polyline,
symbol: textSymbol
})
}
// 根据经纬度计算两点间距离
getDistance(x1, x2, y1, y2){
const EARTH_RADIUS = 6378137
const radX1 = rad(x1)
const radX2 = rad(x2)
const a = radX1 - radX2
const b = rad(y1) - rad(y2)
let s = Math.asin(Math.sqrt(Math.pow(Math.sin(a/2), 2) + Math.cos(radX1) * Math.cos(radX2) * Math.pow(Math.sin(b/2),2)))
s *= EARTH_RADIUS
s = Math.round(s * 10000)/ 10000
return s
function rad(d){
return d * Math.PI / 180
}
}
需要注意的点:
1.如果把函数分开,可能会遇到Graphic等对象不存在的问题,可以通过函数的传参解决
2.如果没有字体服务,就没法显示距离的字体,需要部署字体服务