如何使用 React-leaflet 使用纬度和经度为新位置设置地图视图

How to set view of map for new location using latitute and longitude with React-leaflet

我无法为输入的 IP 地址设置地图视图,而标记可以移动到地图上给定输入 IP 地址的新位置。地图似乎停留在初始位置,而标记移动到新位置。

所以,当我在输入框中输入新的 IP 地址时,它应该将地图更改为新位置。

import React, { useEffect, useState} from "react";
import Result from "../src/Components/Result";
import {MapContainer, TileLayer, Marker, Popup } from 'react-leaflet';

function App() {
  const APP_KEY = PERSONAL_KEY;

  const [IPdata, SetIPData] = useState([]);
  const [search, setSearch] = useState("");
  const [query, setQuery] = useState("8.8.8.8");
  const [loaded, setLoaded] = useState(false);


  useEffect(() => {
    getIp();
    setLoaded(true);

  }, [query]);

  async function getIp() {
    const response = await fetch(`https://geo.ipify.org/api/v1?apiKey=${APP_KEY}&ipAddress=${query}`);
    const data = await response.json();
    console.log(data);
    SetIPData(data)
  }

  function handleChange(event) {
    setSearch(event.target.value);
    console.log(event.target.value);

  }

  function handleSubmit(event) {
    event.preventDefault();
    setQuery(search);
    setSearch('');

  }

  return (
    loaded ? (
      <div>
        <div className="container">

          <div className="input-section">
            <h1 className="header"> IP Address Tracker</h1>

            <form onSubmit={handleSubmit} className="search-form">
              <input className="search-input" type="text" placeholder="Search for any IP address or domain" onChange={handleChange} />
              <button className="search-button" type="submit"> Go! </button>
            </form>

          </div>

          <div className="result-container">

            <Result
              heading={"IP Address"}
              searchResult={IPdata.ip}
            />

            <Result
              heading={"Location"}
              searchResult={IPdata?.location?.country}
            />

            <Result
              heading={"Timezone"}
              searchResult={"UTC" + IPdata?.location?.timezone}
            />

            <Result
              heading={"ISP"}
              searchResult={IPdata.isp}
            />

          </div>

        </div>

        {IPdata.location && (


          <MapContainer
            center={[IPdata.location?.lat, IPdata.location?.lng]}
            zoom={13}
            scrollWheelZoom={true}

          >
            <TileLayer
              attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
              url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
            />
            <Marker position={[IPdata?.location?.lat, IPdata?.location?.lng]}>
              <Popup>Your IP Location</Popup>
            </Marker>
          </MapContainer>
        )
        }

      </div>) : <p>Loading...</p>

  )

}

export default App;

因为这个你不能改变状态的中心...

Except for its children, MapContainer props are immutable: changing them after they have been set a first time will have no effect on the Map instance or its container.

但是,我相信如果您添加一个关键道具,它可能会起作用。你可以试试看是否有效

      <MapContainer
        center={[IPdata.location?.lat, IPdata.location?.lng]}
        zoom={13}
        scrollWheelZoom={true}
        key={`${IPdata.location?.lat}${IPdata.location?.lng}`}
      >

已更新:这里使用 setView -> React leaflet center attribute does not change when the center state changes

提供了另一种解决方案
function ChangeView({ center, zoom }) {
  const map = useMap();
  map.setView(center, zoom);
  return null;
}

function Map({ center, zoom }) {
  return (
    <div className="map">
      <MapContainer center={center} zoom={zoom} scrollWheelZoom={false}>
        <ChangeView center={center} zoom={zoom} /> 
        <TileLayer
          url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
          attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
        />
      </MapContainer>
    </div>
  );
}