如何动态添加标记到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='© <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} />
它不会添加任何新标记,也不会引发任何错误。
您有没有想过如何动态添加/删除标记?