React传单,是地名,不是坐标

问题描述 投票:0回答:2

是否可以在 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;


javascript reactjs leaflet geocoding react-leaflet
2个回答
4
投票

您需要应用地理编码。一种解决方案是使用

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>

演示


1
投票

您需要首先对地名进行地理查找,就像提到的评论之一一样。这是一个使用 javascript 的小例子。我想你可以在 React 中实现它。我将使用 Leaflet 库使用从 Nominatim 查询中获得的纬度和经度来绘制地图。

<div id="map" class="map"></div>
<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>
© www.soinside.com 2019 - 2024. All rights reserved.