/*
//  =============================================================================
//  ===                                                                       ===
//  === JS script programmed by: SHEA Yu-kai Geoffrey, Ph.D.                  ===
//  === Last updated: 05-APR-2025                                             ===
//  ===                                                                       ===
//  === Important Notice: USE THE FOLLOWING SCRIPT AT YOUR OWN RISK!          ===
//  ===                                                                       ===
//  =============================================================================
*/


/*
=========================================================================================
====
==== GeoJSON layer (AJAX request to the same server - webgis26-wl8645.xyz)
==== Data source: CSDI, Hong Kong
====
-----------------------------------------------------------------------------------------
*/
function universityOnEachFeature_v1(feature, layer) {
	var popupContent = '';
	popupContent = feature.properties.Facility_Name_EN;
	popupContent += '<br />['+ feature.properties.Website_EN;
	popupContent += ']';
	layer.bindPopup(popupContent);
}
var universities_csdi_v1 = new L.GeoJSON.AJAX('./files-geojson/UGCFundedInstitutions_GEOJSON.json', {
	onEachFeature: universityOnEachFeature_v1
});
/*
==== ------------------------------------------------------------------------------------
==== End of universities_csdi_v1
==== ====================================================================================
*/


/*
=========================================================================================
====
==== GeoJSON layer (AJAX request to the same server - webgis26-wl8645.xyz)
==== Data source: CSDI, Hong Kong
====
-----------------------------------------------------------------------------------------
*/
function universityOnEachFeature_v2(feature, layer) {
	var popupContent = '';
	popupContent = feature.properties.Facility_Name_EN;
	popupContent += '<br />'+ feature.properties.Facility_Name_TC;
	layer.on({
		mouseover: function (e) {
			layer.bindPopup(popupContent);
			layer.openPopup();
		},
		mouseout: function (e) {
			layer.closePopup();
		}
	});
}
var geojsonMarkerOptions = {
	radius: 8,
	fillColor: "#ff7800",
	color: "#000",
	weight: 1,
	opacity: 1,
	fillOpacity: 0.8
};
var universities_csdi_2 = new L.GeoJSON.AJAX('./files-geojson/UGCFundedInstitutions_GEOJSON.json', {
	pointToLayer: function (feature, latlng) {
		return L.circleMarker(latlng, geojsonMarkerOptions);
	},
	onEachFeature: universityOnEachFeature_v2
});
/*
==== ------------------------------------------------------------------------------------
==== End of universities_csdi_2
==== ====================================================================================
*/


/*
=========================================================================================
====
==== Data source: CSDI, Hong Kong
==== The SRS of the original data source was EPSG:2326.
==== It was converted to EPSG:4326 using ogr2ogr.exe
====
-----------------------------------------------------------------------------------------
*/
var selection_v1;
var selectedLayer_v1;

function districtStyle_v1(feature) {
	return {
		fillColor: "#ff0",
		color: "#00f",
		weight: '1',
		fillOpacity: 0.05
	};
}
function districtSelectedStyle_v1(feature) {
	return {
		fillColor: "#00FFFB",
		color: "#00f",
		weight: '1',
		fillOpacity: 0.25
	};
}
function districtOnEachFeature_v1(feature, layer) {
	layer.on({
		mouseover: function(e) {
			var popupMessageDistrict = feature.properties.NAME_EN;
			popupMessageDistrict += '<br />';
			popupMessageDistrict += feature.properties.NAME_TC;
			layer.bindPopup(popupMessageDistrict);
			layer.openPopup();
		},
		mouseout: function(e) {
			layer.closePopup();
		}
	});
}

var districts_csdi_v1 = new L.GeoJSON.AJAX('./files-geojson/csdi_district_4326.json', {
	style: districtStyle_v1,
	onEachFeature: districtOnEachFeature_v1
});
/*
==== ------------------------------------------------------------------------------------
==== End of districts_csdi_v1
==== ====================================================================================
*/


// Map data copyright
var attrOSM = 'Map data &copy; OpenStreetMap';
var attrLandsD = 'Map data &copy; The Government of the Hong Kong SAR <img src="https://api.hkmapservice.gov.hk/mapapi/landsdlogo.jpg" alt="Lands Department" style="width:15px;height:15px;">';

// Define each layer
var wms_layer_world = L.tileLayer.wms('https://webgis26-wl8645.xyz/geoserver/ne/wms', {
	layers: 'ne:world',
	format: 'image/png',
	transparent: true,
	maxZoom: 10,
	minZoom: 1,
	attribution: attrOSM
});
var osm = L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png', {
	maxZoom: 19,
	attribution: '&copy; OpenStreetMap'
});
var openTopoMap = L.tileLayer('https://{s}.tile.opentopomap.org/{z}/{x}/{y}.png', {
	maxZoom: 19,
	attribution: 'Map data: &copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors, <a href="http://viewfinderpanoramas.org">SRTM</a> | Map style: &copy; <a href="https://opentopomap.org">OpenTopoMap</a> (<a href="https://creativecommons.org/licenses/by-sa/3.0/">CC-BY-SA</a>)'
});

