如何使用鼠标和leaflet.js绘制折线

时间:2017-03-21 22:48:17

标签: leaflet

我想用传单在地图上绘制折线。我想申请的基本手势是:

  • 用户点击并按住鼠标按钮 - >定义第一个标记。如果用户按住鼠标按钮并移动鼠标,则会显示相应的“橡皮筋”。

  • 用户释放鼠标按钮 - >第二个标记添加到地图中,2个标记通过一条线链接。

  • 从第二个标记开始,用户可以使用与上面相同的过程继续构建第二行。

最终结果应该是由折线连接的坐标/标记集。

1 个答案:

答案 0 :(得分:5)

正如 Julien V IvanSanchez 所说,你可以实现一些类似绘画的plugins

以下示例:

您可以看到Leaflet.draw插件的使用情况。希望它有所帮助:)



// center of the map
var center = [46.165164, 15.750443];

// Create the map
var map = L.map('map').setView(center,15);

// Set up the OSM layer
L.tileLayer(
  'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
    attribution: 'Data © <a href="http://osm.org/copyright">OpenStreetMap</a>',
    maxZoom: 18
  }).addTo(map);



// Initialise the FeatureGroup to store editable layers
var editableLayers = new L.FeatureGroup();
map.addLayer(editableLayers);

var options = {
  position: 'topleft',
  draw: {
    polygon: {
      allowIntersection: false, // Restricts shapes to simple polygons
      drawError: {
        color: '#e1e100', // Color the shape will turn when intersects
        message: '<strong>Oh snap!<strong> you can\'t draw that!' // Message that will show when intersect
      },
      shapeOptions: {
        color: '#97009c'
      }
    },
    polyline: {
    	shapeOptions: {
        color: '#f357a1',
        weight: 10
          }
    },
    // disable toolbar item by setting it to false
    polyline: true,
    circle: true, // Turns off this drawing tool
    polygon: true,
    marker: true,
    rectangle: true,
  },
  edit: {
    featureGroup: editableLayers, //REQUIRED!!
    remove: true
  }
};

// Initialise the draw control and pass it the FeatureGroup of editable layers
var drawControl = new L.Control.Draw(options);
map.addControl(drawControl);

var editableLayers = new L.FeatureGroup();
map.addLayer(editableLayers);

map.on('draw:created', function(e) {
  var type = e.layerType,
    layer = e.layer;

  if (type === 'polyline') {
    layer.bindPopup('A polyline!');
  } else if ( type === 'polygon') {
  	layer.bindPopup('A polygon!');
  } else if (type === 'marker') 
  {layer.bindPopup('marker!');}
  else if (type === 'circle') 
  {layer.bindPopup('A circle!');}
   else if (type === 'rectangle') 
  {layer.bindPopup('A rectangle!');}


  editableLayers.addLayer(layer);
});
&#13;
html, body, #map { margin: 0; height: 100%; width: 100%; }
&#13;
<!DOCTYPE html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.0.0-beta.2.rc.2/leaflet.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.0.0-beta.2.rc.2/leaflet.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet.draw/0.2.3/leaflet.draw.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/leaflet.draw/0.2.3/leaflet.draw.css" rel="stylesheet" />
  <meta charset="utf-8">
  <title>TEST</title>

</head>
<body>
  <div id='map'></div>
</body>
</html>
&#13;
&#13;
&#13;