@csn_chile/status_map_gnss
Version:
Mapa de status GNSS
421 lines (359 loc) • 10.6 kB
JavaScript
const fs=eval(require('graceful-fs'));
import 'ol/ol.css';
import './estilos.css';
import Map from 'ol/Map';
import View from 'ol/View';
import TileLayer from 'ol/layer/Tile';
import OSM from 'ol/source/OSM';
/*
Coordinate Transform
*/
import { fromLonLat } from 'ol/proj';
/* Controls for Map GUI */
import { defaults as defaultControls } from 'ol/control';
import MousePosition from 'ol/control/MousePosition';
import { createStringXY } from 'ol/coordinate';
/*
Características para marcadores, líneas, etc
*/
import Feature from 'ol/Feature';
import Point from 'ol/geom/Point';
import VectorSource from 'ol/source/Vector';
import VectorLayer from 'ol/layer/Vector';
import {
Circle as CircleStyle,
Fill,
Icon,
Stroke,
Style,
} from 'ol/style';
/* Tooltip for markers */
// import Overlay from 'ol/Overlay';
import Popup from 'ol-popup';
/* read files */
export function mousePosition() {
const mouseOpts = {
coordinateFormat: createStringXY(4),
projection: 'EPSG:4326',
className: 'custom-mouse-position',
targe: document.getElementById('mouse-position'),
undefinedHTML: ' ',
};
const mousePC = new MousePosition(mouseOpts);
return mousePC;
}
import Overlay from 'ol/Overlay';
export function getPopup(){
var container = document.getElementById('popup');
var content = document.getElementById('popup-content');
var closer = document.getElementById('popup-closer');
var overlay = new Overlay({
id:"popup",
element: container,
autoPan: true,
autoPanAnimation: {duration:250}
});
closer.onclick = function(){
overlay.setPosition(undefined);
closer.blur();
return false;
};
return {"container":container, "content":content, "closer":closer, "overlay":overlay};
}
export function startMap(targetMap, coordinate, mpc, init_zoom) {
var popup = getPopup();
const map = new Map({
controls: defaultControls().extend([mpc]),
target: targetMap,
layers: [
new TileLayer({
source: new OSM(),
}),
],
overlays:[popup.overlay],
view: new View({
center: coordinate,
zoom: init_zoom,
}),
});
map.popup = popup;
return map;
}
export function mouseChange(projectionId, mousePC) {
const projectionSelect = document.getElementById(projectionId);
projectionSelect.addEventListener('change', (event) => {
mousePC.setProjection(event.target.value);
});
const precisionInput = document.getElementById('precision');
precisionInput.addEventListener('change', (event) => {
const format = createStringXY(event.target.valueAsNumber);
mousePC.setCoordinateFormat(format);
});
}
/*
Cargar marcador en el mapa
*/
// Estilos de marcador
// Read svg
import {svgMarker} from './svg_tpl';
export function loadMarkers() {
//const path=new pwd();
const iconSvgPath = __dirname+'/img/gnss.tpl.svg';
/* console.log("read", iconSvgPath, fs);
const svgMarker = fs.readFileSync(iconSvgPath, 'utf8');
console.log("Marker svg", svgMarker);*/
const markerColors = {
rtx: '#0092e8',
no_rtx: 'red',
no_csn: 'orange',
};
const regex = '#0092e8';
/* Insert in html the marker */
const markers = {};
Object.keys(markerColors).forEach((elem) => {
const marker = svgMarker.replace(regex, markerColors[elem]);
const dataSvg = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(marker)}`;
markers[elem] = dataSvg;
});
return markers;
}
export function loadIcons(markers) {
const icons = {};
Object.keys(markers).forEach((elem) => {
const iconPosition = {
src: markers[elem],
imgSize: [363, 480],
opacity: 1,
scale: 0.06,
anchor: [0.5, 1],
anchorXUnits: 'fraction',
anchorYUnits: 'fraction',
};
icons[elem] = new Icon(iconPosition);
});
return icons;
}
export function loadStyles(markers, icons) {
const svgStyles = {};
Object.keys(markers).forEach((elem) => {
const svgStyle = new Style({ image: icons[elem] });
svgStyles[elem] = svgStyle;
});
const iconPath = './img/gnss.png';
const styles = {
route: new Style({
stroke: new Stroke({
width: 6,
color: [237, 212, 0, 0.8],
}),
}),
icon: new Style({
image: new Icon({
anchor: [0.5, 1],
src: iconPath,
}),
}),
geoMarker: new Style({
image: new CircleStyle({
radius: 7,
fill: new Fill({ color: 'black' }),
stroke: new Stroke({
color: 'white',
width: 2,
}),
}),
}),
rtx: svgStyles.rtx,
no_rtx: svgStyles.no_rtx,
no_csn: svgStyles.no_csn,
};
return styles;
}
//
// fin estilos
/*
Posicionar marcadores
*/
export function createStationList(stationList) {
if (stationList){
if (stationList.length === 0) {
const newStationList = [
{ type: 'rtx', pos: { lat: -25.36, lon: -71.361 }, code: 'valn',name:"Valparaíso" },
{ type: 'no_rtx', pos: { lat: -26.36, lon: -71.561 }, code: 'trpd',name:"Torpederas" },
{ type: 'rtx', pos: { lat: -28.36, lon: -71.361 }, code: 'qtay',name:"Quintay" },
{ type: 'rtx', pos: { lat: -30.36, lon: -70.51 }, code: 'ccsn',name:"Casona CSN" },
{ type: 'no_csn', pos: { lat: -41.36, lon: -70.61 }, code: 'atjn', name:"Atajaña" },
{ type: 'no_rtx', pos: { lat: -38.36, lon: -70.361 }, code: 'bing', name:"Bahía Inglesa" },
];
return newStationList;
}
return stationList;}
else{
return [];}
}
export function getStationList(stationsId) {
const jsonData = document.getElementById(stationsId).textContent;
let stationList = [];
if (jsonData.trim().length > 0) {
stationList = JSON.parse(jsonData);
}
stationList = createStationList(stationList);
return stationList;
}
// transforma una lista de datos,
// a una lista que entiende openlayers
// Añadir a layer
export function data2feature(dataList) {
const featuresMarkers = [];
dataList.forEach((elem) => {
const coordinate = fromLonLat([elem.pos.lon, elem.pos.lat]);
const feature = new Feature({
type: elem.type,
geometry: new Point(coordinate),
name: 'station' in elem ? elem.code : 'stgo',
});
// const featProperties = feature.getProperties();}
feature.control = true;
feature.data = elem;
featuresMarkers.push(feature);
});
return featuresMarkers;
}
/*
Definición de function de estilos
*/
const markers = loadMarkers();
const icons = loadIcons(markers);
const styles = loadStyles(markers, icons);
export function styleFeature(feature) {
return styles[feature.get('type')];
}
/*
Cargar marcadores y estilos en vectorlayer
*/
// features_markers=features_markers.concat([gnssMarker, svg_gnssMarker]);
export function features2source(featuresMarkers) {
const vectorLayer = new VectorLayer({
source: new VectorSource({
features: featuresMarkers,
}),
style: styleFeature,
});
return vectorLayer;
}
/*
Tooltip factory
*/
/*
Show when mouse is hovering over the marker
*/
export function tooltipName(ids, title) {
const htmlList = [
`<div class='tooltip'>
<div class='station'>`,
ids,
`</div>
<div class='name'>`,
title,
`</div>
</div>`,
];
const html = ''.concat(...htmlList);
return html;
}
/*
Activar eventos relacionados a acciones sobre marcadores
*/
export function searchHTMLcontent(elements, ids) {
const list = [];
if(elements){
Array.from(elements).forEach( (elem) => {
const idList = elem.id.split(' ');
if (idList.includes(ids)) {
list.push(elem.innerHTML);
}
});}
return list;
}
/* var popup = new Overlay({
element: element,
positioning: 'top-center',
stopEvent: true,
offset: [-75,-150]
}); */
import {toStringHDMS} from 'ol/coordinate';
import {toLonLat} from 'ol/proj';
export function generatePopup(data){
var html = `<section class="section" id="popup-section">
<h5 class="title is-5">${data.name}</h5>
<table class="table">
<tr>
<td>Código</td><td>${data.code}</td>
</tr>
<tr>
<td>Tipo</td><td>${data.type}</td>
</tr>
<tr>
<td>Posición (lat,lon)</td><td>(${data.pos.lat.toFixed(3)}, ${data.pos.lon.toFixed(3)})</td>
</tr>
<tr>
<td>Ver detalle</td><td>${data.detail}</td>
</tr>
</table>
</section>`;
return html;
}
export function mapClick(map) {
const popup = map.popup;
const elements = document.getElementsByClassName('popup');
map.on('click', (event) => {
const featureMap = map.forEachFeatureAtPixel(event.pixel, (feature) => {
let fc = false;
if (feature.control) {
fc = true;
} else {
fc = false;
}
return feature;
});
const [w,h] = map.getSize();
if (featureMap) {
const coordinates = featureMap.getGeometry().getCoordinates();
var data = featureMap.data;
var html = generatePopup(data);
map.popup.content.innerHTML = html;
var overlay = map.getOverlayById("popup");
const element = document.querySelector('.ol-popup');
const style = getComputedStyle(element);
if (w<=500){
const new_width=0.6*w;
document.getElementById("popup").style.width = new_width+"px";}
else{
document.getElementById("popup").style.width = 200+"px";
}
overlay.setPosition(coordinates);
}
});
}
/*
Init section
*/
export function defaultInit(mapID, stationList, init_zoom) {
const position = {
lat: -28.366,
lon: -70.3661,
};
const coordinate = fromLonLat([position.lon, position.lat]);
const mousePositionControl = mousePosition(position);
const map = startMap(mapID, coordinate, mousePositionControl, init_zoom);
//mouseChange('projection', mousePositionControl);
// Crear Features list
const featuresMarkers = data2feature(stationList);
const vectorLayer = features2source(featuresMarkers);
map.addLayer(vectorLayer);
/* Agregar vectorlayer a mapa
*/
/* activate click on map */
mapClick(map);
return map;
}