File size: 6,982 Bytes
958e845
eaf3824
5d75e95
 
 
 
958e845
 
eaf3824
 
 
bf9afe4
5d75e95
eaf3824
 
5d75e95
eaf3824
5d75e95
 
eaf3824
bf9afe4
5d75e95
 
eaf3824
5d75e95
eaf3824
bf9afe4
5d75e95
 
eaf3824
bf9afe4
5d75e95
eaf3824
 
5d75e95
eaf3824
bf9afe4
5d75e95
eaf3824
bf9afe4
eaf3824
 
 
 
 
 
 
 
5d75e95
eaf3824
5d75e95
bf9afe4
eaf3824
5d75e95
eaf3824
5d75e95
eaf3824
5d75e95
 
eaf3824
 
 
 
 
 
 
 
 
 
 
5d75e95
 
eaf3824
 
 
 
 
 
 
 
 
 
bf9afe4
5d75e95
eaf3824
 
 
 
5d75e95
 
 
eaf3824
 
 
 
 
 
c9e0f70
eaf3824
 
 
 
bf9afe4
eaf3824
 
 
 
 
 
 
 
5d75e95
eaf3824
 
 
5d75e95
bc4c6a1
5d75e95
 
eaf3824
 
 
 
 
958e845
eaf3824
bc4c6a1
eaf3824
 
bc4c6a1
eaf3824
 
bc4c6a1
eaf3824
 
bc4c6a1
eaf3824
 
bc4c6a1
eaf3824
 
 
 
 
 
958e845
eaf3824
 
bc4c6a1
958e845
eaf3824
 
958e845
eaf3824
 
5d75e95
 
eaf3824
 
958e845
eaf3824
bc4c6a1
5d75e95
eaf3824
958e845
5d75e95
eaf3824
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bf9afe4
c918558
562ac93
958e845
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
import json
import html
import folium
import gradio as gr
from folium import plugins

from lib import RequestFunction


def CreateMap() -> folium.Map:
    """Çizim araçları ve çoklu temel katmanlar içeren ana haritayı oluşturur."""
    fmap = folium.Map(location=[37.511905, 38.51532], zoom_start=6, world_copy_jump=True, tiles=None)

    # Temel katmanlar
    folium.TileLayer("https://tile.openstreetmap.org/{z}/{x}/{y}.png", attr="OpenStreetMap", name="OpenStreetMap").add_to(fmap)

    folium.TileLayer("http://www.google.cn/maps/vt?lyrs=s@189&gl=cn&x={x}&y={y}&z={z}", attr="Google", name="Google Uydu").add_to(fmap)

    folium.TileLayer(
        "https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}", attr="Esri", name="Esri Dünya Uydu"
    ).add_to(fmap)

    folium.TileLayer(
        "https://server.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer/tile/{z}/{y}/{x}",
        attr="Esri",
        name="Esri Dünya Sokak",
    ).add_to(fmap)

    folium.TileLayer(
        "https://cartodb-basemaps-a.global.ssl.fastly.net/light_all/{z}/{x}/{y}.png", attr="CartoDB", name="CartoDB Açık"
    ).add_to(fmap)

    # Koordinat göstergesi
    formatter = "function(num) {return L.Util.formatNum(num, 5) + ' ° ';};"
    plugins.MousePosition(
        position="bottomright", separator=" | ", lng_first=True, prefix="Konum:", lat_formatter=formatter, lng_formatter=formatter
    ).add_to(fmap)

    plugins.Geocoder(position="topleft").add_to(fmap)
    plugins.Draw(export=True, filename="drawing.geojson", position="topleft", show_geometry_on_click=False).add_to(fmap)
    plugins.Fullscreen(position="topright").add_to(fmap)
    folium.LayerControl(position="bottomleft").add_to(fmap)

    # Çizim olaylarını Gradio bileşenlerine bağla
    map_name = fmap.get_name()
    fmap.get_root().html.add_child(
        folium.Element(
            f"""
        <script type="text/javascript">
            document.addEventListener('DOMContentLoaded', function() {{
                var idx = 0;
                var drawnItems = new L.FeatureGroup();
                {map_name}.addLayer(drawnItems);

                const updateGeoJsonOutput = (geoJsonData) => {{
                    const textArea = parent.document.querySelector('#geojson_output textarea');
                    if (!textArea) return;
                    textArea.value = JSON.stringify(geoJsonData);
                    textArea.dispatchEvent(new Event('input'));
                }};

                // "GeoJSON Al" butonuna tıklandığında güncel veriyi aktar
                const processBtn = parent.document.getElementById('geojson_process');
                if (processBtn) {{
                    processBtn.onclick = function() {{
                        updateGeoJsonOutput(drawnItems.toGeoJSON());
                    }};
                }}

                {map_name}.on('draw:created', function(e) {{
                    var layer = e.layer;
                    var title, value;

                    do {{
                        title = prompt('Şekle bir isim giriniz:', '');
                        if (title === null) return;
                    }} while (!title.trim());

                    do {{
                        value = prompt('Şekle bir değer giriniz:', '');
                        if (value === null) return;
                    }} while (!value.trim());

                    var id = idx++;
                    var feature     = layer.feature = layer.feature || {{}};
                    feature.type    = 'Feature';
                    var props       = feature.properties = feature.properties || {{}};
                    props.Id    = id;
                    props.Title = title;
                    props.Value = value;

                    layer.bindTooltip(
                        `Şekil: ${{id + 1}} | İsim: ${{title}} | Değer: ${{value}}`,
                        {{ permanent: false, direction: 'center', className: 'label-tooltip' }}
                    );

                    drawnItems.addLayer(layer);
                    updateGeoJsonOutput(drawnItems.toGeoJSON());
                }});

                {map_name}.on('draw:deleted', function(e) {{
                    e.layers.eachLayer(function(layer) {{
                        drawnItems.removeLayer(layer);
                    }});
                    updateGeoJsonOutput(drawnItems.toGeoJSON());
                }});

                {map_name}.on('draw:edited', function(e) {{
                    updateGeoJsonOutput(drawnItems.toGeoJSON());
                }});
            }});
        </script>
    """
        )
    )

    return fmap


