【问题标题】:How to set view of map for new location using latitute and longitude with React-leaflet如何使用 React-leaflet 使用纬度和经度设置新位置的地图视图
【发布时间】:2021-04-16 03:22:16
【问题描述】:

我无法为输入 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;

【问题讨论】:

    标签: javascript reactjs api rest react-leaflet


    【解决方案1】:

    因此,您无法使用状态更改中心...

    除了它的孩子,MapContainer 的 props 是不可变的:改变 它们在第一次设置后将不会影响 地图实例或其容器。

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

          <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>
      );
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-12-02
      • 2011-10-31
      • 1970-01-01
      • 2018-02-15
      • 2012-03-24
      • 1970-01-01
      • 2019-12-07
      相关资源
      最近更新 更多