From b7026f453b472187cf1c0a393c9d7529373d2489 Mon Sep 17 00:00:00 2001
From: Sara <sarasdj@stud.ntnu.no>
Date: Wed, 6 Mar 2024 13:50:21 +0100
Subject: [PATCH] updaet: try to append tiles to map

---
 app/lib/pages/marker_handler/get_markers.dart |  10 ++++++-
 .../pages/marker_handler/get_relation.dart    |  11 -------
 app/lib/pages/widgets/cloropleth_map.dart     |   3 --
 .../__pycache__/get_relation.cpython-311.pyc  | Bin 3310 -> 3692 bytes
 server/map/get_relation.py                    |  28 ++++++++++++++----
 5 files changed, 31 insertions(+), 21 deletions(-)

diff --git a/app/lib/pages/marker_handler/get_markers.dart b/app/lib/pages/marker_handler/get_markers.dart
index d90a7774..ebe5081e 100644
--- a/app/lib/pages/marker_handler/get_markers.dart
+++ b/app/lib/pages/marker_handler/get_markers.dart
@@ -3,6 +3,7 @@ import 'dart:convert';
 import 'dart:io';
 import '../consts.dart';
 import 'marker_data.dart';
+import 'package:path_provider/path_provider.dart';
 
 // fetchMarkerTemplate requests all marker data from the server
 Future<List<Measurement>> fetchMarkerData() async {
@@ -26,7 +27,14 @@ Future<List<Measurement>> fetchMarkerData() async {
         // Attempt to parse response to Measurement object only if the body
         // contains correctly formatted data
         if (jsonData != null && jsonData is List) {
-          print(jsonData.map((data) => Measurement.fromJson(data)).toList());
+          Directory appDocumentsDirectory = await getApplicationDocumentsDirectory();
+          String filePath = '${appDocumentsDirectory.path}/last_update.txt';
+
+          try { // Write most recent time of update to file
+            await File(filePath).writeAsString('${DateTime.now()}', mode: FileMode.write);
+            print('Update time written to file');
+          } catch (error) { print('Error in writing to file: $error');}
+
           return jsonData.map((data) => Measurement.fromJson(data)).toList();
         } else {
           throw Exception('Failed to parse marker data: Unexpected response format');
diff --git a/app/lib/pages/marker_handler/get_relation.dart b/app/lib/pages/marker_handler/get_relation.dart
index c965faaf..77d3297d 100644
--- a/app/lib/pages/marker_handler/get_relation.dart
+++ b/app/lib/pages/marker_handler/get_relation.dart
@@ -3,9 +3,6 @@ import 'dart:convert';
 import 'dart:io';
 import '../consts.dart';
 import 'dart:typed_data';
-import 'dart:io';
-import 'package:path/path.dart';
-import 'package:path_provider/path_provider.dart';
 
 /// Fetch relation data from server
 Future<Uint8List> fetchRelation() async {
@@ -24,14 +21,6 @@ Future<Uint8List> fetchRelation() async {
       var responseBody = await response.transform(utf8.decoder).join();
 
       if (responseBody.isNotEmpty) {
-        Directory appDocumentsDirectory = await getApplicationDocumentsDirectory();
-        String filePath = '${appDocumentsDirectory.path}/last_update.txt';
-
-        try { // Write most recent time of update to file
-          await File(filePath).writeAsString('${DateTime.now()}', mode: FileMode.write);
-          print('Update time written to file');
-        } catch (error) { print('Error in writing to file: $error');}
-
         // Return relation data from the response body
         return Uint8List.fromList(utf8.encode(responseBody));
       } else {
diff --git a/app/lib/pages/widgets/cloropleth_map.dart b/app/lib/pages/widgets/cloropleth_map.dart
index e776663a..9f98e9a4 100644
--- a/app/lib/pages/widgets/cloropleth_map.dart
+++ b/app/lib/pages/widgets/cloropleth_map.dart
@@ -1,11 +1,8 @@
 import 'dart:typed_data';
 import 'package:latlong2/latlong.dart';
-
 import '../marker_handler/marker_data.dart';
 import 'package:flutter/material.dart';
 import 'package:syncfusion_flutter_maps/maps.dart';
-import '../consts.dart';
-import 'dart:typed_data';
 
 /// A class containing thickness for each subdivision of the map.
 class IceThicknessModel {
diff --git a/server/map/__pycache__/get_relation.cpython-311.pyc b/server/map/__pycache__/get_relation.cpython-311.pyc
index bec3ee45489a6064fd5d5de765d0a1ff2f53b1e7..351ca50214511cdb07cdca192bc07bca2d960bb5 100644
GIT binary patch
delta 1195
zcmZWo&ube;6n?YX-&#qwBr8%RJ1)dnPF>R`b_$80EhIF=i7#m{f*^!vt*o=L#LTvk
zc2&DzS|0+%OiOeyRK28u^bqi+^wR&JNMRvn!O&w5rRdNcTRO9{RqPCJ-@I?$_ukHX
z`}VKGpQYrFiG&G!y}R~@{ja&3%vUNLJq8RIxlkSMs47J`R+afKxyl2zsv^KKTU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9<nK#UQ+VweU
zJ~WIF0xM2_u!aLQGchy-Y7H^Oa0%r)9_I*XQc@OZj$*_VOPwW*uF{;w)K!%0s$D!m
z-r`#Qb$3ydr%Cg|q96B)XT;PN)hen7#0rTDoy2jl&5n`;4z<~192OO#>UyUUp?bHB
ztEj5h4aqjv$q|fA@lII*EYSTaTI5dISJ|b73irdzzHBoq?^>mTXFFx_lxDFezSF^|
z;aa@nl)06c4P0JMoKbuAy+EYkACd6X`JPzv=ER+)M^_r@k!E_N(KFiY85J?@8XnxZ
ztHnqk(^gSc8AA`CXB~FO7R{=87G=7`ba3+A4BiTZ?}8nL{q;P+8k$2@G<{$ZS206L
zh;+>RqXRN{J5&6fDH3r=iJxNRHmQ;8129c-_d&ZWA1g!J+}CFu$7Oc8;8{GQ__Snm
z&kaI>ueCEA3gs{R)U!*LNQQ=|j)UZ50L!R_a3r}6oAb^suRhUCAACulPrb^#$T!EQ
zo8zpJwVGLLGcpTnySmL>6AprBxE~rwWy0=mIVvbe<+**;@`=rSRZ1>?hE8XA81nsp
zo7)XBH?ak2ApG9O4Sflpq+7Rp6WQ5PKzxz+{U%{~;=LZ*q_NKYfE$N4KR9POl|q>n
zxVr<icw(e9`Q2_pG>lXz3sk-?zaV}XX|czQ9E;<j`b-Of`xg%P;dl%E5AA`!01`#R
AnE(I)

diff --git a/server/map/get_relation.py b/server/map/get_relation.py
index 616adfa3..a7830330 100644
--- a/server/map/get_relation.py
+++ b/server/map/get_relation.py
@@ -1,5 +1,6 @@
 import json
 import geopandas as gpd
+import pandas as pd
 from shapely.geometry import Polygon
 
 
@@ -16,8 +17,13 @@ def get_relation(self, body_of_water: str):
     if len(polygons) <= 1:
         print("Failed to convert to polygons")
 
-    # Convert response data to JSON string
-    response_json = json.dumps(divide_relation(polygons))
+    # Divide relation into tiles and append tiles to relation object
+    tiles = divide_relation(polygons)
+    # polygon_data = pd.concat([polygon_data, gpd.GeoDataFrame(tiles)], ignore_index=True)
+
+    # Transform geojson to json -> syncfusion_flutter_maps lib requires json
+    geojson_dict = json.loads(polygon_data.to_json())
+    response_json = json.dumps(geojson_dict)
 
     # Set headers
     self.send_response(200)
@@ -39,12 +45,12 @@ def divide_relation(polygons):
         rows = int((y_max - y_min) / tile_size)
         cols = int((x_max - x_min) / tile_size)
 
-        if rows == 0 or cols == 0:  # Skip small polygons
+        if rows == 0 or cols == 0:  # Skip polygons that are smaller than the division size
             continue
 
         for row in range(rows):
             for col in range(cols):
-                tile_bbox = Polygon([
+                tile_bbox = Polygon([ # Calculate coordinate for current place in column and row
                     (x_min + col * tile_size, y_min + row * tile_size),
                     (x_min + (col + 1) * tile_size, y_min + row * tile_size),
                     (x_min + (col + 1) * tile_size, y_min + (row + 1) * tile_size),
@@ -56,6 +62,16 @@ def divide_relation(polygons):
     if len(tiles) <= 1:
         print("Failed to divide polygons into tiles")
 
-    tiles_json = [{"SubDivID": tile["SubDivID"], "coordinates": list(tile["polygon"].exterior.coords)} for tile in
-                  tiles]
+    # Format each tile object with coordinate, type, and subdivision id tags
+    tiles_json = []
+    for tile in tiles:
+        coordinates = list(tile["polygon"].exterior.coords)
+        polygon_json = {
+            "type": "Polygon",
+            "coordinates": [[(coord[0], coord[1]) for coord in coordinates]],
+            "SubDivID": tile["SubDivID"]
+        }
+        tiles_json.append(polygon_json)
+
+    # Return all tiles for current polygon
     return tiles_json
-- 
GitLab