如果我这样做:
function app(e) {
var $tar = e.target.getLatLngs();
alert($tar);
}
function onEachFeature(feature, layer) {
layer.on({
click: app
});
}
我收到警告:
LatLng(19.08348, -155.54211),
LatLng(18.91619, -155.68817),
LatLng(19.05939, -155.93665),
LatLng(19.33888, -155.90806),
LatLng(19.70294, -156.07347),
LatLng(19.81422...
但我需要获得如下格式:
[19.08348, -155.54211],
[18.91619, -155.68817],
[19.05939, -155.93665],
[19.33888, -155.90806],
[19.70294, -156.07347],
[19.81422...
答案 0 :(得分:3)
如果只是格式化问题,那么您可以这样做:
function app(e) {
var $tar = e.target.getLatLngs();
var formattedTar = $tar.map(function(obj) { // Loops through each Latlng object
return [obj.lat, obj.lng]; // and returns an array instead
});
console.log(formattedTar);
}
<强>更新强>
如果要打印数组,请尝试以下方法:
alert(JSON.stringify(formattedTar));
演示: JSFiddle
答案 1 :(得分:2)
您可以遍历元素数组并将它们推入一个新的数组(具有所需的格式)。请参阅以下一种方式:
根据聊天更新
$(function() {
// Assuming a whole bunch of latlngs
var target = [];
// these would come from your original e.target.getLatLngs();
// I am just making some up for this demo
for (i = 0; i < 10; i++) {
var latlng = L.latLng(i, i);
target.push(latlng);
}
alert(target);
/* you only need the code from here on, right after your own alert(...) */
// will hold the newly formatted values
var newLatLng = [];
// convert to new format
/** UPDATED Based on chat comments */
$.each(target, function(index, value) {
if( value.length ){
$.each(value, function(ind, val) {
var latLngArr = [val.lat, val.lng];
newLatLng.push(latLngArr);
});
}else{
var latLngArray = [value.lat, value.lng];
newLatLng.push(latLngArray);
}
});
console.log(newLatLng);
alert(JSON.stringify(newLatLng));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://unpkg.com/leaflet@1.0.1/dist/leaflet.js"></script>