【问题标题】:React-Leaflet Map relocation with using Places Autocomplete使用 Places Autocomplete 进行 React-Leaflet Map 重定位
【发布时间】:2021-03-25 13:17:20
【问题描述】:

我的 react 应用程序使用 react Leaflet 创建了地图:

import {MapContainer TileLayer } from "react-leaflet";
import React from "react";

export default function App() {
return (
<MapContainer
                center={[49.1951, 16.6068]}
                zoom={13}
                scrollWheelZoom={false}
            >
<TileLayer
                attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
                url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
            />

</MapContainer>

<Search/>
);}

另外,我的 App 有使用 Places 自动完成功能的 Search 组件,我可以从中获取新坐标,这里是:https://github.com/AlonaVa/searchApp/blob/main/search.js

我的任务是将我的地图从搜索组件 (latLng) 重新定位到所选位置。 谢谢你的建议。

【问题讨论】:

    标签: javascript reactjs google-api leaflet react-leaflet


    【解决方案1】:

    在 App comp 中创建地图变量和坐标变量。

    然后将坐标设置器传递给 Search comp。一旦坐标变化触发应用上的地图视图变化

    export default function App() {
      const [map, setMap] = useState(null);
      const [coordinates, setCoordinates] = useState({ lat: "", lng: "" });
    
      useEffect(() => {
        if (map && coordinates.lat && coordinates.lng) map.setView(coordinates);
      }, [map, coordinates]);
    
      return (
        <>
          <MapContainer
            center={[49.1951, 16.6068]}
            zoom={13}
            scrollWheelZoom={false}
            style={{ height: "100vh" }}
            whenCreated={setMap}
          >
            <TileLayer
              attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
              url='https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png'
            />
          </MapContainer>
          <Search setCoordinates={setCoordinates} />
        </>
      );
    }
    

    在搜索组合中,如果我们考虑到该值是一​​个包含latlng 的对象,则使用坐标设置器来更改坐标值:

     export default function Search({ coordinates, setCoordinates }) {
          const [address, setAddress] = useState("");
        
          const handleSelect = async (value) => {
            const results = await geocodeByAddress(value);
            latLng = await getLatLng(results[0]);
            setAddress(value);
            setCoordinates({ lat: value.lat, lng: value.lng });
          };
       ...
     }
    

    【讨论】:

    • 谢谢,看起来不错,但我的代码有点复杂,我已经在 MapContainer 中声明了 whenCreated:whenCreated={(map) => setBbox(map.getBounds())}我可以再添加一个吗?
    • 您可以这样做以将两者结合起来:whenCreated={(map) =&gt; { setBbox(map.getBounds()); setMap(map) }}
    • 好主意,非常感谢您的帮助!
    猜你喜欢
    • 2018-03-22
    • 1970-01-01
    • 2017-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-19
    相关资源
    最近更新 更多