如何解决无法使用图书馆传单移动我的标记 Working codesandbox
我正在使用传单库处理 react.js,我希望在单击地图时移动标记而不是添加新标记。这是我的代码:
import React from "react";
import {
MapContainer,TileLayer,useMapEvents,MapConsumer
} from "react-leaflet";
import "leaflet/dist/leaflet.css";
import L from "leaflet";
import icon from "./constants";
import "./styles.css";
export default function App() {
function MyComponent() {
const map = useMapEvents({
click: (e) => {
const { lat,lng } = e.latlng;
L.marker([lat,lng],{ icon }).addTo(map);
}
});
return null;
}
return (
<MapContainer
center={[50.5,30.5]}
zoom={13}
style={{ height: "100vh" }}
// whenReady={(map) => {
// console.log(map);
// map.target.on("click",function (e) {
// const { lat,lng } = e.latlng;
// L.marker([lat,{ icon }).addTo(map.target);
// });
// }}
>
<TileLayer
attribution='© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
<MapConsumer>
{(map) => {
console.log("map center:",map.getCenter());
map.on("click",function (e) {
const { lat,lng } = e.latlng;
L.marker([lat,{ icon }).addTo(map);
});
return null;
}}
</MapConsumer>
</MapContainer>
);
}
你可以在那里找到我的代码:my code
你能帮我吗?
非常感谢!
解决方法
是的,这是可以做到的。您可以设置现有标记的纬度,而不是每次都创建一个新标记:
<MapConsumer>
{(map) => {
let marker;
map.on("click",function (e) {
const { lat,lng } = e.latlng;
if (marker) {
marker.setLatLng([lat,lng]);
} else {
marker = L.marker([lat,lng],{ icon }).addTo(map);
}
});
return null;
}}
</MapConsumer>
Working codesandbox
,根据文档,这是标记的预期行为:
draggable
Boolean false 标记是否可拖动
鼠标/触摸与否。
含义:
L.marker([lat,{ icon,draggable: "true" }).addTo(map);
将使标记成为可拖动
为了防止在地图点击时出现多个标记,您可以考虑使用 solution proposed in another answer 或使用 once
而不是 on
:
表现为 on(...),除了监听器只会被触发一次并且 然后删除。
最后的例子
<MapContainer center={[50.5,30.5]} zoom={13} style={{ height: "100vh" }}>
<TileLayer
attribution='© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
<MapConsumer>
{(map) => {
map.once("click",function (e) {
const { lat,lng } = e.latlng;
L.marker([lat,draggable: "true" }).addTo(map);
});
return null;
}}
</MapConsumer>
</MapContainer>
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。