【问题标题】:MapBox GL JS - Update coordinates of the current map?MapBox GL JS - 更新当前地图的坐标?
【发布时间】:2022-07-21 16:15:12
【问题描述】:

我无法更新当前地图的坐标。在我下面的代码中...

  1. useEffect 初始化地图并添加搜索栏和地理定位器。然后,使用两个“if”语句(地图在 2 个不同的组件中使用)来更新状态中的地图坐标(“setLng”和“setLat”)。

  2. 在 state 中的坐标被更新后,第二个 useEffect 被调用。此 useEffect 使用以下语法使用新坐标更新当前地图:

      map.current.getCenter().lng.toFixed(4);
      map.current.getCenter().lat.toFixed(4);
    

然后,再次使用两个“if”语句(以确定哪个组件正在使用地图),我将标记添加到当前地图以显示我存储的标记坐标(在 localStorage 和 Redux 状态下)。

我遇到的问题是上面更新当前地图坐标的代码不起作用。此外,标记也没有出现。

很高兴获得以下方面的反馈:

  1. 用于更新当前地图坐标的语法
  2. 获取有关我的代码整体结构的反馈,以便标记也将显示。

非常感谢您的反馈。我的完整代码如下供参考:

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


    【解决方案1】:

    我遇到了同样的问题,问题在于 mapRef.current 从未注册为拥有地图,我可以看到地图已加载,但 mapRef.current 仍会输出为空。我的解决方案是使用useState 来确定地图何时准备就绪。看看下面什么对我有用:

    interface MapCenter {
      lng: number
      lat: number
    }
    
    const Map = () => {
      const containerRef = useRef<HTMLDivElement | null>(null)
      const mapRef = useRef<mapboxgl.Map | null>(null)
      const [map, setMap] = useState<mapboxgl.Map | undefined>()
      const [zoom, setZoom] = useState(9)
      const [center, setCenter] = useState<MapCenter>({
        lng: -0.1163,
        lat: 51.4929
      })
    
      useEffect(() => {
        // Initialize map only once
        if (map || containerRef.current === null) return
    
        mapRef.current = new mapboxgl.Map({
          container: containerRef.current,
          style: 'mapbox://styles/mapbox/streets-v11',
          center: [center.lng, center.lat],
          zoom
        })
    
        setMap(mapRef.current)
      }, [])
    
      useEffect(() => {
        // Wait for map to initialize
        if (!map) return
    
        map.on('move', () => {
          const { lng, lat } = map.getCenter()
          setCenter({
            lng: Number(lng.toFixed(4),
            lat: Number(lat.toFixed(4)
          })
          setZoom(Number(map.getZoom().toFixed(2))
        })
      }, [map])
    
      return (
        <div ref={containerRef} className="map-container" />
      )
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-10-29
      • 1970-01-01
      • 2020-07-17
      • 1970-01-01
      • 2016-07-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多