如何在Leaflet中绘制带有初始点的折线

时间:2017-10-20 09:40:05

标签: leaflet leaflet.draw

我正在使用Leaflet.draw的自定义折线抽屉

let polylineDrawer = new L.Draw.Polyline(map, {})

polylineDrawer.enable()

我需要以编程方式将起点添加到折线

我试过调用addVertex的{​​{1}}。看起来它不适用于L.Draw.Polyline或其他东西的自定义折线抽屉原因...试图改变来源,没有结果。

启用抽屉后,还尝试在地图上触发addHooks。像这样:

click

也不起作用

编辑:实际上,let point = new L.LatLng(x, y) map.fireEvent('click', { latlng: point, layerPoint: map.latLngToLayerPoint(point), containerPoint: map.latLngToContainerPoint(point), }) 可以使用自定义折线。它“无效”,因为我在我的函数中传递了错误的参数。不知怎的,我错过了。

1 个答案:

答案 0 :(得分:2)

在抽屉对象上使用addVertex可让您为线路添加起点:

var polylineDrawer = new L.Draw.Polyline(map, {})
polylineDrawer.enable();

var latlng = L.latLng(48.8583736, 2.2922926);
polylineDrawer.addVertex(latlng);

和演示

var style = {
    stroke: true,
    color: 'red',
    weight: 4,
    opacity: 0.5
};
var map = L.map(document.getElementById('map')).setView([48.8583736, 2.2922926], 15);

L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
    attribution: '&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map);

var drawnItems = new L.geoJson(null, {style: style}).addTo(map);

map.on(L.Draw.Event.CREATED, function (event) {
    var layer = event.layer;
    drawnItems.addLayer(layer);
});

var polylineDrawer = new L.Draw.Polyline(map, {})
polylineDrawer.enable();

var latlng = L.latLng(48.8583736, 2.2922926);
polylineDrawer.addVertex(latlng);
html, body {
  height: 100%;
  margin: 0;
}
#map {
  width: 100%;
  height: 100%;
}
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.2.0/dist/leaflet.css" integrity="sha512-M2wvCLH6DSRazYeZRIm1JnYyh22purTM+FDB5CsyxtQJYeKq83arPe5wgbNmcFXGqiSH2XR8dT/fJISVA1r/zQ==" crossorigin=""/>
    <script src="https://unpkg.com/leaflet@1.2.0/dist/leaflet.js" integrity="sha512-lInM/apFSqyy1o6s89K4iQUKg6ppXEgsVxT35HbzUupEVRh2Eu9Wdl4tHj7dZO0s1uvplcYGmt3498TtHq+log==" crossorigin=""></script>
    
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/leaflet.draw/0.4.12/leaflet.draw.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet.draw/0.4.12/leaflet.draw.js"></script>

<div id='map'></div>