使用leaflet-geosearch添加搜索栏

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

我正在尝试使用leaflet-geosearch将搜索栏添加到React中的Leaflet Map(react-leaflet

import { Map, TileLayer, MapControl } from 'react-leaflet'
import { GeoSearchControl, OpenStreetMapProvider } from 'leaflet-geosearch'

class Search extends MapControl {
  createLeafletElement() {
    return GeoSearchControl({
      provider: new OpenStreetMapProvider(),
      style: 'bar'
    })
  }
}

...

export class MapContainer extends Component {
  render() {
    return (
      <div>
        <Map
          ref={m => { this.leafletMap = m; }}
          center={this.state.position}
          zoom={this.state.zoom}
        >
          <TileLayer
            attribution={tilesAttr}
            url={tilesUrl}
          />
          <Search />
        </Map>
      </div>
    )
  }
}

当我运行它时,我得到一个TypeError:

TypeError:无法读取未定义的Search.componentDidMount的属性“map”

};

MapControl.prototype.componentDidMount = function componentDidMount() {
-> this.leafletElement.addTo(this.props.leaflet.map);
};

MapControl.prototype.componentDidUpdate = function componentDidUpdate(prevProps) {

有没有人成功在他们的传单地图中添加搜索栏?

javascript reactjs maps react-leaflet
3个回答
1
投票

const GeoSearch = withLeaflet(Search)


0
投票

使用“withLeaflet”

这里回答https://github.com/smeijer/leaflet-geosearch/issues/167#issuecomment-403107336

在这里https://react-leaflet.js.org/docs/en/custom-components.html

*import ...unrelated imports*
import { Map, TileLayer, Marker, MapControl, Popup, ZoomControl, withLeaflet } from 'react-leaflet';
import { GeoSearchControl, OpenStreetMapProvider } from 'leaflet-geosearch';

class SearchMap extends MapControl {

    createLeafletElement() {
      return GeoSearchControl({
        provider: new OpenStreetMapProvider(),
        style: 'bar',
        showMarker: true,
        showPopup: false,
        autoClose: true,
        retainZoomLevel: false,
        animateZoom: true,
        keepResult: false,
        searchLabel: 'search'
      });
    }
}


class MapContainer extends React.Component {
  render() {
    const SearchBar = withLeaflet(SearchMap);  {/*  this part is needed */}
    return(
      <Map>
        <SearchBar />
        {/* rest of your map elements */}
      </Map>
    );
  }
}

export default MapContainer;

0
投票

变更清单:

  • withLeaflet HOC包装你的组件,以确保在加载地图后控件被初始化,例如export default withLeaflet(GeoSearch);
  • 控件需要明确地添加到地图中,例如在componentDidMount函数中
  • 需要引用leaflet-geosearch css,例如通过public/index.html

class Search extends MapControl {

  createLeafletElement(opts) {
    const provider = new OpenStreetMapProvider();
    const searchControl = new GeoSearchControl({
      provider: provider,
      //position: "topleft",
      style: "bar"
    });

    return searchControl;
  }

  componentDidMount() {
    const { map } = this.props.leaflet;
    map.addControl(this.leafletElement);
  }
}

这是a demo

© www.soinside.com 2019 - 2024. All rights reserved.