React Leaflet:动态添加标记

时间:2017-03-16 13:37:46

标签: reactjs leaflet react-leaflet

如何动态地将标记添加到React-Leaflet贴图?

我想在用户点击地图时添加新标记。我无法让它发挥作用。

import React, { Component } from 'react'
import { render } from 'react-dom';
import Control from 'react-leaflet-control';
import { Map, Marker, Popup, TileLayer, ZoomControl, ScaleControl } from 'react-leaflet';
import './Points.scss'

export default class PointsMap extends Component {
  state = {
    lat: 50.2, 
    lng: 30.2,
    zoom: 13,
  }

  handleClick = (e) => {
    this.addMarker();
  }

  addMarker() {

    // A) Following raises error:  
    var marker3 = L.marker([50.5, 30.5]).addTo(this.refs.map);

    // B) With following marker doesn't appear on map:
    const position2 = [50,30];      
    <Marker map={this.refs.map} position={position2} />
  }

  render () {
    const position = [this.state.lat, this.state.lng]
    return (
      <Map ref='map' center={position} zoom={this.state.zoom} onClick=    {this.handleClick} >
        <ZoomControl position="topright" />
        <ScaleControl position="bottomright" />
        <TileLayer
      attribution='&copy <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
      url='http://{s}.tile.osm.org/{z}/{x}/{y}.png'
    />
    <Marker map={this.refs.map} position={position} >
      <Popup>
        <span>A pretty CSS3 popup. <br /> Easily customizable.</span>
      </Popup>
    </Marker>
  </Map>

    )
  }
}

addMarker()中,我尝试添加新标记。我尝试以两种方式做到这一点:

A)

 var marker3 = L.marker([50.5, 30.5]).addTo(this.refs.map);

它引发了错误:

 Uncaught TypeError: map.addLayer is not a function
     at NewClass.addTo (leaflet-src.js:3937)
     at PointsMap.addMarker (Points.js?12f5:54)

B)

const position2 = [50,30];      
    <Marker map={this.refs.map} position={position2} />

它不会添加任何新标记,也不会引发任何错误。

您是否知道如何动态添加/删除标记?

2 个答案:

答案 0 :(得分:16)

为了充分利用 反应 -leaflet,您应该考虑如何以反应生命周期处理两次点击的方式设计地图渲染并显示标记。 React-leaflet为您处理几乎所有的传单gruntwork。

您应该使用组件的状态或道具来跟踪组件显示的标记。因此,您只需呈现新的L.marker组件,而不是手动调用<Marker>

以下是点击地图后添加标记的反应方式:

class SimpleExample extends React.Component {
  constructor() {
    super();
    this.state = {
      markers: [[51.505, -0.09]]
    };
  }

  addMarker = (e) => {
    const {markers} = this.state
    markers.push(e.latlng)
    this.setState({markers})
  }

  render() {
    return (
      <Map 
        center={[51.505, -0.09]} 
        onClick={this.addMarker}
        zoom={13} 
        >
        <TileLayer
          attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
          url='http://{s}.tile.osm.org/{z}/{x}/{y}.png'
        />
        {this.state.markers.map((position, idx) => 
          <Marker key={`marker-${idx}`} position={position}>
          <Popup>
            <span>A pretty CSS3 popup. <br/> Easily customizable.</span>
          </Popup>
        </Marker>
        )}
      </Map>
    );
  }
}

这是一个小伙伴:https://jsfiddle.net/q2v7t59h/413/

答案 1 :(得分:1)

我使用了下面的代码,它可以成功运行。在此代码中,用户只能在一个位置添加一个标记,并且可以更改:

请注意导入leaflet.css文件

有时,添加传单文件后,有关图像加载的两个错误。要解决这些错误,请在导入部分中导入marker-icon.png和marker-shadow.png,然后在下面定义L.Marker.prototype.options.icon链接。

如果未显示地图,则将高度和宽度(样式= {{宽度:'100%',高度:'400px'}})添加为样式标签 < / p>

import React from 'react';
import L from 'leaflet';
import 'leaflet/dist/leaflet.css';
import { Map, TileLayer, Marker, Popup } from 'react-leaflet';
import icon from 'leaflet/dist/images/marker-icon.png';
import iconShadow from 'leaflet/dist/images/marker-shadow.png';

class OSMap extends React.Component {
    constructor() {
        super();
        this.state = {
            markers: [[35.6892, 51.3890]],
        };
    }

    addMarker = (e) => {
        const { markers } = this.state;
        markers.pop();
        markers.push(e.latlng);
        this.setState({ markers });
    }

    render() {
        let DefaultIcon = L.icon({
            iconUrl: icon,
            shadowUrl: iconShadow
        });
        L.Marker.prototype.options.icon = DefaultIcon;

        return (
            <div>
                <Map
                    center={[35.6892, 51.3890]}
                    onClick={this.addMarker}
                    zoom={13}
                    maxZoom={18}
                    minZoom={5}   
                    style={{width: '100%',height: '400px'}}
                >
                    <TileLayer
                        attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
                        url='http://{s}.tile.osm.org/{z}/{x}/{y}.png'
                    />
                    {this.state.markers.map((position, idx) =>
                        <Marker key={`marker-${idx}`} position={position}></Marker>
                    )}
                </Map>
            </div>
        );
    }
}

export default OSMap;