无法从Mapbox GL中的建筑源图层获取要素



我在这里试图实现的是在有人搜索地址时绘制建筑。这可以通过点击地图事件来实现。但它不适用于地理编码结果事件。为了从构建层获得功能,我必须将{x,y}点传递到可以通过单击事件实现的层。但是当我使用地理编码器"时;结果";事件,它给出的是{纬度,经度}坐标,而不是{x,y}点。我还试着用map.project((转换这些坐标,但没有正确指向。是否有实现这一点的变通方法?签出我的代码:


const bounds = [
[-97.846976993, 30.167105159], // Southwest coordinates
[-97.751211018, 30.242129961], // Northeast coordinates
];
const map = new mapboxgl.Map({
container: "map",
style: "mapbox://styles/smallcrowd/cl07a4926001b15pnu5we767g",
center: [-79.4512, 43.6568],
zoom: 13,
// maxBounds: bounds,
});
// Add the control to the map.
const geocoder = new MapboxGeocoder({
accessToken: mapboxgl.accessToken,
mapboxgl: mapboxgl,
});
map.on("load", function () {
var layers = map.getStyle().layers;
var labelLayerId;
for (var i = 0; i < layers.length; i++) {
if (layers[i].type === "symbol" && layers[i].layout["text-field"]) {
labelLayerId = layers[i].id;
break;
}
}
map.addLayer(
{
id: "3d-buildings",
source: "composite",
"source-layer": "building",
type: "fill",
minzoom: 10,
paint: {
"fill-color": "#aaa",
},
},
labelLayerId
);
map.addSource("currentBuildings", {
type: "geojson",
data: {
type: "FeatureCollection",
features: [],
},
});
map.addLayer(
{
id: "highlight",
source: "currentBuildings",
type: "fill",
minzoom: 15,
paint: {
"fill-color": "#f00",
},
},
labelLayerId
);
// Working perfectly on click, it is painting the address but I do not want the address to be clicked rather it should be painted on searched.
map.on("click", "3d-buildings", (e) => {
map.getSource("currentBuildings").setData({
type: "FeatureCollection",
features: e.features,
});
});
//not working because the 3d-building layer wants input as x,y point which I tried to convert result's coordinates into point but map.project is giving wrong points as compared to mouse clicked points
geocoder.on("result", (e) => {
var coordinates = e.result.geometry.coordinates;
const point = map.project(coordinates);
const selectedFeatures = map.queryRenderedFeatures(point, {
layers: ["3d-buildings"],
});
console.log(point);
map.getSource("currentBuildings").setData({
type: "FeatureCollection",
features: selectedFeatures.features,
});
});
});

任何帮助都将不胜感激!

如果我理解正确:

  1. 用户搜索地址
  2. 地图缩放到选定地址的中心
  3. 现在您想知道所选地址的屏幕X/Y坐标是多少

这很简单:它正好在视口的中心。所以你可以做一些类似的事情:

const x = map.getContainer().getClientRects()[0].width / 2;
const y = map.getContainer().getClientRects()[0].height / 2;

在步骤1之后,您可能需要等待地图真正完成移动,并且源功能已经加载。我会使用map.once('idle', ...)

相关内容

  • 没有找到相关文章

最新更新