我在這里想要實作的是在有人搜索地址時繪制建筑物。這可以通過點擊事件上的地圖來實作。但它不適用于地理編碼器結果事件。要從構建層獲取功能,我必須將 {x, y} 指向可以通過點擊事件實作的層。但是當我使用地理編碼器“結果”事件時,它給出的是 {latitude, longitude} 坐標而不是 {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,
});
});
});
任何幫助將不勝感激 !
uj5u.com熱心網友回復:
所以如果我理解正確:
- 用戶搜索地址
- 地圖縮放以所選地址為中心
- 現在你想知道所選地址的螢屏 X/Y 坐標是多少
這很簡單:它正好在視口的中心。因此,您可以執行以下操作:
const x = map.getContainer().getClientRects()[0].width / 2;
const y = map.getContainer().getClientRects()[0].height / 2;
在第 1 步之后,您可能必須等到地圖實際完成移動并加載源要素。我會使用map.once('idle', ...)
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/443689.html
標籤:javascript jQuery 地图框 mapbox-gl-js
上一篇:MySQL約束
