【发布时间】:2022-07-21 16:15:12
【问题描述】:
我无法更新当前地图的坐标。在我下面的代码中...
-
useEffect 初始化地图并添加搜索栏和地理定位器。然后,使用两个“if”语句(地图在 2 个不同的组件中使用)来更新状态中的地图坐标(“setLng”和“setLat”)。
-
在 state 中的坐标被更新后,第二个 useEffect 被调用。此 useEffect 使用以下语法使用新坐标更新当前地图:
map.current.getCenter().lng.toFixed(4); map.current.getCenter().lat.toFixed(4);
然后,再次使用两个“if”语句(以确定哪个组件正在使用地图),我将标记添加到当前地图以显示我存储的标记坐标(在 localStorage 和 Redux 状态下)。
我遇到的问题是上面更新当前地图坐标的代码不起作用。此外,标记也没有出现。
很高兴获得以下方面的反馈:
- 用于更新当前地图坐标的语法
- 获取有关我的代码整体结构的反馈,以便标记也将显示。
非常感谢您的反馈。我的完整代码如下供参考:
import React, { useRef, useEffect, useState } from "react";
import { Card, Button, Link } from "@mui/material";
import { useAuth } from "../contexts/AuthContext";
import { Link as RouterLink, useHistory } from "react-router-dom";
import MapboxGeocoder from "@mapbox/mapbox-gl-geocoder";
import axios from "axios";
import "@mapbox/mapbox-gl-geocoder/dist/mapbox-gl-geocoder.css";
import { useSelector } from "react-redux";
import mapboxgl from "!mapbox-gl";
mapboxgl.accessToken =
"HIDDEN";
export default function Map(props) {
const [error, setError] = useState("");
const { currentUser, logout } = useAuth();
const history = useHistory();
const mapContainer = useRef(null);
const map = useRef(null);
const [lng, setLng] = useState(-73.985428);
const [lat, setLat] = useState(40.748817);
const [zoom, setZoom] = useState(9);
const listings = useSelector((state) => state.listings);
useEffect(() => {
if (map.current) return; // initialize map only once
map.current = new mapboxgl.Map({
container: mapContainer.current,
style: "mapbox://styles/mapbox/streets-v11",
center: [lng, lat],
zoom: zoom,
})
.addControl(
new MapboxGeocoder({
accessToken: mapboxgl.accessToken,
mapboxgl: mapboxgl,
})
)
.addControl(
new mapboxgl.GeolocateControl({
positionOptions: {
enableHighAccuracy: true,
},
trackUserLocation: true,
showUserHeading: true,
})
);
if (props.currentMapListings) {
const getLatLng = async () => {
try {
const { data } = await axios.get(
"HIDDEN"
);
setLat(data.latitude);
setLng(data.longitude);
} catch (error) {
console.log(error);
}
};
getLatLng();
}
if (props.lngLatHostSummary) {
let listingLngLat = Object.values(props.lngLatHostSummary);
setLat(listingLngLat[1]);
setLng(listingLngLat[0]);
}
}, []);
useEffect(() => {
if (lat && lng) {
map.current.getCenter().lng.toFixed(4);
map.current.getCenter().lat.toFixed(4);
if (props?.currentMapListings) {
listings.forEach((listingData) => {
if (listingData.host) {
let listingLngLat = Object.values(
listingData.host.location
).reverse();
new mapboxgl.Marker().setLngLat(listingLngLat).addTo(map.current);
}
});
}
if (props?.lngLatHostSummary) {
if (map && map.current) {
let listingLngLat = Object.values(props.lngLatHostSummary);
new mapboxgl.Marker().setLngLat(listingLngLat).addTo(map.current);
}
}
}
}, [lat, lng]);
return (
<div>
<div ref={mapContainer} className="map-container" />
</div>
);
}
【问题讨论】:
标签: reactjs mapbox mapbox-gl-js