<script>
    //klik kanan begin
    map.on('contextmenu', function(e) {
        $("#map-create").remove();
        $("#map-create-jalan").remove();
        $("#map-create-admin").remove();

        // document.getElementsByClassName('leaflet-popup-content').style.width = "550px";
        // <div class="form-group">
        //     <label class="col-lg-2 control-label" style="margin-top:10px">Image</label>
        //     <div class="col-lg-9" style="margin-top:10px">
        //         <input type="file" id="filesb" name="images[]" multiple accept="image/jpg,image/png,image/jpeg,image/gif">
        //         <input style="display:none;" id="gambarsb" type="text" class="form-control" value="" required>
        //     </div>
        // </div>
        var popup = L.popup()
            .setLatLng(e.latlng)
            .setContent(`
            
            <div class="tab-pane has-padding" id="panel-tab2">
                <div class="tab-pane" id="bottom-justified-data">
                    <div class="tabbable" style="width: 450px!important;">
                        <ul class="nav nav-tabs nav-tabs-bottom nav-justified">
                            <li onclick="changetabs(this)" class="active"><a href="#bangunan" data-toggle="tab" id="c_bangunan">Bangunan</a></li>
                            <li onclick="changetabs(this)"><a href=".koordinatjalan" data-toggle="tab" id="c_jalan">Jalan</a></li>
                            <li onclick="changetabs(this)"><a href=".point-insert" data-toggle="tab" id="point-insert">Point</a></li>
                        </ul>
            
                        <div class="tab-content">
                            <div class="tab-pane active" id="bangunan">
                                <div class="tabbable" style="overflow:auto;height:450px!important;width: 450px!important;">
                                    <ul class="nav nav-tabs nav-tabs-bottom nav-justified">
                                        <li onclick="changetabs(this)" class="active"><a href="#right-tab2-feas-upl" data-toggle="tab">Koordinat</a></li>
                                        <li onclick="changetabs(this)"><a href="#left-tab1-feas-upl" data-toggle="tab">Informasi Bangunan</a></li>
                                    </ul>
            
                                    <div class="tab-content">
                                        <div class="tab-pane active" id="right-tab2-feas-upl">
                                            <div class="form-group">
                                                <div id="map-create" style="height: 250px;">
                                                    <input type="button" id="create" value="Create" style="z-index: 1000;position:relative;">
                                                </div>
                                                
                                            </div>
                                        </div>
                                        <div class="tab-pane" id="left-tab1-feas-upl">
                                            <div class="row" style="margin-top: 15px;">
                                                <div class="form-group">
                                                    <label class="col-lg-3 control-label lbl-top" >Nama Bangunan</label>
                                                    <div class="col-lg-9">
                                                        <input id="name_create" type="text" class="form-control" value="" required>
                                                    </div>
                                                </div>
                                            </div>

                                            <div class="row" style="margin-top: 15px;">
                                                <div class="form-group">
                                                    <label class="col-lg-3 control-label lbl-top" >Jenis Bangunan</label>
                                                    <div class="col-lg-9">
                                                        <select style="border-bottom: 1px solid rgb(83, 83, 83) !important;" id="tipe_point_b" data-placeholder="select point.." class="select-size-md">
                                                            <option value="null" selected disabled>-- Pilih Jenis Point --</option>
                                                            <option value="bangunan">Bangunan Biasa</option>
                                                            <option value="kantor_administrasi">Kantor Administrasi</option>
                                                            <option value="layanan_kesehatan">Layanan Kesehatan</option>
                                                            <option value="puskesmas">Puskesmas</option>
                                                            <option value="rumah_sakit">Rumah Sakit</option>
                                                            <option value="sarana_ibadah">Sarana Ibadah</option>
                                                            <option value="sarana_pendidikan">Sarana Pendidikan</option>
                                                            <option value="spbu">SPBU</option>
                                                            <option value="stasiun">Stasiun</option>
                                                            <option value="terminal_bus">Terminal Bus</option>
                                                            <option value="cagar_budaya">Cagar Budaya dan Tempat Wisata</option>
                                                            <option value="gardu_listrik">Gardu Listrik</option>
                                                        </select>
                                                    </div>
                                                </div>
                                            </div>

                                            <div class="row" style="margin-top: 15px;">
                                                <div class="form-group">
                                                    <label class="col-lg-3 control-label lbl-top" >Tipe Bangunan</label>
                                                    <div class="col-lg-9">
                                                        <select style="border-bottom: 1px solid rgb(83, 83, 83) !important;width: 220px;" id="tipe_point_2_b" data-placeholder="select point.." class="select-size-md">
                                                            <option value="null" selected disabled>-- Pilih Tipe Point --</option>
                                                        </select>
                                                    </div>
                                                </div>
                                            </div>

                                            <div class="row" style="margin-top: 15px;">
                                                <div class="form-group">
                                                    <label class="col-lg-3 control-label lbl-top" >Nama Point</label>
                                                    <div class="col-lg-9">
                                                        <select style="border-bottom: 1px solid rgb(83, 83, 83) !important;width: 220px;" id="tipe_point_3_b" data-placeholder="select point.." class="select-size-md">
                                                            <option value="null" selected disabled>-- Pilih Point --</option>
                                                        </select>
                                                    </div>
                                                </div>
                                            </div>
            
                                            <div class="row" style="margin-top: 15px;">
                                                <div class="form-group">
                                                    <label class="col-lg-3 control-label lbl-top" >Informasi Bangunan</label>
                                                    <div class="col-lg-9">
                                                        <input id="info_create" type="text" class="form-control" value="" placeholder="Rumah/Gedung/Ruko/Pabrik/dsb" required>
                                                    </div>
                                                </div>
                                            </div>
            
                                            <div class="row" style="margin-top: 15px;">
                                                <div class="form-group">
                                                    <label class="col-lg-3 control-label lbl-top" >Alamat</label>
                                                    <div class="col-lg-9">
                                                        <input id="alamat_create" type="text" class="form-control" value="" placeholder="cth : Jl. Contoh Rt 005/01 No.01" required>
                                                    </div>
                                                </div>
                                            </div>
            
                                            <div class="row" style="margin-top: 15px;">
                                                <div class="form-group">
                                                    <label class="col-lg-3 control-label lbl-top" >Luas Bangunan</label>
                                                    <div class="col-lg-6">
                                                        <input id="luas_bangunan_create" type="text" class="form-control" value="" required>
                                                    </div>
                                                    <div class="col-lg-3">
                                                        <select id="satuan_luas_bangunan" >
                                                            <option>m2</option>
                                                        </select>
                                                    </div>
                                                </div>
                                            </div>
            
                                            <div class="row" style="margin-top: 15px;">
                                                <div class="form-group">
                                                    <label class="col-lg-3 control-label lbl-top">Luas Tanah</label>
                                                    <div class="col-lg-6">
                                                        <input id="luas_tanah_create" type="text" class="form-control" value="" required>
                                                    </div>
                                                    <div class="col-lg-3">
                                                        <select id="satuan_luas_tanah">
                                                            <option>m2</option>
                                                        </select>
                                                    </div>
                                                </div>
                                            </div>
            
                                            <div class="row" style="margin-top: 15px;">
                                                <div class="form-group">
                                                    <label class="col-lg-3 control-label lbl-top">Tinggi Bangunan</label>
                                                    <div class="col-lg-6">
                                                        <input id="tinggi_bangunan_create" type="text" class="form-control" value="" required>
                                                    </div>
                                                    <div class="col-lg-3">m</div>
                                                </div>
                                            </div>
            
                                            <div class="row" style="margin-top: 15px;">
                                                <div class="form-group">
                                                    <label class="col-lg-3 control-label lbl-top">Jumlah Lantai</label>
                                                    <div class="col-lg-9">
                                                        <input id="lantai" type="text" class="form-control" value="" placeholder="Estimasi Per Lantai = 3m" required>
                                                    </div>
                                                </div>
                                            </div>
            
                                            <div class="row" style="margin-top: 15px;">
                                                <div class="form-group">
                                                    <label class="col-lg-3 control-label lbl-top" >Pemilik</label>
                                                    <div class="col-lg-9">
                                                        <input id="pemilik_create" type="text" class="form-control" value="" placeholder="cth : Ali Budiman, S.Si." required>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
            
                                    </div>
                                </div>
                                <input type="button" class="btn btn-primary" id="create_save_bangunan" value="SAVE" style="margin-right:30px;">
                                <input type="text" name="poly_create" class="hidden" id="poly_create_bangunan" value="">
                            </div>
            
                            <div class="tab-pane koordinatjalan">
                                <div class="tabbable" style="overflow:auto;height:450px!important;width: 450px!important;">
                                    <ul class="nav nav-tabs nav-tabs-bottom nav-justified">
                                        <li onclick="changetabs(this)" class="active"><a href=".koordinatjalan" data-toggle="tab">Koordinat</a></li>
                                        <li onclick="changetabs(this)"><a href="#informasi_jalan" data-toggle="tab">Informasi Jalan</a></li>
                                    </ul>
            
                                    <div class="tab-content">
                                        <div class="tab-pane koordinatjalan" id="koordinatjalan">
                                            <div class="form-group">
                                                <div id="map-create-jalan" style="height: 250px;">
                                                    <input type="button" id="create-jal" value="Create" style="z-index: 1000;position:relative;">
                                                </div>
                                                <div class="form-group">
                                                    <label class="col-lg-2 control-label" style="margin-top:10px">Image</label>
                                                    <div class="col-lg-9" style="margin-top:10px">
                                                        <input type="file" id="img_jalan" name="images[]" multiple accept="image/jpg,image/png,image/jpeg,image/gif">
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="tab-pane" id="informasi_jalan">
            
                                            <div class="row" style="margin-top: 15px;">
                                                <div class="form-group">
                                                    <label class="col-lg-4 control-label lbl-top" style="margin-top: 15px;">Nama Jalan</label>
                                                    <div class="col-lg-8">
                                                        <input id="nama_jalan_create" type="text" class="form-control" value="" required>
                                                    </div>
                                                </div>
                                            </div>
            
                                            <div class="row" style="margin-top: 15px;">
                                                <div class="form-group">
                                                    <label class="col-lg-4 control-label lbl-top" style="margin-top: 15px;">Panjang Jalan (m)</label>
                                                    <div class="col-lg-8">
                                                        <input id="panjang_jalan_create" type="text" class="form-control" value="" required>
                                                    </div>
                                                </div>
                                            </div>
            
                                            <div class="row" style="margin-top: 15px;">
                                                <div class="form-group">
                                                    <label class="col-lg-4 control-label lbl-top" style="margin-top: 15px;">Lebar Jalan (m)</label>
                                                    <div class="col-lg-8">
                                                        <input id="lebar_jalan_create" type="text" class="form-control" value="" required>
                                                    </div>
                                                </div>
                                            </div>
            
                                            <div class="row" style="margin-top: 15px;">
                                                <div class="form-group">
                                                    <label class="col-lg-4 control-label lbl-top" style="margin-top: 15px;">Tipe Jalan</label>
                                                    <div class="col-lg-8">
                                                        <input id="tipe_jalan_create" type="text" class="form-control" value="" required>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <input type="button" class="btn btn-primary" id="create_save_jalan" value="SAVE" style="margin-right:30px;">
                                <input type="text" name="poly_create" class="hidden" id="poly_create_jalan" value="">
                            </div>
            
                            <div class="tab-pane point-insert">
                                <div class="tabbable" style="overflow:auto;height:450px!important;width: 450px!important;">
                                    <ul class="nav nav-tabs nav-tabs-bottom nav-justified">
                                        <li onclick="changetabs(this)" class="active"><a href=".point-insert" data-toggle="tab">Koordinat</a></li>
                                    </ul>
            
                                    <div class="tab-content">
                                        <div class="tab-pane point-insert">
                                            <div class="form-group">
                                                <div id="map-create-admin" style="height: 250px;">
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            `)
            .openOn(map);

        map.openPopup(popup);

        $("#tipe_point").change(function() {
            var tipe = $(this).val();

            $.ajax({
                url: "{% url 'api:change-tipe' %}",
                data: {
                    'tipe': tipe
                },
                dataType: 'json',
                success: function(data) {
                    console.log(data)
                    var data_all_kab = []
                    for (var i = 0; i < data['result'].length; i++) {
                        var data_k = data['result'][i][0];
                        var data_kab = `<option value="` +
                            data_k +
                            `">` +
                            data_k +
                            `</option>`;
                        data_all_kab.push(data_kab)
                    };
                    $('#tipe_point_2').html(`<option value="null" selected disabled>-- Pilih Tipe Point --</option>` + data_all_kab);
                }
            });
        });

        $("#tipe_point_b").change(function() {
            var tipe = $(this).val();

            $.ajax({
                url: "{% url 'api:change-tipe' %}",
                data: {
                    'tipe': tipe
                },
                dataType: 'json',
                success: function(data) {
                    var data_all_kab = []
                    for (var i = 0; i < data['result'].length; i++) {
                        var data_k = data['result'][i][0];
                        console.log(data_k)
                        var data_kab = `<option value="` + data_k + `">` + data_k + `</option>`;
                        data_all_kab.push(data_kab)
                    };
                    $('#tipe_point_2_b').html(`<option value="null" selected disabled>-- Pilih Tipe Point --</option>` + data_all_kab);
                }
            });
        });

        $("#tipe_point_2_b").change(function() {
            var jenis = $(this).val();
            var tipx = $("#tipe_point_b").val();

            $.ajax({
                url: "{% url 'api:change-jenis' %}",
                data: {
                    'tipe': tipx,
                    'jenis': jenis
                },
                dataType: 'json',
                success: function(data) {
                    console.log(data)
                    var data_all_kab = []
                    for (var i = 0; i < data['result'].length; i++) {
                        var data_id = data['result'][i][0];
                        var data_po = data['result'][i][1];
                        var data_kab = `<option value="` + data_id + `">` + data_po + `</option>`;
                        data_all_kab.push(data_kab)
                    };
                    $('#tipe_point_3_b').html(`<option value="null" selected disabled>-- Pilih Point --</option>` + data_all_kab);
                }
            });
        });

        var map_create_bangunan = L.map('map-create', {
            editable: true,
            zoomControl: false,
            drawControl: true
        }).setView([e.latlng.lat, e.latlng.lng], 20.5);

        map_created = L.tileLayer('https://mt1.google.com/vt/lyrs=s&x={x}&y={y}&z={z}', {
            maxZoom: 22,
            minZoom: 4,
        }).addTo(map_create_bangunan);

        map_create_bangunan.invalidateSize();

        $('#create').click(function() {
            polygonDraweredit.enable();
        });

        var Marker = {};
        var Poly = {};

        map_create_bangunan.on(L.Draw.Event.CREATED, function(e) {
            var layer = e.layer;

            $("#poly_create_bangunan").empty();

            var type = e.layerType;
            var layer = e.layer;

            var shape = layer.toGeoJSON();
            let geoShape = shape.geometry.coordinates[0];

            let kordinat = "";
            for (j in geoShape) {

                kordinat += geoShape[j][0] + ' ' + geoShape[j][1];

                if (j <= (geoShape.length - 2)) {
                    kordinat += ', ';
                }
            }
            window.thisBaseDrawPolygonLayer = layer;
            $("#poly_create_bangunan").val(JSON.stringify(kordinat));
        });

        polygon_options = {
            showArea: false,
            shapeOptions: {
                stroke: true,
                color: '#6e83f0',
                weight: 1.5,
                opacity: 2,
                fill: false,
                fillColor: null, //same as color by default
                clickable: true
            }
        }

        var polygonDraweredit = new L.Draw.Polygon(map_create_bangunan, polygon_options);

        polygonDraweredit.on("click", function(event) {
            shapecoords.innerHTML = event.latlng.toString();
            map_create_bangunan.fire("click", event); // Trigger a map click as well.
        });

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

            var lay = layer.addTo(map_create_bangunan);
            Poly = lay;
        });

        var map_create_jalan = L.map('map-create-jalan', {
            editable: true,
            zoomControl: false,
            drawControl: true
        }).setView([e.latlng.lat, e.latlng.lng], 20.5);

        L.tileLayer('https://mt1.google.com/vt/lyrs=s&x={x}&y={y}&z={z}', {
            maxZoom: 22,
            minZoom: 4,
        }).addTo(map_create_jalan);


        $("#c_jalan").click(function() {
            setTimeout(function() {
                map_create_jalan.invalidateSize();
            }, 500);
        })


        var lineDraweredit = new L.Draw.Polyline(map_create_jalan, polygon_options);

        lineDraweredit.on("click", function(event) {
            shapecoords.innerHTML = event.latlng.toString();
            map_create_jalan.fire("click", event); // Trigger a map click as well.
        });

        map_create_jalan.on('draw:created', function(e) {
            var type = e.layerType,
                layer = e.layer;
            layer.options.color = 'yellow';
            layer.options.weight = 10;
            var koordina = ""
            if (type === 'polyline') {

                var tempLatLng = null;
                var totalDistance = 0.00000;
                $.each(e.layer._latlngs, function(i, latlng) {
                    if (tempLatLng == null) {
                        tempLatLng = latlng;
                        return;
                    }

                    totalDistance += tempLatLng.distanceTo(latlng);
                    tempLatLng = latlng;

                });
                e.layer.bindPopup((totalDistance).toFixed(2) + ' meter');
                e.layer.openPopup();

                $("#panjang_jalan_create").val((totalDistance).toFixed(2) + ' meter');
            }
            $("#poly_create_jalan").val(JSON.stringify(layer.toGeoJSON()));
            layer.addTo(map_create_jalan);
        });

        $("#create-jal").click(function() {
            lineDraweredit.enable();
        })

        var map_create_admin = L.map('map-create-admin', {
            editable: true,
            zoomControl: false,
            drawControl: true
        }).setView([e.latlng.lat, e.latlng.lng], 20.5);

        L.tileLayer('https://mt1.google.com/vt/lyrs=s&x={x}&y={y}&z={z}', {
            maxZoom: 22,
            minZoom: 4,
        }).addTo(map_create_admin);

        $("#point-insert").click(function() {
            setTimeout(function() {
                map_create_admin.invalidateSize();
            }, 500);
        })

        $(".leaflet-draw-draw-marker").html('<span class="fa fa-expand"></span>')

        var drawControl = new L.Control.Draw(drawPluginOptions);
        map_create_admin.addControl(drawControl);

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

        // define custom marker
        var MyCustomMarker = L.Icon.extend({
            options: {
                shadowUrl: null,
                iconAnchor: new L.Point(12, 12),
                iconSize: new L.Point(24, 24),
            }
        });

        var drawPluginOptions = {
            position: 'topright',
            draw: {
                marker: {
                    title: "soyel1",
                    icon: new MyCustomMarker()
                },
                marker: true
            },
            edit: {
                featureGroup: editableLayers, //REQUIRED!!
                remove: true
            }
        };

        var drawControl = new L.Control.Draw(drawPluginOptions);
        map_create_admin.addControl(drawControl);

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

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

            editableLayers.addLayer(layer);
            $("#poly_create_point").val(JSON.stringify(layer.toGeoJSON()));
            $("#modal_point").modal()
            map.closePopup();
        });

        $("#map-create-admin > div.leaflet-control-container > div.leaflet-top.leaflet-left > div:nth-child(2) > div > div > a.leaflet-draw-draw-marker").css("display", "block!important")

    });

    $(document).on("click", "#create_save_jalan", function(e) {
        data = new FormData()
        data.append("gambar", $("input[id^='img_jalan']")[0].files[0]);
        data.append("polyline", $("#poly_create_jalan").val())
        data.append("name_jalan", $("#nama_jalan_create").val())
        data.append("panjang_jalan", $("#panjang_jalan_create").val())
        data.append("lebar_jalan", $("#lebar_jalan_create").val())
        data.append("tipe_jalan", $("#tipe_jalan_create").val())

        $.ajax({
            url: "{% url 'api:create-jalan' %}",
            data: data,
            dataType: 'json',
            type: 'POST',
            processData: false,
            contentType: false,
            success: function(data) {
                let response = data
                if (response.status == 0) {
                    swal({
                        title: response.info,
                        text: response.data,
                        type: "success",
                        icon: "success",
                        confirmButtonColor: "#00BCD4"
                    })
                } else {
                    swal({
                        title: response.info,
                        text: response.data,
                        type: "warning",
                        icon: "error",
                        confirmButtonColor: "#00BCD4"
                    })

                }
                map.closePopup();
            }
        });
    });


    $(document).on("click", "#create_save_bangunan", function(e) {
        var polygin = $('#poly_create_bangunan').val();
        var name_poly = $('#name_create').val();
        var tdb = $('#tipe_point_b').val();
        var remark = $('#tipe_point_2_b').val();
        var poin_id = $('#tipe_point_3_b').val();
        var napo = $("#tipe_point_3_b option:selected").text();
        var info_poly = $('#info_create').val();
        var alamat_poly = $('#alamat_create').val();
        var lb_poly = $('#luas_bangunan_create').val();
        var lt_poly = $('#luas_tanah_create').val();
        var tb_poly = $('#tinggi_bangunan_create').val();
        var ltbang = $('#lantai').val();
        var mpu_poly = $('#pemilik_create').val();

        $.ajax({
            url: "{% url 'api:c_bangunan' %}",
            data: {
                'polygon': polygin,
                'name': name_poly,
                'tipedb': tdb,
                'poin_id': poin_id,
                'nama_po': napo,
                'remark': remark,
                'info': info_poly,
                'alamat': alamat_poly,
                'lb': lb_poly,
                'lt': lt_poly,
                'tb': tb_poly,
                'ltb': ltbang,
                'pemilik': mpu_poly
            },
            dataType: 'json',
            // type: 'POST',
            // processData: false,
            // contentType: false,
            success: function(data) {
                let response = data
                if (response.status == 0) {
                    swal({
                        title: response.info,
                        text: response.data,
                        type: "success",
                        icon: "success",
                        confirmButtonColor: "#00BCD4"
                    })
                } else {
                    swal({
                        title: response.info,
                        text: response.data,
                        type: "warning",
                        icon: "error",
                        confirmButtonColor: "#00BCD4"
                    })

                }
                map.closePopup();
            }
        });
    });


    $(document).on("click", "#btnsavepoint", function(e) {
        data = new FormData()
        data.append("gambar", $("input[id^='gambar_pitik']")[0].files[0]);
        data.append("point", $("#poly_create_point").val())
        data.append("name_create_point", $("#name_create_point").val())
        data.append("tipe_point", $("#tipe_point").val())
        data.append("info_create_point", $("#tipe_point_2").val())
        data.append("alamat_create_point", $("#alamat_create_point").val())
        data.append("luas_tanah_point", $("#luas_tanah_point").val())
        data.append("pemilik_point", $("#pemilik_point").val())

        $.ajax({
            url: "{% url 'api:create-point' %}",
            data: data,
            dataType: 'json',
            type: 'POST',
            processData: false,
            contentType: false,
            success: function(data) {
                let response = data
                if (response.status == 0) {
                    swal({
                        title: response.info,
                        text: response.data,
                        type: "success",
                        icon: "success",
                        confirmButtonColor: "#00BCD4"
                    }, function() {
                        $("#modal_point").css('display', 'none');
                    })
                } else {
                    swal({
                        title: response.info,
                        text: response.data,
                        type: "warning",
                        icon: "error",
                        confirmButtonColor: "#00BCD4"
                    })

                }
                map.closePopup();
            }
        });
    });
    //klik kanan end
</script>