簡體   English   中英

想要更新 React-Leaflet-js 的 MapContainer 的中心

[英]Want to Update the Center of MapContainer of React-Leaflet-js

我最近開始使用 React。 但是當我開始 React-Leaflet Map 時,我遇到了問題。 我有一個所有國家的 Json 文件,我只想放大我選擇的那個國家。 但我不知道我該怎么做?

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

這是我的 Map.js 文件,我已將其導入我的 App.js 文件並使用 useState 方法為其提供數據。

所以 leaflet 定位(像大多數 web 映射庫一樣)適用於緯度和經度。 您在評論中引用的 API 接受國家名稱作為參數,並返回一些 COVID 數據。 為了讓您的 map 做出適當響應,您需要對國家/地區名稱進行地理編碼。 快速搜索找到了這個包含縣名和國家中心緯度的倉庫: latlng ://github.com/eesur/country-codes-lat-long

此處引用的 json 文件具有以下格式的數據:

{
  "country" : "Albania",
  "alpha2" : "AL",
  "alpha3" : "ALB",
  "numeric" : 8,
  "latitude" : 41,
  "longitude" : 20
}

為簡單起見,假設我們下載該文件,將其重命名為 a.js,然后導入內容。 現在您擁有所有可用的數據。

您的代碼未顯示您在哪里進行 API 調用以獲取您的 COVID 數據。 但是假設有一個 function 你稱之為 state 變量selectedCountry 你可以有一個useEffect來響應 state 變量:

import countrycodes from './country-codes-lat-long-alpha3.js'

function App() {

  const [selected, setSelected] = useState("")
  const [center, setCenter] = useState([55, 122]) // some initial state

  // Call this effect whenever selected changes
  // (assuming the value of selected is an alpha3 3 character country code)
  useEffect(() => {
    if (selected){
      fetch(`/v3/covid-19/countries/${selected}`)
        .then(res => {
          // do something with your response data
          // set the map center to the lat lng defined by the reference json
          const countryData = countrycodes.ref_country_codes.filter(country => 
            country.alpha3 === selected
          )[0]
          const countryLatLng = {
            lat: countryData.latitude,
            lng: countryData.longitude,
          }
          setCenter(countryLatLng)
        })
    }
  }, [selected])
  

  return (
    <div>
      <Map center={center} />
      <select onChange={() => setSelected(e.target.value}>
        {a_bunch_of_country_options}
      </select>
    <div>
  )
}

總而言之,您的<select>元素將設置selected的 state 變量。 When selected changes, it triggers the useEffect , which calls your api and does whatever you want with the data. 當數據返回時,效果會檢查參考數據以獲取所選國家/地區的latlng。 setCenter然后將 state 變量center設置為該緯度,該緯度將傳遞給 map。 map 應通過調整其中心來響應。

這只是您將如何實現目標的基本概述。 我所寫的主要問題是它只設置了 map 的中心 可能您正在尋找的效果是設置 map 視圖以顯示國家/地區。 為此,您不僅需要該國家/地區的中心latlng ,還需要所選國家/地區的整個LatLngBounds 獲取這種數據並不是那么簡單。 查看 GIS stack exchange 中有關獲取該數據的線程

假設您能夠獲得一個數據源,該數據源可以根據國家名稱或 2/3 字母代碼為您提供國家范圍。 例如:

[
  {
    "country" : "Albania",
    "alpha2" : "AL",
    "alpha3" : "ALB",
    bounds: [ // made up
      {
        lat: 40.712, 
        lng: -74.227
      },
      {
        lat: 42.712, 
        lng: -72.227
      },  
  }
  ... // all the other countries
]

You can use the same method I described above, but instead of doing 

```javascript
const [center, setCenter] = useState(initialCenter)

你會做的

const [bounds, setBounds] = useState()

然后你可以在你的MapContainer中設置 MapContainer 的bounds屬性:


  const [bounds, setBounds] = useState()

  useEffect(() => {
    if (selected){
      fetch(`/v3/covid-19/countries/${selected}`)
        .then(res => {
          const countryData = countrycodes.ref_country_codes.filter(country => 
            country.alpha3 === selected
          )[0]
          setBounds(country.bounds)
        })
    }
  }, [selected])
  

  return (
    <div>
      <Map center={someInitialCenter} bounds={bounds} />
      ...
    <div>
  )

這將產生這樣的效果:一旦用戶選擇下拉列表,map 就符合國家的邊界,並且國家在框架中。 當然,您需要正確的數據源,並且發現這本身就是一項超出您問題的 scope 的任務。

總之,leaflet 或 react-leaflet 中沒有任何內容可以僅根據國家名稱在 map 上找到正確的坐標。 您需要一種基於名稱對國家坐標進行地理編碼的方法,然后在您的 map 中使用它。 希望這能讓你開始。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM