无法移动位置并创建标记 mapbox 反应
2021-05-10
1097
此代码用于使用用户输入的值创建标记,并使此标记固定。 但我甚至无法创建标记,什么也没发生。
渲染后,它停留在初始位置。我告诉过它可能是纬度和经度顺序,但我尝试这样做,它一直在加载。 我也尝试删除 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>
);
}
1个回答
尝试在某个状态下保存地图并使用
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]});
}
Someone Special
2021-05-10