无法移动位置并创建标记映射框react



这段代码是使用用户引入的值创建一个标记,并修复这个标记。但我甚至无法创建标记,什么都没发生。

它在渲染后一直停留在初始位置。我教过它可能是一个lat-and-lng订单,但我试过了,它一直在加载。我也试图删除flyTo,但没有改变

export default function Map() {

const mapContainer = useRef(null);
const [lng, setLng] = useState(-70.9);
const [lat, setLat] = useState(42.35);
const [zoom, setZoom] = useState(9);

const [searchValue, setSearchValue] = useState("");


useEffect(() => {
const map = new mapboxgl.Map({
container: mapContainer.current,
style: "mapbox://styles/mapbox/streets-v11",
center: [lng, lat],
zoom: zoom,
});
map.addControl(new mapboxgl.NavigationControl(), "top-right");
map.on("move", () => {
setLng(map.getCenter().lng.toFixed(4));
setLat(map.getCenter().lat.toFixed(4));
setZoom(map.getZoom().toFixed(2));
});
}, []); // eslint-disable-line react-hooks/exhaustive-deps

function getCoordinates(placesContent) {
const { center, place_name } = placesContent.features[0];
return {
coordinates: center.reverse(),
name: place_name,
};
}
const changeMapCenter = async () => {
const map = new mapboxgl.Map({
container: mapContainer.current,
style: "mapbox://styles/mapbox/streets-v11",
center: [lng, lat],
zoom: zoom,
});
return fetch(
`${MAPBOX_PLACES_API}${searchValue}${REST_PLACES_URL}`,
FETCH_HEADERS
)
.then((res) => res.json())
.then((apiData) => {
console.log("apidata=>", apiData);
const { coordinates } = getCoordinates(apiData);
console.log("coordinates=>", coordinates);
map.flyTo(coordinates);
new mapboxgl.Marker().setLngLat(coordinates).addTo(map);
});
};
const handleChange = (event) => {
setSearchValue(event.target.value);
};
return (
<div className="mapBox">
<div className="sidebar">
Longitude: {lng} | Latitude: {lat} | Zoom: {zoom}
<div>
<label>create your spot collection</label>
<input
type="text"
id="spotLocation"
onChange={handleChange}
value={searchValue}
/>
<button onClick={changeMapCenter}>search and create </button>
</div>
</div>
<div className="map-container" ref={mapContainer} />
</div>
);
}

尝试将地图保存在一个状态并使用setCenter

const [ customMap, setMap ] = useState({ lat: 0, lng: 0}) // set your own initial value
useEffect(() => {
const map = new mapboxgl.Map({
container: mapContainer.current,
style: "mapbox://styles/mapbox/streets-v11",
center: [lng, lat],
zoom: zoom,
});
map.addControl(new mapboxgl.NavigationControl(), "top-right");
map.on("move", () => {
setLng(map.getCenter().lng.toFixed(4));
setLat(map.getCenter().lat.toFixed(4));
setZoom(map.getZoom().toFixed(2));
});
setMap(map);
}, []);

const handleChange = (event) => {
// i assume event.target.value contains the coordinates
// example 929292, 2929292
setSearchValue(event.target.value)
};
const onSubmit = () => {
let coordinates = searchValue.split(',')
customMap.setCenter({ lat: coordinates[0], lng: coordinates[1]});
}

最新更新