Mapbox JS-在父状态更新时用程序更新地图



Gatsby项目-当所需路线的状态更新时,尝试突出显示Mapbox路线

当前实施情况:

  • 加载映射
  • 使用updateList函数更新父列表状态
  • 父级将更新的列表转发到其他组件以显示路线列表
  • 其中一个listItems被悬停
  • activeItem状态得到更新
  • activeItem使弹出窗口出现在当前地图上>gt>gt;不工作

由于地图框映射似乎只在useEffect挂钩中正确加载,我看不到任何其他方法可以根据父项的activeItem显示弹出窗口。如果有其他选择,请告诉我!

我尝试过的方法:

  • 从useEffect钩子中提取映射,并在普通常量中实例化它->"错误:无效类型:'container'必须是String或HTMLElement。">
  • 使用useState钩子为映射创建状态->映射对于所有与映射相关的函数都是未定义的,例如Map.on("load",….(

当前代码:

const EmbeddedMap = ({ updateList, activeItem }) => {
const mapContainerRef = useRef(null)
const [list, setList] = useState([])
useEffect(() => {    
const map = new mapboxgl.Map({
container: mapContainerRef.current,
accessToken: process.env.GATSBY_MAPBOX_TOKEN,
style: "mapbox://styles/mapbox/...",
center: [-90.836, 51.134],
zoom: 6,
})
const popup = new mapboxgl.Popup()
const getUniqueFeatures = (array, comparatorProperty) =>
array.filter(
(v, i, a) =>
a.findIndex(
t =>
t.properties[comparatorProperty] ===
v.properties[comparatorProperty]
) === i
)
const updateMap = map => {
const features = map.queryRenderedFeatures({ layers: ["data"] })
if (features) {
const uniqueFeatures = getUniqueFeatures(features, "post_id")
setList(uniqueFeatures)
}
}
map.on("load", () => {
updateMap(map)
map.on("movestart", () => {
map.setFilter("data", ["has", "title"])
})
map.on("moveend", () => {
updateMap(map)
})
map.on("mousemove", "data", e => {
map.getCanvas().style.cursor = "pointer"
const feature = e.features[0]
setPopup(map, popup, feature)
})
map.on("mouseleave", "data", () => {
map.getCanvas().style.cursor = ""
})
map.on("click", "data", e => {
const feature = e.features[0]
map.flyTo({
center: feature.geometry.coordinates[0],
})
setPopup(map, popup, feature)
})
})
return () => map.remove()
}, [])
return (
<div>
<EmbeddedMapStyled ref={mapContainerRef} />
</div>
)
}

将我的方法更改为ref解决了问题:

const map = useRef(null)
map.current = new mapboxgl.Map({
container: mapContainerRef.current,
accessToken: process.env.GATSBY_MAPBOX_TOKEN,
style: "mapbox://styles/data",
center: [-114.836, 51.134],
zoom: 6,
})

然后我可以很容易地重复使用地图,例如:

map.current.flyTo({
center: activeItem.startPoint,
})

最新更新