簡體   English   中英

反應傳單,地名,而不是坐標

[英]React leaflet, the name of the place, not the coordinates

是否可以在 React Leaflet 中渲染地圖並給出地點名稱而不是地圖坐標? 我希望輸入地名,而不是給出地點的坐標,例如。 “聖詹姆斯公園”或“巴塞羅那-加泰羅尼亞賽道”

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

function MyMap() {
  const position = [53.35, 18.8];
  return (
    <MapContainer
      className="map"
      center={position}
      zoom={6}
      style={{ height: 500, width: "100%" }}>
      <TileLayer
        attribution='&amp;copy <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
        url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"/>
    </MapContainer>
  );
}
export default MyMap;


您需要應用地理編碼。 一種解決方案是使用esri-leaflet-geocoder庫。

通過npm i esri-leaflet-geocoder安裝它並創建一個Geocoder組件,該組件將獲取地址並將地址轉換為坐標后將地圖視圖設置為所選位置。

    function Geocoder({ address }) {
        const map = useMap();
    
        ELG.geocode()
          .text(address)
          .run((err, results, response) => {
            console.log(results.results[0].latlng);
            const { lat, lng } = results.results[0].latlng;
            map.setView([lat, lng], 12);
          });
    
        return null;
      }

像這樣使用它:

    <MapContainer
          className="map"
          center={position}
          zoom={6}
        >...
          <Geocoder address="Circuit de Barcelona-Catalunya" />
      </MapContainer>

演示

您需要先像提到的評論之一一樣使用地名進行地理查找。 這是一個使用 javascript 的小例子。 我猜你可以在 React 中實現它。 我將使用 Leaflet 庫使用從 Nominatim 查詢中獲得的經緯度繪制地圖。

<div id="map" class="map">
<script>
... // getting user input
// incoming user address from input should be encoded to be used in url
const encodedAddress = encodeURIComponent(addressComingFromInput);
const nominatimURL = 'https://nominatim.openstreetmap.org/?addressDetails=1&q=' + encodedAddress + 'format=json&limit=1';
// fetch lat and long and use it with leaflet
fetch(nominatimURL)
   .then(response => response.json())
   .then(data => {
       const lat = data[0].lat;
       const long = data[0].lon;
       const osmTileUrl = 'https://{s}.tile.osm.org/{z}/{x}/{y}.png';
       let map = L.map('map').setView([lat, long], zoomLevel);
       L.tileLayer(osmTileUrl, {
           attribution: '&copy; <a href="https://osm.org/copyright">OpenStreetMap</a> contributors'
                            }).addTo(map);
      let marker = L.marker([lat, long]).addTo(map);
      marker.bindPopup(userAddress).openPopup();
   });
</script>

暫無
暫無

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

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