From 774efd0d6af2bb789ceb51f6aa3d300b15c2da28 Mon Sep 17 00:00:00 2001
From: brli <brita.linnestad@nibio.no>
Date: Thu, 31 Oct 2024 15:41:39 +0100
Subject: [PATCH] Add map to Applefrutmoth

---
 .../applefruitmoth/js/applefruitmoth.js       | 191 ++++++++++++++----
 .../templates/applefruitmoth/index.html       | 132 +++++++++++-
 2 files changed, 272 insertions(+), 51 deletions(-)

diff --git a/applefruitmoth/static/applefruitmoth/js/applefruitmoth.js b/applefruitmoth/static/applefruitmoth/js/applefruitmoth.js
index 0d15fe62..37f2d4cd 100644
--- a/applefruitmoth/static/applefruitmoth/js/applefruitmoth.js
+++ b/applefruitmoth/static/applefruitmoth/js/applefruitmoth.js
@@ -1,5 +1,5 @@
 
-document.addEventListener('DOMContentLoaded', setBasis);
+document.addEventListener('DOMContentLoaded', setBasis());
 document.title="Rognebærmøllvarsling";
 
 
@@ -9,39 +9,64 @@ var serverUri = "https://" + settings.vipsCoremanagerServerName;
 var runUri= serverUri + "/models/DAYDEGREES/run"; 
 
 var emptyChart;
