【发布时间】:2019-11-19 15:55:42
【问题描述】:
如果我点击一个标记,我想将地图视图平移到标记的中心。到目前为止,这适用于我的项目。此外,我希望打开的弹出窗口与地图视图的中心对齐。
我想我可以像这样使用leaflet-popup 类对其进行硬编码:
.leaflet-popup {
transform: translate(-40%, 50%) !important;
}
但这不起作用。我的代码的问题是,弹出窗口的位置独立于地图视图。但它应该根据当前视图居中。我可以告诉你我的地图设置:
编辑
我提供了一个CodeSandBox 链接来玩。单击顶部的标记,您会看到弹出窗口未在屏幕中心对齐:
地图组件
const {Map, TileLayer, Marker, GeoJSON} = ReactLeaflet;
function MapOverlay({setSwipeState}) {
const mapRef = useRef(null);
const [donationLocations] = useState([
[48.135125, 11.581981], [58.403, 20.420], [43.300, 40],
[70.505, -20], [40.505, -80], [-40.505, -10]
]);
function centerMapView(e) {
const {leafletElement} = mapRef.current;
if(e) {
leafletElement.setView(e.popup._latlng); // center view to where popup opens
// todo: align popup in the middle of the screen
// Get bounds of map view, divide it by 2 and apply coorditanes to the popup position
}
}
function getMapData() {
return (
<div>
{
donationLocations.map((position, i) =>
(
<Marker position={position} key={i}>
<MarkerPopup/>
</Marker>
)
)
}
</div>
)
}
return (
<Map
ref={mapRef}
center={[45.000, 10.000]}
zoom={3}
onPopupopen={centerMapView.bind(this)}
zoomControl={false}
minZoom={3}
bounceAtZoomLimits={true}
maxBoundsViscosity={.95}
maxBounds={[[-180, -90], [180, 90]]}
>
<TileLayer
noWrap={true}
attribution='&copy <a href="http://osm.org/copyright">OpenStreetMap</a> contributors | &copy <a href="https://apps.mapbox.com/feedback/">Mapbox</a>'
url={'https://api.mapbox.com/styles/v1/mapbox/streets-v11/tiles/{z}/{x}/{y}?access_token=' + process.env.REACT_APP_MAPBOX_KEY}
/>
{getMapData()}
</Map>
)
}
标记弹出组件
const {Popup} = ReactLeaflet;
export default function MarkerPopup() {
return (
<Popup
autoPan={false} // Important part here
>
<Card>
...
</Card>
</Popup>
);
}
【问题讨论】:
-
你好。 this 是你目前拥有的吗?如果是这种情况,您可以将标记集中在其 y 轴上,而不是在地图的中心,并且弹出窗口看起来不错,也居中。你到底想达到什么目标?
-
@kboul 我用 CodeSandBox 链接更新了我的问题。我想要实现的是在地图中心完全对齐的弹出窗口。问候马可
标签: javascript reactjs leaflet react-leaflet