0

我正在使用带有反应传单的传单。启用地理定位时,OverpassLayer 正在工作。当地理定位因为我在本地主机上而被阻止时,应用程序甚至没有进入 OverpassLayer 组件。

应用程序.js

import OverpassLayer from './OverpassLayer'
class App extends React.Component {
  state = {
    zoom: 16,
    position: {
      lat: 51.505,
      lng: -0.09,
    },
    mapKey: Math.random(),
    overpassLayerKey: Math.random()
  }

  componentDidMount () {
    //center map on user's current position
    this.handleGeolocation()
    this.refreshOverpassLayer()
  }

  handleGeolocation = () => {
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(
        (position) => {
          this.setState({
            position: {
              lat: position.coords.latitude,
              lng: position.coords.longitude,
            },
            mapKey: Math.random()
          })
        }, (err) => {
          console.log("Geolocation did not work: " + err)
        }
      )
    } else {
      console.log("Geolocation did not work.  Navigator.geolocation falsy")
    }
  }

  refreshOverpassLayer = () => {
    this.setState({
      overpassLayerKey: Math.random()
    })
  }

  render () {
    return (
        <Map 
          style={{height: "100vh", width: "100vw"}}
          zoom={this.state.zoom}
          center={[this.state.position.lat, this.state.position.lng]}
          key={this.state.mapKey}
          ref='map'
        >
          <TileLayer
            url='https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png'
            attribution='&copy; <a href="http://osm.org/<copyright">OpenStreetMap</a> contributors'
          />
          <OverpassLayer
            key={this.state.overpassLayerKey}            
          />
        </Map>
    )
  }
}

OverpassLayer.js

import {LayerGroup} from 'react-leaflet'
import L from 'leaflet'
import OverPassLayer from 'leaflet-overpass-layer'

export default class OverpassLayer extends LayerGroup {
  componentWillReceiveProps(nextProps) {
    console.log(nextProps.key)
    console.log('OverpassLayer receiving props')
    const query = '('
      + 'node["amenity"]({{bbox}});'
      + 'way["amenity"]({{bbox}});'
      + 'relation["amenity"]({{bbox}});'
      + ');'
      + 'out body;'
      + '>;'
      + 'out skel qt;'

    const opl = new L.OverPassLayer({
      'query': query,
      'endPoint': 'https://overpass-api.de/api/',
    })
    nextProps.map.addLayer(opl)
  }
}
4

1 回答 1

0

问题是 componentWillReceiveProps 在第一次渲染时不会触发。我还必须在构造函数中添加图层。

于 2016-11-24T01:57:34.533 回答