react-leaflet <geojson> pointToLayer选项可更改图标

时间:2017-02-24 11:40:23

标签: react-leaflet

我目前正在尝试学习反应,我想使用传单地图(反应传单)。

我有两个(Point,Polygon)GeoJson对象我想要显示,这是有效的,但我想替换默认的标记图标。

传单文档http://leafletjs.com/examples/geojson/告诉我使用pointToLayer选项。

代码:

onEachFeaturePoint,onEachfeaturePolygon,pointToLayer

onEachFeaturePoint(feature, layer) {
  console.log('feature: ', feature);
  console.log('layer: ', layer);
  layer.on({
    'click': function (e) {
       console.log('e: ', e);
       console.log('click');
     }
  })
}

onEachFeaturePolygon(feature, layer) {
  console.log('feature: ', feature);
  console.log('layer: ', layer);
  layer.on({
    'click': function (e) {
       console.log('e: ', e);
       console.log('click');
     }
  })
}

pointToLayer(feature, latlng) {
  console.log('--- Point to layer');
  console.log('feature: ', feature);
  console.log('latlng: ', latlng);
  return <CircleMarker center={latlng} />;
}

呈现

render() {
  const center = [9.4921875, 51.83577752045248];

  return (
    <Map center={center} zoom={1}>
      <GeoJSON ref='marker1' data={this.state.point} onEachFeature={this.onEachFeaturePoint.bind(this)} pointToLayer={this.pointToLayer.bind(this)} />
      <GeoJSON ref='polygon1' data={this.state.polygon} onEachFeature={this.onEachFeaturePolygon.bind(this)} />
    </Map>
  )
}

如果我保留pointToLayer={this.pointToLayer.bind(this)},它将停止处理以下错误:

Uncaught TypeError: layer.on is not a function
    at CustomMarker.onEachFeaturePoint (MapDemo.js:73)
    at NewClass.addData (leaflet-src.js:10455)
    at NewClass.addData (leaflet-src.js:10435)
    at NewClass.initialize (leaflet-src.js:10420)
    at new NewClass (leaflet-src.js:310)
    at L.geoJSON (leaflet-src.js:10732)

我无法弄清楚错误发生的原因,也许有人知道如何解决这个问题或帮助我理解我所犯的错误。

修改:在return <CirleMarker />函数中将return L.circleMarker()替换为pointToLayer,即可让它发挥作用。

2 个答案:

答案 0 :(得分:4)

return <CirleMarker />替换为return L.circleMarker()函数中的pointToLayer,我就可以使用它。

import L from 'leaflet';

...

pointToLayer(feature, latlng) {
   return L.circleMarker(latlng, null); // Change marker to circle
   // return L.marker(latlng, { icon: {}}); // Change the icon to a custom icon
}

答案 1 :(得分:0)

我认为如果您只是尝试显示自定义图标,最好不要尝试使用Marker组件而不是GeoJSON组件。

<Map center={center} zoom={1}>
  <Marker
    icon={homeIcon}
    key='marker1'
    onClick={this._handleClick}
    position={leafletLatLng}
    />
</Map>

...

const homeIconUrl = 'home-2.png'
const homeIcon = icon({
  iconUrl: homeIconUrl,
  iconSize: [32, 37],
  iconAnchor: [16, 37]
})