问题描述
我当前在 React项目中使用 MapBox GL JS 。
我想知道在交互结束后如何在特定坐标处显示一些文本。我从函数 getMinCoords()
获取位置的坐标我当前的代码如下
stop() {
let nextState = this.state;
if (nextState !== INteraCTION_STATES.completed) {
nextState = INteraCTION_STATES.abort;
}
if (this.vertices.length > 2) {
this.annotation.geometries = [{
type: 'polygon',coordinates: this.getpolygonCoordinates(),properties: {
annotationType: 'polygon',},}];
} else {
this.annotation.geometries = [];
}
console.log(this.getMinCoords());
this.mapViewer.off('click',this.onClickCallback);
this.asset.dataUpdated();
this.setState(nextState);
this.flushState();
}
负责注释的功能如下:
this.geometries.forEach((geometry) => {
switch (geometry.type) {
case 'Point':
case 'Linestring':
case 'polygon': {
const styleProps = AssetStyle.getStyles(geometry,styles);
const feature = GeoJSONUtil.featureFromGeometry(geometry,this.properties);
if (this.properties.annotationType === 'label') {
styleProps.textAnchor = 'center';
}
feature.properties = { ...feature.properties,...styleProps };
features.push(feature);
break;
}
在刷新状态之前,我想在getMinCoords返回的坐标处显示区域。我还有另一个函数 getArea(),该函数返回面积。我只需要在地图上显示
解决方法
用空资源实例化地图后,您可以创建一个空图层,如下所示:
代码段:
//Empty Source
const textGeoJsonSource = {
type: 'geojson',data: featureCollection //Initially this is empty
};
//Text Layer with textGeoJsonSource
const sectionTextLayer: mapboxgl.Layer = {
"id": "sectionTextLayer","type": "symbol","source": textGeoJsonSource,"paint": {
"text-color": textColor,//Color of your choice
"text-halo-blur": textHaloBlur,"text-halo-color": textHaloColor,"text-halo-width": textHaloWidth,"text-opacity": textOpacity
},"layout": {
"text-field": ['get','t'],//This will get "t" property from your geojson
"text-font": textFontFamily,"text-rotation-alignment": "auto","text-allow-overlap": true,"text-anchor": "top"
}
};
this.mapInstance.addLayer(sectionTextLayer);
然后,一旦有了坐标(例如您的案例中的getMinCoords),就将“ textGeoJsonSource”的源设置为以下:
{
"type": "FeatureCollection","features": [
{
"type": "Feature","geometry": {
"type": "Point","coordinates": [ //Pass your coordinates here
5.823,-6.67
]
},"properties": {
"t": "18C" //Text you want to display on Map
}
}
]
}
请注意以下几点:
- 您的要素集合将需要点坐标,以便在该点上的地图上显示文本。如果您有多边形,请首先获取该多边形的质心,然后再使用草皮: http://turfjs.org/docs/#centroid