使用Leaflet-geosearch添加Searchbar

时间:2018-07-12 16:15:50

标签: javascript reactjs maps react-leaflet

我正在尝试使用CounterConsumer.consumeCounter()将搜索栏添加到React(leaflet-geosearch)的传单地图中

react-leaflet

运行此命令时出现TypeError:

  

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

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>
    )
  }
}

有人成功地在其传单地图中添加了搜索栏吗?

3 个答案:

答案 0 :(得分:1)


const GeoSearch = withLeaflet(Search)


答案 1 :(得分: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

答案 2 :(得分:0)