我正在使用leafletFreeDraw我也尝试关注 this SO question
通过以下内容,我得到了经度/纬度:
freeDraw.on('markers', function (event) {
// Listen for any markers added, removed or edited,
// and then output the lat lng boundaries.
console.log('LatLngs:', event.latLngs, 'Polygons:', freeDraw.size());
});
我得到的控制台输出如下:
Array[1]
0
:
Array[20]
0
:
L.LatLng
lat
:
51.51435127755928
lng
:
-0.08651733398437501
__proto__
:
Object
1
:
L.LatLng
lat
:
51.51349664501128
lng
:
-0.08505821228027345
__proto__
:
Object
2
:
L.LatLng
有没有一种方法可以附加每个坐标并在控制台中输出如下所示的内容?
var states = [{
"type": "LineString",
"coordinates": [[-100, 40], [-105, 45], [-110, 55]]
}, {
"type": "LineString",
"coordinates": [[-105, 40], [-110, 45], [-115, 55]]
}];
我什至可以在控制台中以正确的格式打印第一组坐标,然后我将手动复制/粘贴到我的 geojson 文件。
"coordinates": [[-105, 40], [-110, 45], [-115, 55]]
最佳答案
您可以循环遍历从绘图创建的坐标,然后将其作为对象推送到全局数组(容器)。
var states = [];
freeDraw.on('markers', function (event) {
// create coordinates object
var polyObj = event.latLngs[0].map(function(o){
return [o.lat, o.lng];
});
// Push new object to states
states.push({
"type": "LineString",
"coordinates":polyObj
});
});
var LAT_LNG = [51.505, -0.09];
var TILE_URL = 'https://cartodb-basemaps-a.global.ssl.fastly.net/light_all/{z}/{x}/{y}@2x.png';
var map = new L.Map(document.querySelector('section.map'), { doubleClickZoom: false }).setView(LAT_LNG, 14);
L.tileLayer(TILE_URL).addTo(map);
var freeDraw = new FreeDraw({ mode: FreeDraw.ALL });
map.addLayer(freeDraw);
// All drawings container.
var states = [];
freeDraw.on('markers', function (event) {
// create coordinates object
var polyObj = event.latLngs[0].map(function(o){
return [o.lat, o.lng];
});
// Push new object to states
states.push({
"type": "LineString",
"coordinates":polyObj
});
console.log(states);
});
body {
margin:0;
}
.map {
width: 100%;
height: 70vh;
}
.as-console-wrapper {
height:30vh;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.0.2/leaflet-src.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.0.2/leaflet.css">
<script src="https://rawgit.com/Wildhoney/Leaflet.FreeDraw/master/dist/leaflet-freedraw.web.js"></script>
<section class="map"></section>
关于javascript - 如何以控制台geojson格式纬度/经度输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41101745/