英文:
Showing/Hiding groups of markers using layers or some other grouping method
问题
我有一组标记,我想在React Google地图上设置它们的可见性或不可见性。
在ESRI/ArcGIS地图中,您可以创建可以打开或关闭的图层,但似乎在Google地图中没有类似的功能。
我想可以给这些标记指定一个特定的类,并在需要时打开或关闭它们的可见性,但我担心这可能会影响性能。
关于前进的方法,有什么建议吗?
英文:
I have a set of markers which I want to have visible or not on a React Google map.
In ESRI/ArcGIS maps you can create layers which can be turned on or off, but it does not seem any equivalent features exist in Google maps.
I suppose can give the markers a specific class and turn their visibility on or off, but I am concerned this may impact performance.
Any suggestions on a way forward?
答案1
得分: 1
Google Maps API不支持这种自定义图层(请参考官方文档以获取支持的图层列表)。
以下自定义组件演示了如何对标记进行分组并切换其可见性。
function MarkersGroup(props, context) {
const layersRef = useRef(null);
useEffect(() => {
const map = context[MAP];
let layers = null;
if (!layersRef.current) {
layers = new window.google.maps.MVCObject();
for (let name in props.groupData) {
for (let item of props.groupData[name].items) {
const markerProps = { position: { lat: item.lat, lng: item.lng } };
const marker = new window.google.maps.Marker(markerProps);
marker.bindTo("map", layers, name);
}
}
layersRef.current = layers;
} else layers = layersRef.current;
for (let name in props.groupData) {
if (props.groupData[name].visible) {
layers.set(name, map);
} else {
layers.set(name, null);
}
}
});
return null;
}
注:
google.maps.MVCObject
类 用于存储图层(标记)组。- 通过
MVCObject.set
方法 切换图层可见性。
英文:
Google Maps API does not support this kind of custom layers (refer official docs for a supported list of layers).
The following custom component demonstrates how to group markers and toggle its visibility
function MarkersGroup(props, context) {
const layersRef = useRef(null);
useEffect(() => {
const map = context[MAP];
let layers = null;
if (!layersRef.current) {
layers = new window.google.maps.MVCObject();
for (let name in props.groupData) {
for (let item of props.groupData[name].items) {
const markerProps = { position: { lat: item.lat, lng: item.lng } };
const marker = new window.google.maps.Marker(markerProps);
marker.bindTo("map", layers, name);
}
}
layersRef.current = layers;
} else layers = layersRef.current;
for (let name in props.groupData) {
if (props.groupData[name].visible) {
layers.set(name, map);
} else {
layers.set(name, null);
}
}
});
return null;
}
Notes:
google.maps.MVCObject
class - is used to store layer(markers) group- layer visibility is toggled via
MVCObject.set
method
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论