-
-
-
-
+var storedWeatherstation;
+ 
+window.onload = function() {
+    setBasis();
+};
+ 
+ 
 function setBasis () {
-		
-	let path = "https://lmt.nibio.no/services/rest/weatherstation/mapweatherstations";
-	
-    $.getJSON(path, function( mapStations ) {	
 	
-		allStations = mapStations;
+		emptyChart=true;
+		displayResults();
+		setStartText();
 		
-		allStations.sort(function(a,b) {
-			return a.name.toString().localeCompare(b.name.toString());
-		});
+		//let path = "https://lmt.nibio.no/services/rest/weatherstation/mapweatherstations";
+		/*
+    	$.getJSON(path, function( mapStations ) {	
 		
-		for(var i=0;i<allStations.length;i++){
-			stations[i]=([mapStations[i].weatherstationId, mapStations[i].name]);
-			
-		}
+			allStations = mapStations;
 		
-		for (let i = 0; i < stations.length; i++ ) {
-			let option = document.createElement("option");
-			option.text = stations[i][1];
-			option.value = stations[i][0];
-			document.getElementById("weatherstation").appendChild(option);
-		}
+			allStations.sort(function(a,b) {
+				return a.name.toString().localeCompare(b.name.toString());
+			});
 		
-		emptyChart = true;
+			for(var i=0;i<allStations.length;i++){
+				stations[i]=([mapStations[i].weatherstationId, mapStations[i].name]);
+			
+			}
 		
-		setStartText();
-		displayResults(emptyChart);
-    });
+			for (let i = 0; i < stations.length; i++ ) {
+				let option = document.createElement("option");
+				option.text = stations[i][1];
+				option.value = stations[i][0];
+				document.getElementById("weatherstation").appendChild(option);
+			}
+			
+			// After populating the dropdown, get the stored weatherstation value 
+    		storedWeatherstation = window.localStorage.getItem('weatherstation');
+
+    		// If a stored value exists, set it as the selected value of the dropdown
+   	 		if (storedWeatherstation) {
+        		document.getElementById('weatherstation').value = storedWeatherstation;
+    		}
+    		
+			var startdate = window.localStorage.getItem('startdate');    		
+    		
+        	document.getElementById('enddate').value = moment().add(7,'days').format('YYYY-MM-DD'); 
+    		
+    		if (startdate) {
+            	document.getElementById('startdate').value = startdate;
+            	getBasis();
+        	}
+        	else {
+				emptyChart=true;
+				displayResults();
+				setStartText();
+			}
+			
+    });*/
 
 }
 
@@ -51,11 +76,32 @@ function getBasis () {
 	var basisTemp = "0";
 	var startTime = document.getElementById('startdate').value;
 	var endTime = document.getElementById('enddate').value;
-	var weatherStation = document.getElementById('weatherstation').value;
+	var weatherStation = document.getElementById('weatherstationtest').value;
 	
 	var temperature = [];
 	
+	var latitudeInput = document.getElementById('latitude');
+   	var longitudeInput = document.getElementById('longitude');
+
+    var latitude = parseFloat(latitudeInput.value);
+    var longitude = parseFloat(longitudeInput.value);
+    
+    let useLocation = false;
+    let long_lat;
+
+	console.info("long");
+	console.info(latitude, longitude);
+	
 	weatherstationId = weatherStation;
+
+	if(latitude){
+		long_lat = longitude + "_" +latitude;
+		useLocation = true;
+	}
+	
+	//window.localStorage.setItem('weatherstation', weatherStation);
+	window.localStorage.setItem('startdate', startTime);
+	window.localStorage.setItem('enddate', endTime);		
 	  
 	if (startTime > endTime) {
     	alert("Datoen er ikke gyldig");
@@ -64,15 +110,22 @@ function getBasis () {
     
     emptyChart = false;
     
-    $.getJSON("https://lmt.nibio.no/services/rest/vips/getdata/forecastfallback?weatherStationId="+weatherStation+"&elementMeasurementTypes[]=TM&logInterval=1d&startDate="+startTime+"&startTime=00&endDate="+endTime+"&endTime=23&timeZone=Europe/Oslo", function( observations ) { 
+    	
+	if(useLocation)
+	{
+		$.getJSON("https://weather.vips.nibio.no/rest/grid/openmeteo/"+long_lat+"?elementMeasurementTypes[]=TM&timeZone=Europe/Oslo&logIntervalId=2&startDate="+startTime+"&endDate="+endTime, function( observations ) {
+			runModel(basisTemp, observations, long_lat, startTime, endTime);
+		});
+	} else {	
+    	$.getJSON("https://lmt.nibio.no/services/rest/vips/getdata/forecastfallback?weatherStationId="+weatherStation+"&elementMeasurementTypes[]=TM&logInterval=1d&startDate="+startTime+"&startTime=00&endDate="+endTime+"&endTime=23&timeZone=Europe/Oslo", function( observations ) { 
     		$.getJSON("https://lmt.nibio.no/services/rest/weatherstation/getstation?weatherStationId="+weatherStation, function( weatherstation ) {
     			allObservations = weatherstation; 
             	var name = String(weatherstation.name);
-            	console.info(observations);
     			runModel(basisTemp, observations, name, startTime, endTime);
-    });
-    });
-    
+    				
+   		});
+    	});
+   }
 }
 
 /**
@@ -92,7 +145,7 @@ function runModel (basisTemp, data, name, start, end) {
 			"observations": data
 		}
 	};
-
+	
     var request = $.ajax({
         type:"POST",
         url: runUri,
@@ -116,8 +169,7 @@ function displayResults(data, basisTemp, name, start, end) {
 			let time = new Array();
 			let temperature = new Array();
 			let forecast = new Array();
-			
-			
+				
 			if(!emptyChart) {
 				for (var i = 0; i < data.length; i++){
 					
@@ -135,6 +187,7 @@ function displayResults(data, basisTemp, name, start, end) {
 		    	    localTime = localTime.toISOString().split('T')[0];
 		        	time.push(localTime);
 				}
+				
 				// Fill the gap between temperature and forecast
 				let index = temperature.length-1;
 				forecast[index]=temperature[index];
@@ -163,14 +216,11 @@ function displayResults(data, basisTemp, name, start, end) {
 				for (var i = 0; i < 10; i++){
 					time.push(null);
 					forecast.push(null);
-					name = 'Alvdal';
+					name = '-';
 					start = '-';
 					end = '-'; 
 				}
 			}
-				
-			
-			
 			
 			var chartExist = Chart.getChart("daydegreesum");
 			
@@ -328,11 +378,12 @@ function displayResults(data, basisTemp, name, start, end) {
 					}
 				}
 			  });
-			  
-	
+			 
 }
 
 function setStartText (){
+	
+			console.info('settext');
 			
 			document.getElementById("textInfo").innerText = "";		  
 			
@@ -343,4 +394,60 @@ function setStartText (){
 	
 }
 
+function useWeatherstation() {
+	
+    document.getElementById('weatherstationDiv').style.display = 'block';
+    let path = "https://lmt.nibio.no/services/rest/weatherstation/mapweatherstations";
+
+    $.getJSON(path, function( mapStations ) {	
+		
+			allStations = mapStations;
+		
+			allStations.sort(function(a,b) {
+				return a.name.toString().localeCompare(b.name.toString());
+			});
+		
+			for(var i=0;i<allStations.length;i++){
+				stations[i]=([mapStations[i].weatherstationId, mapStations[i].name]);
+			
+			}
+		
+			for (let i = 0; i < stations.length; i++ ) {
+				let option = document.createElement("option");
+				option.text = stations[i][1];
+				option.value = stations[i][0];
+				document.getElementById("weatherstationtest").appendChild(option);
+			}
+			
+			console.info(stations);
+	
+			// After populating the dropdown, get the stored weatherstation value 
+    		storedWeatherstation = window.localStorage.getItem('weatherstation');
+
+    		// If a stored value exists, set it as the selected value of the dropdown
+   	 		if (storedWeatherstation) {
+        		document.getElementById('weatherstationtest').value = storedWeatherstation;
+    		}
+    		
+			var startdate = window.localStorage.getItem('startdate');    		
+    		
+        	document.getElementById('enddate').value = moment().add(7,'days').format('YYYY-MM-DD'); 
+    		
+    		if (startdate) {
+            	document.getElementById('startdate').value = startdate;
+        	}
+        	else {
+				emptyChart=true;
+				displayResults();
+				setStartText();
+			}
+			
+    });
+    
+}
+
+function useCoordinates () {
+		console.info('lengde-bredde');
+}
+
 
diff --git a/applefruitmoth/templates/applefruitmoth/index.html b/applefruitmoth/templates/applefruitmoth/index.html
index 6f930f78..28de0ba6 100755
--- a/applefruitmoth/templates/applefruitmoth/index.html
+++ b/applefruitmoth/templates/applefruitmoth/index.html
@@ -23,6 +23,7 @@
 {% endcomment %}
 {% load i18n %}
 {% block title%}{% trans "Apple fruit moth forecasting" %}{%endblock%}
+
 {% block content %}
 <h1>{% trans "Apple fruit moth forecasting" %}</h1>
 <div class="singleBlockContainer">
@@ -76,12 +77,35 @@
 			<div class="row"><br><br>
 			<div style="font-size:75%;" id="setBasis"></div>
 			    
-			    <div class="col-md-3">		
-			    	<div class="form-group">
-						<label for="weatherstation">Målestasjon</label>
-						<select id="weatherstation" class="form-control"></select>
+			    <div class="col-md-4">		
+					<div class="form-group">
+								
+					<p>Jeg vil bruke værdata</p>
+					<div class="radio">
+						<label>
+							<input type="radio" name="weatherdataType" id="coordinates" value="coordinates" checked onchange="displayCoordinatesInput()">
+							for et spesifikt punkt (koordinater)
+						</label>
+						<div id="input-coordinates">
+							<input type="text" class="form-control" name="latitude" id="latitude" placeholder="Breddegrad" aria-label="Breddegrad">
+							<input type="text" class="form-control" name="longitude" id="longitude" placeholder="Lengdegrad" aria-label="Lengdegrad">
+							<button type="button" class="btn btn-primary" onclick="openCoordinatesMap()"><i class="fa fa-map-marker fa-lg"></i> Velg i kart</button>
+						</div>
+						<div id="coordinates-map" class="map-modal"></div>
 					</div>
-			    
+					</div>
+					<div class="radio">
+					<label>
+						  <input type="radio" name="weatherdataType" id="weatherstation" value="weatherstation" onchange="displayWeatherstationInput()">
+						  fra en værstasjon			  
+					</label>
+					<br>
+			        <div class="form-group" id="weatherstationDiv" style="display: none;">
+						<label for="weatherstation">Værstasjon</label>
+						<select id="weatherstationtest" class="form-control"></select>
+					</div>
+					</div>
+					<br>
 					<div class="form-group">
 						<label for="startdate">Dato for full blom i rogn</label>
 						<input type="date" id="startdate" class="form-control">
@@ -89,7 +113,7 @@
 					
 					<div class="form-group">
 						<label for="enddate">Sluttdato, med prognose 9 døgn fram i tid</label>
-						<input type="date" value=moment().add(7,'days').format('YYYY-MM-DD'); id="enddate" class="form-control">
+						<input type="date" id="enddate" class="form-control">
 					</div>
 			    
   	    			<br>
@@ -100,7 +124,7 @@
   	    		
 				</div>
   	    		
-  	    		<div class="col-md-9">
+  	    		<div class="col-md-8">
   	    			<div class="col-md-2"></div>
   	    			<div class="col-md-9">
   	    			    <br>
@@ -108,9 +132,8 @@
   						<img id="image" src="{% static 'applefruitmoth/applefruitmoth.png' %}" style="width:100%; height:auto;">
 						<p style="padding-left: 10px;padding-top: 5px;font-style: italic;">Foto: Sverre Kobro og E. Fløistad, NIBIO</p>
   					</div>
-  					<div class="col-md-1"></div>
   				</div>
-  	    		
+  	    		<div class="col-md-1"></div>
   	    		</div>	
   	    		<br>
   	    	</div>
@@ -130,7 +153,34 @@
 
 {% endblock %}
 {% block customCSS %}
+
+<!--[if lte IE 9]>
+  <style type="text/css">#oldIEWarning{display: block !important;}</style>
+<![endif]-->
+<link type="text/css" rel="stylesheet" href="https://logic.testvips.nibio.no/css/3rdparty/leaflet.css" />
+<link type="text/css" rel="stylesheet" href="https://logic.testvips.nibio.no/css/mapModal.css" />
 <link rel="stylesheet" href="{% static "css/3rdparty/ol.css" %}" type="text/css">
+
+<style>
+	input#latitude, input#longitude {
+		width: 30%;
+		display: inline-block;
+		margin: 10px 10px 10px 0;
+	}
+	select#weatherStationId {
+		width: 60%;
+		display: inline-block;
+		margin: 10px 10px 10px 0;
+	}
+	.main-label {
+		font-size: 1.8rem;
+		font-weight: 500 !important;
+	}
+	.space {
+		margin-top: 40px;
+	}
+</style>
+
 {% endblock %}
 {% block customJS %}
 <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.1/chart.min.js"></script>
@@ -151,4 +201,68 @@
 		
 	});
 </script>
+<script type="module">
+	import MapModal from 'https://logic.testvips.nibio.no/js/mapModal.js';
+	//import MapModal from settings.vipslogicProtocol + "://" + settings.vipslogicServerName + "/js/mapModal.js"
+
+	const inputLatitudeElement = document.getElementById("latitude");
+	const inputLongitudeElement = document.getElementById("longitude");
+	const selectWeatherstationElement = document.getElementById("weatherStationId");
+	let poiIdList = []
+
+	let selectedPoint = null;
+	let selectedFeature = undefined;
+
+	function selectCoordinates(coordinatesData) {
+		const selectedLatitude = coordinatesData ? coordinatesData.latitude : undefined;
+		const selectedLongitude = coordinatesData ? coordinatesData.longitude : undefined;
+
+		if(selectedLatitude && selectedLongitude) {
+			inputLatitudeElement.value = selectedLatitude;
+			inputLongitudeElement.value = selectedLongitude;
+		}
+	}
+
+	window.openCoordinatesMap = () => {
+		if (inputLatitudeElement.value && inputLongitudeElement.value) {
+			selectedPoint = 1;
+			selectedFeature = { 
+				"type": "FeatureCollection", "features": [
+					{
+						"type": "Feature",
+						"geometry": {
+							"type": "Point",
+							"coordinates": [parseFloat(inputLongitudeElement.value), parseFloat(inputLatitudeElement.value)]
+						},
+						"properties": {
+							"pointOfInterestId": selectedPoint,
+						}
+					}]
+			};
+		} else {
+			selectedPoint = undefined;
+			selectedFeature = undefined;
+		}
+
+		// TODO Open map with currently selected language! (not 'nb')
+
+		const isPoiMap = false; // Map should enable selection of coordinates (not pois)
+        const allowNewPoints = true; // User should be able to select new pois
+        const coordinatesMapInstance = new MapModal('coordinates-map', selectedFeature, 'nb', isPoiMap, allowNewPoints, selectCoordinates);
+		coordinatesMapInstance.openModal(selectedPoint);
+		console.info("open map");
+	}
+
+	window.displayCoordinatesInput = (id) => {
+		document.getElementById("coordinates").checked = true;
+		document.getElementById('weatherstationDiv').style.display = 'none';
+		document.getElementById('input-coordinates').style.display="block";
+	}
+
+	window.displayWeatherstationInput = (id) => {
+		document.getElementById('weatherstationDiv').style.display = 'block';
+		document.getElementById('input-coordinates').style.display="block";	
+		useWeatherstation();
+	}
+</script>    
 {% endblock %}
\ No newline at end of file
-- 
GitLab