文章目录
- 1、飞行平移到鼠标点击图层属性的地图中心位置
- 2、当鼠标光标进入“圆”图层中的某个要素时,将其更改为指针
- 3、量测距离
- 4、量测area面积和中心点坐标
1、飞行平移到鼠标点击图层属性的地图中心位置
//鼠标点击事件
map.on("click", "iconImage", (e) => {
console.log("e", e);
const lng = e.lngLat.lng;
const lat = e.lngLat.lat;
const coordinates = e.lngLat;
const description = "点击的位置坐标为:" + lng + "/" + lat;
popup.setLngLat(coordinates).setHTML(description).addTo(map);
//飞行平移到地图中心的位置
map.flyTo({
center: e.lngLat,
zoom: 3,
speed: 0.2,
curve: 2,
});
});
2、当鼠标光标进入“圆”图层中的某个要素时,将其更改为指针
// Change the cursor to a pointer when the it enters a feature in the 'circle' layer.
map.on('mouseenter', 'circle', () => {
map.getCanvas().style.cursor = 'pointer';
});
// Change it back to a pointer when it leaves.
map.on('mouseleave', 'circle', () => {
map.getCanvas().style.cursor = '';
});
3、量测距离
单击地图上的点来创建线,使用turf测量线的长度距离。
这里我们使用到turfjs库,安装并引入turf。
npm安装
npm install @turf/turf
页面中引入:
import * as turf from '@turf/turf'
页面中添加一个容器:
<div id="distance" class="distanceContainer"></div>
核心代码:
const distanceContainer = document.getElementById('distance');
// GeoJSON object to hold our measurement features
const geojson = {
'type': 'FeatureCollection',
'features': []
};
// Used to draw a line between points
const linestring = {
'type': 'Feature',
'geometry': {
'type': 'LineString',
'coordinates': []
}
};
map.addSource('geojson', {
'type': 'geojson',
'data': geojson
});
// Add styles to the map
map.addLayer({
id: 'measure-points',
type: 'circle',
source: 'geojson',
paint: {
'circle-radius': 5,
'circle-color': '#000'
},
filter: ['in', '$type', 'Point']
});
map.addLayer({
id: 'measure-lines',
type: 'line',
source: 'geojson',
layout: {
'line-cap': 'round',
'line-join': 'round'
},
paint: {
'line-color': '#000',
'line-width': 2.5
},
filter: ['in', '$type', 'LineString']
});
map.on('click', (e) => {
const features = map.queryRenderedFeatures(e.point, {
layers: ['measure-points']
});
console.log(features)
// Remove the linestring from the group
// so we can redraw it based on the points collection.
if (geojson.features.length > 1) geojson.features.pop();
// Clear the distance container to populate it with a new value.
distanceContainer.innerHTML = '';
// If a feature was clicked, remove it from the map.
if (features.length) {
const id = features[0].properties.id;
geojson.features = geojson.features.filter(
(point) => point.properties.id !== id
);
} else {
const point = {
'type': 'Feature',
'geometry': {
'type': 'Point',
'coordinates': [e.lngLat.lng, e.lngLat.lat]
},
'properties': {
'id': String(new Date().getTime())
}
};
geojson.features.push(point);
}
if (geojson.features.length > 1) {
linestring.geometry.coordinates = geojson.features.map(
(point) => point.geometry.coordinates
);
geojson.features.push(linestring);
// Populate the distanceContainer with total distance
const value = document.createElement('pre');
const distance = turf.length(linestring);
value.textContent = `Total distance: ${distance.toLocaleString()}km`;
distanceContainer.appendChild(value);
}
map.getSource('geojson').setData(geojson);
});
});
//获取鼠标移动位置
map.on("mousemove", (e) => {
this.screenxy = JSON.stringify(e.point);
this.lnglat = JSON.stringify(e.lngLat);
const features = map.queryRenderedFeatures(e.point, {
layers: ['measure-points']
});
// Change the cursor to a pointer when hovering over a point on the map.
// Otherwise cursor is a crosshair.
map.getCanvas().style.cursor = features.length ?
'pointer' :
'crosshair';
});
效果:
4、量测area面积和中心点坐标
在地图上画一个多边形,并计算多边形中包含的面积和中心点坐标。
操作步骤:
-
单击地图开始绘制多边形。
-
绘制最终顶点时双击以完成多边形。多边形的总面积将显示在地图的左上角。
-
要删除多边形并绘制新多边形,请使用地图右上角的绘制工具。
该功能使用mapbox gl draw绘制多边形,并使用Turf.js计算其面积(平方米)和中心点坐标。
代码如下:
创建一个div元素:
<div id="calculated-area" style="width: 250px;height: 150px;background-color: #ffff;margin: 10px;padding: 10px;">
实例化mapboxdraw:
const draw = new MapboxDraw({
// displayControlsDefault: false,
// Select which mapbox-gl-draw control buttons to add to the map.
controls: {
polygon: true,
trash: true
},
// Set mapbox-gl-draw to draw by default.
// The user does not have to click the polygon control button first.
defaultMode: 'draw_polygon'
});
map.addControl(draw);
map.on('draw.create', updateArea);
map.on('draw.delete', updateArea);
map.on('draw.update', updateArea);
function updateArea(e) {
const data = draw.getAll();
console.log(data)
const answer = document.getElementById('calculated-area');
if (data.features.length > 0) {
const area = turf.area(data);
// const polygonfeatures = turf.points([data.features[0].geometry.coordinates[0]])
const centrepostion = turf.centroid(data.features[0])
// Restrict the area to 2 decimal points.
const rounded_area = Math.round(area * 100) / 100;
answer.innerHTML = `<p>面积为:<strong>${rounded_area}</strong>square meters</p>
<br />
<p>中心点坐标:${centrepostion.geometry.coordinates}</p>`;
console.log(centrepostion)
} else {
answer.innerHTML = '';
if (e.type !== 'draw.delete')
alert('Click the map to draw a polygon.');
}
}
效果展示: