从 LeafletDraw 到 GeoJSON 的多边形

Polygon from LeafletDraw to GeoJSON

这是我第一次尝试使用传单使用 javascript 和 GeoJSON。 到目前为止,我得到了所需的地图和 leaflet.draw 插件,我可以绘制一个形状并将其显示在我的屏幕上。 我试图将这个形状写入我想在 R 中使用的 GeoJSON。 因此,我使用提出的想法 here 来创建 GeoJSON 字符串。我认为我需要的信息存储在变量 shape_for_db 中。 但是,在 Firefox 中使用 Firebug 我找不到这个变量。 我在这里弄错了吗? 这是我正在使用的脚本:

<html>
<head>
  <title>A Leaflet map!</title>
  <link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet/v1.0.0-rc.1/leaflet.css" />
  <link rel="stylesheet" href="http://leaflet.github.io/Leaflet.draw/leaflet.draw.css" />
  <script src="http://cdn.leafletjs.com/leaflet/v1.0.0-rc.1/leaflet.js"></script>
  <script src="jquery-2.1.1.min.js"></script>
  <script src="http://leaflet.github.io/Leaflet.draw/leaflet.draw.js"></script>
  <style>
    #map{ width: 100%; height: 100%; }
  </style>
</head>

<body>


  <div id="map"></div>

  <script>

  // base map
  var map = L.map('map').setView([51.25,10.57], 8);

  // load a tile layer
 L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png',
    {
      attribution: 'Tiles by: OpenStreetMaps',
      maxZoom: 17,
      minZoom: 5
    }).addTo(map);

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

// Initialise the draw control and pass it the FeatureGroup of editable layers
        var drawnItems = new L.FeatureGroup();
        map.addLayer(drawnItems);

        var drawControl = new L.Control.Draw({
            edit: {
                featureGroup: drawnItems
            }
        });
        map.addControl(drawControl);

        map.on('draw:created', function (e) {
            var type = e.layerType,
                layer = e.layer;
            drawnItems.addLayer(layer);
        });
// Shape to GeoJSON
map.on('draw:created', function (e) {
  var type = e.layerType;
  var layer = e.layer;
  var shape = layer.toGeoJSON()
  var shape_for_db = JSON.stringify(shape);
});

  </script>
</body>
</html>

shape_for_db 的作用域在 draw-created 的第二个侦听器中。如果你这样做是为了一次性 experimental/playing 方法并且想使用你的开发 console/Firebug,你可以放在 window.shape_for_db 上。或者在监听器外设置var shape_for_db