如何在javascript中向json添加值?

问题描述 投票:-3回答:1

[我正在为无人机课程创建地图,我正在使用mapbox gl js进行绘制,我能够创建航点并获取坐标,但是我尝试使用带有ID课程,坐标等的json创建多个课程。

有人可以帮我谢谢。

此功能可帮助我创建课程:

   map.on('draw.modechange', function(e) { 
    map.on('click', function(e) { 
        if (draw.getMode() == 'draw_polygon') {

            lon = e.lngLat.lng;
            lat = e.lngLat.lat;

            gps[nbPoints][0] = lon;
            gps[nbPoints][1] = lat; 

            nbPoints = nbPoints+1;

            console.log("Longitude : "+lon + " - " + "Latitude : "+lat);
        };
    });
});

我使用此功能将数据发送到服务器:

$("#vol").click(function(e)
    {   
        for (var i = 0 ; i < nbPoints; i++) {

            posLon = gps[i][0];  
            posLat = gps[i][1];

            lon = posLon;
            lat = posLat;           

      }

            const obj ={
                        "numero":"3",
                        "r_name":"parcours2",
                        "speed":"6",
                        "actionFinished":"home",
                        "coordinate":
                            {
                                "waypoint":[
                                            {
                                            "longitude":lon,
                                            "latitude":lat,
                                            "EnablePicture":"false",
                                            "PositionBatiment":"gauche",
                                            "altitude":"30"
                                            }
                                        ]
                                    }
                                }   

             const jsonString = JSON.stringify(obj);
             const xhr = new XMLHttpRequest();

             xhr.open("POST", "Api.php", true);
             xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
             xhr.send(jsonString); 

             console.log(jsonString);       

});
javascript php json draw mapbox-gl-js
1个回答
0
投票
也许是这样?

$("#vol").click(function (e) { const obj = { "numero": "3", "r_name": "parcours2", "speed": "6", "actionFinished": "home", "coordinate": { "waypoint": [] } } for (var i = 0; i < nbPoints; i++) { obj.coordinate.waypoint.push( { "longitude": gps[i][0], "latitude": gps[i][1], "EnablePicture": "false", "PositionBatiment": "gauche", "altitude": "30" } ) } const jsonString = JSON.stringify(obj); const xhr = new XMLHttpRequest(); xhr.open("POST", "Api.php", true); xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8'); xhr.send(jsonString); console.log(jsonString); });

如果我了解您要正确执行的操作
© www.soinside.com 2019 - 2024. All rights reserved.