// === =====-======-==========-==========-======-===== ===
// === Maps from Lands Department, Government of HKSAR ===
// ===        v v v v v            v v v v v           ===

var mbUrlImagery = 'https://mapapi.geodata.gov.hk/gs/api/v1.0.0/xyz/imagery/WGS84/{z}/{x}/{y}.png';
var imageryMapNoLabel = L.tileLayer(mbUrlImagery, {
	subdomains: ['a', 'b', 'c'],
	minZoom:4,
	maxZoom: 19,
	attribution: attrLandsD
});
var basemap_imagery_en = L.layerGroup.hongKong("imagery.en");
var basemap_topography_en = L.layerGroup.hongKong("topography.en");
var basemap_topography_tc = L.layerGroup.hongKong("topography.tc");
var basemap_topography_sc = L.layerGroup.hongKong("topography.sc");

// ===        ^ ^ ^ ^ ^            ^ ^ ^ ^ ^           ===
// === =====-======-==========-==========-======-===== ===
//

var my_poi = new L.LayerGroup();
var a_marker = L.marker([22.30964,113.91572], {icon: L.AwesomeMarkers.icon({icon: '',prefix: 'fa',markerColor: 'blue',spin:false})}).bindPopup("Hong Kong international Airport<br />香港國際機場<br />香港国际机场").addTo(my_poi);
var population_hk = new L.LayerGroup();
var pop_2025 = L.marker([22.39766,114.13422], {icon: L.AwesomeMarkers.icon({icon: '',prefix: 'fa',markerColor: 'green',spin:false})}).bindPopup("7,400,865<br />(30-MAR-2025)</br />[<b>Unofficial data</b>]").addTo(population_hk);
var universities = new L.LayerGroup();
for (var m=0; m < universityMarkers.length; ++m) {
	L.marker([universityMarkers[m].lat, universityMarkers[m].lng], {icon: L.AwesomeMarkers.icon({icon: '',prefix: 'fa',markerColor: 'orange',spin:false,html: universityMarkers[m].pkuid})})
		.bindPopup(universityMarkers[m].pkuid + '<br />' + universityMarkers[m].text_note)
		.addTo(universities);
}

// Define map object
var map = L.map('map_canvas', {
	center: [22.39766,114.13422],
	zoom: 10,
	zoomControl: false,
	layers: [wms_layer_world]
});

// Define base layers (group of layers)
var baseLayers = {
	'World Map': wms_layer_world
};

// Define overlays (group of layers) (initially, it can be empty and layer(s) can be added later)
var overlays = {
};

// Add layer control on the map object
var layerControl = L.control.layers(baseLayers, overlays).addTo(map);

// Add control on the map object
L.control.zoomLabel({position: 'topleft'}).addTo(map);
var zoom_bar = new L.Control.ZoomBar({position: 'topleft'}).addTo(map);
L.control.coordinates({
	position: "bottomright",
	decimals: 5,
	useLatLngOrder: true
}).addTo(map);
L.control.scale().addTo(map);


// Add layer to base layers
layerControl.addBaseLayer(osm, 'OpenStreetMap');
layerControl.addBaseLayer(openTopoMap, 'OpenTopoMap');
layerControl.addBaseLayer(imageryMapNoLabel,"Imagery Map (No labels)");
layerControl.addBaseLayer(basemap_imagery_en,"Imagery Map (EN)");
layerControl.addBaseLayer(basemap_topography_en,"Hong Kong Map (EN)");
layerControl.addBaseLayer(basemap_topography_tc,"Hong Kong Map (TC)");
layerControl.addBaseLayer(basemap_topography_sc,"Hong Kong Map (SC)");

// Add layer to overlays
layerControl.addOverlay(my_poi, "<img src='images/pinBlue.png' height='24px' /> POI");
layerControl.addOverlay(population_hk, "<img src='images/pinGreen.png' height='24px' /> Population");
layerControl.addOverlay(universities, "<img src='images/pinOrange.png' height='24px' /> Universities <span style='font-size:0.9em;'>(local GeoJSON file)</span>");
layerControl.addOverlay(universities_csdi_v1, "<img src='images/pinBlue.png' height='24px' /> Universities v1 <span style='font-size:0.9em;'>(AJAX request: webgis26-wl8645.xyz)</span>");
layerControl.addOverlay(universities_csdi_2, "Universities v2 <span style='font-size:0.9em;'>(AJAX request: webgis26-wl8645.xyz)</span>");
layerControl.addOverlay(districts_csdi_v1, "Districts [v1] <span style='font-size:0.9em;'>(AJAX request: webgis26-wl8645.xyz)</span>");