def CreateDatasetMap(geojson_data: str) -> str:
    """GeoJSON verisinden GEE haritası üretir ve iframe olarak döndürür."""
    if not geojson_data:
        return "<p>Lütfen önce haritada bir bölge çizin.</p>"

    geojson = json.loads(geojson_data)
    features = geojson.get("features", [])

    if not features:
        return "<p>Çizili şekil bulunamadı.</p>"

    coords = features[0]["geometry"]["coordinates"][0]
    fmap = RequestFunction(coords)

    if fmap is None:
        return "<p>Veri alınamadı.</p>"

    raw_html = fmap._repr_html_()
    escaped = html.escape(raw_html)

    return f"""<iframe
        style="width:100%; height:520px; border:none;"
        sandbox="allow-scripts allow-same-origin allow-popups allow-forms allow-modals"
        allowfullscreen
        srcdoc='{escaped}'
    ></iframe>"""


# Ana haritayı oluştur
basemap = CreateMap()

# Gradio Arayüzü
with gr.Blocks(title="GEE Harita Uygulaması") as app:

    gr.Markdown("# GEE Harita Uygulaması")
    gr.Markdown("Çalışmak istediğiniz bölgeyi harita üzerinde çizin, ardından veri çekin.")

    with gr.Row():
        geojson_process_btn = gr.Button("GeoJSON Al", elem_id="geojson_process", variant="secondary")
        prepare_dataset_btn = gr.Button("Veri Çek", elem_id="prepare_dataset", variant="primary")

    # Ana harita
    map_html = gr.HTML(basemap._repr_html_(), elem_id="map_container")

    # GEE sonuç haritası
    dataset_map_html = gr.HTML(elem_id="dataset_map_container")

    # Ham GeoJSON çıktısı (JS tarafından doldurulan gizli alan)
    geojson_output = gr.Textbox(
        value="",
        placeholder="Çizilen şekillerin GeoJSON verisi burada görünür.",
        label="Ham GeoJSON",
        lines=4,
        elem_id="geojson_output",
        interactive=False,
    )

    # GeoJSON görünümü
    geojson_view = gr.JSON(label="GeoJSON Görünümü")

    # Event bağlantıları
    geojson_process_btn.click(
        fn=lambda data: json.loads(data) if data else {}, inputs=geojson_output, outputs=geojson_view, scroll_to_output=True
    )

    prepare_dataset_btn.click(fn=CreateDatasetMap, inputs=geojson_output, outputs=dataset_map_html, scroll_to_output=True)


app.queue(max_size=10)
app.launch(share_server_protocol="https")