Leaflet插件仅在启用地理定位时才起作用

时间:2016-11-24 00:17:52

标签: javascript reactjs ecmascript-6 leaflet react-leaflet

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

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

1 个答案:

答案 0 :(得分:0)

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