【问题标题】:can not move location and create marker mapbox react无法移动位置并创建标记地图框反应
【发布时间】:2021-05-10 11:04:21
【问题描述】:

此代码是使用用户引入的值创建一个标记,并使该标记固定。 但我什至无法创建标记,没有任何反应。

渲染后它会停留在初始位置。我教过的可能是 lat 和 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>
    );
  }

【问题讨论】:

    标签: javascript node.js reactjs mapbox mapbox-gl


    【解决方案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]});
        }
    

    【讨论】:

    • @SomeoneSepecial 我这样做并得到一个错误:未捕获错误:` LngLatLike 参数必须指定为 LngLat 实例,对象 {lng: , lat: },一个对象 {lon: , lat: } 或 [, ]` 的数组,我有一个问题,seacrhValue 我仍然需要它,我该如何更改它 idf I不使用 setSearchValue?
    • 你需要使用const [ customMap, setMap] = useState({ lng: 292929, lat: 9929292}) // initial value然后在handleChange中,你需要用lat和lng更新对象
    • 我用一个非常粗略的例子更新了一个答案,你可以自己完善它,例如为 lng 和 lat 使用 2 个输入字段,并相应地更新它们。
    • 它不起作用,无论如何谢谢@SomeoneSpecial
    • 它正在工作,但现在发生的事情是我必须单击两次才能将标记放在目标中。它在到达目的地之前在同一位置渲染。谢谢
    猜你喜欢
    • 1970-01-01
    • 2019-05-19
    • 2020-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多