Improvement in Subs and FireMap Union

This commit is contained in:
vjrj 2017-12-19 20:02:14 +01:00
parent 497724443f
commit 1742cd4913
19 changed files with 390 additions and 299 deletions

View file

@ -42,7 +42,8 @@ Subscriptions.schema = new SimpleSchema({
'location.lat': Number,
'location.lon': Number,
distance: Number,
owner: String
owner: String,
type: String
});
Subscriptions.attachSchema(Subscriptions.schema);

View file

@ -9,9 +9,10 @@ Meteor.methods({
location: Match.ObjectIncluding({ lat: Number, lon: Number }),
distance: Number
});
const type = 'web';
try {
return Subscriptions.insert({ owner: this.userId, ...doc });
return Subscriptions.insert({ owner: this.userId, type, ...doc });
} catch (exception) {
throw new Meteor.Error('500', exception);
}

View file

@ -18,21 +18,24 @@ Meteor.publishTransformed('userSubsToFires', function transform() {
const location = doc.location;
/* doc.lat = location.lat;
* doc.lon = location.lon; */
let lat;
let lon;
if (location) {
doc.lat = Math.round(location.lat * 10) / 10;
doc.lon = Math.round(location.lon * 10) / 10;
lat = Math.round(location.lat * 10) / 10;
lon = Math.round(location.lon * 10) / 10;
// console.log(`[${lat}, ${lon}]`);
const noiseBase = Perlin.perlin2(lat, lon);
const noise = Math.abs(noiseBase / 3);
// console.log(`Noise ${noise}, abs: ${Math.abs(noise)}`);
lat += noise;
lon += noise;
doc.location.lat = lat;
doc.location.lon = lon;
doc.distance += noiseBase;
}
// console.log(`[${doc.lat}, ${doc.lon}]`);
const noiseBase = Perlin.perlin2(doc.lat, doc.lon);
const noise = Math.abs(noiseBase / 3);
// console.log(`Noise ${noise}, abs: ${Math.abs(noise)}`);
doc.lat += noise;
doc.lon += noise;
doc.distance += noiseBase;
// console.log(`with noise: [${doc.lat}, ${doc.lon}]`);
delete doc.chatId;
delete doc.geo;
delete doc.location;
return doc;
});
});

View file

@ -5,6 +5,9 @@ import LngDetector from 'i18next-browser-languagedetector';
import Cache from 'i18next-localstorage-cache';
import { T9n } from 'meteor-accounts-t9n';
import moment from 'moment';
import 'moment/locale/es';
import 'moment/locale/pt';
import 'moment/locale/gl';
import i18nOpts from '../common/i18n';
// Adapted from: https://github.com/appigram/ryfma-boilerplate/blob/44c1eabfb9928b5623afab36a23997969e5beb02/imports/startup/client/i18n.js
@ -61,6 +64,8 @@ i18n.use(backend)
T9n.setLanguage(i18n.language);
// console.log(T9n.get('error.accounts.User not found'));
moment.locale(i18n.language);
// cookies eu consent
const cookiesOpt = {
cookieTitle: t('Uso de Cookies'),

View file

@ -16,12 +16,12 @@ import NavItem from '../NavItem/NavItem';
const AuthenticatedNavigation = ({ name, history, props }) => (
<ul className="navbar-nav">
{/* <Nav pullRight> */}
<LinkContainer className="nav-item" anchorClassName="nav-link" to="/documents">
<NavItem eventKey={5} href="/documents">Documents</NavItem>
</LinkContainer>
<LinkContainer className="nav-item" anchorClassName="nav-link" to="/documents">
<NavItem eventKey={5.01} href="/subscriptions">Subscriptions</NavItem>
</LinkContainer>
{/* <LinkContainer className="nav-item" anchorClassName="nav-link" to="/documents">
<NavItem eventKey={5} href="/documents">Documents</NavItem>
</LinkContainer> */}
{/* <LinkContainer className="nav-item" anchorClassName="nav-link" to="/subscriptions">
<NavItem eventKey={5} href="/subscriptions"><Trans>Mis alertas</Trans></NavItem>
</LinkContainer> */}
<LinkContainer className="nav-item" anchorClassName="nav-link" to="/profile">
<NavItem eventKey={5.1} href="/profile">{name}</NavItem>
</LinkContainer>
@ -34,7 +34,6 @@ const AuthenticatedNavigation = ({ name, history, props }) => (
AuthenticatedNavigation.propTypes = {
name: PropTypes.string.isRequired
};
export default translate([], { wait: true })(withRouter(AuthenticatedNavigation));

View file

@ -0,0 +1,78 @@
/* eslint-disable react/jsx-indent-props */
/* eslint-disable import/no-absolute-path */
/* eslint-disable import/no-absolute-path */
/* global L */
import { Map } from 'react-leaflet';
import LGeo from 'leaflet-geodesy';
import tunion from '@turf/union';
import { check, Match } from 'meteor/check';
// https://stackoverflow.com/questions/35394577/leaflet-js-union-merge-circles
function unify(polyList) {
let unionTemp;
for (let i = 0; i < polyList.length; i += 1) {
if (i === 0) {
unionTemp = polyList[i].toGeoJSON();
} else {
unionTemp = tunion(unionTemp, polyList[i].toGeoJSON());
}
}
return unionTemp;
}
const subsUnion = (union, options) => {
// check(union, Match.Optional(Object));
check(options, {
map: Map,
show: Boolean,
subs: [Object],
color: Match.Optional(String),
fillcolor: Match.Optional(String),
opacity: Match.Optional(Number),
fit: Boolean
});
const color = options.color || '#145A32';
const fillColor = options.fillColor || 'green';
const opacity = options.options || 0.1;
if (options.subs.length > 0) {
const lmap = options.map.leafletElement;
// http://leafletjs.com/reference-1.2.0.html#layergroup
// FeatureGroup has getBounds
const unionGroup = new L.FeatureGroup();
if (union) {
lmap.removeLayer(union);
}
union = null;
if (options.show) {
// http://leafletjs.com/reference-1.2.0.html#path
const copts = {
parts: 144
};
options.subs.forEach((sub) => {
const circle = LGeo.circle([sub.location.lat, sub.location.lon], sub.distance * 1000, copts);
circle.addTo(unionGroup);
});
const unionJson = unify(unionGroup.getLayers());
union = L.geoJson(unionJson);
union.setStyle({
color,
fillColor,
fillOpacity: opacity
});
union.addTo(lmap);
if (options.fit) {
options.map.leafletElement.fitBounds(unionGroup.getBounds());
}
return union;
}
}
return union;
};
export default subsUnion;

View file

@ -1,15 +0,0 @@
/* global L */
// https://stackoverflow.com/questions/35394577/leaflet-js-union-merge-circles
import union from '@turf/union';
export function unify(polyList) {
let unionTemp;
for (let i = 0; i < polyList.length; i += 1) {
if (i === 0) {
unionTemp = polyList[i].toGeoJSON();
} else {
unionTemp = union(unionTemp, polyList[i].toGeoJSON());
}
}
return L.geoJson(unionTemp);
}

View file

@ -35,7 +35,7 @@ const Navigation = props => (
</LinkContainer> */}
<LinkContainer className="nav-item" anchorClassName="nav-link" to="/subscriptions">
<NavItem eventKey={1.2} href="/subscriptions">
{props.authenticated ? <Trans>Mis alertas</Trans> : <Trans>Participar</Trans>}
{props.authenticated ? <Trans>Mis zonas</Trans> : <Trans>Participar</Trans>}
</NavItem>
</LinkContainer>
<LinkContainer className="nav-item" anchorClassName="nav-link" to="/fires">

View file

@ -1,5 +1,6 @@
/* global setTimeout */
/* eslint-disable react/jsx-indent-props */
/* eslint-disable react/jsx-indent */
/* eslint-disable import/no-absolute-path */
/* eslint-disable import/no-absolute-path */
@ -7,7 +8,7 @@ import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Map, TileLayer, Marker, CircleMarker, Circle } from 'react-leaflet';
import Leaflet from 'leaflet';
import { Trans, translate } from 'react-i18next';
import { translate } from 'react-i18next';
import { withTracker } from 'meteor/react-meteor-data';
import update from 'immutability-helper';
import geolocation from '/imports/startup/client/geolocation';
@ -16,9 +17,8 @@ import 'leaflet-graphicscale/dist/Leaflet.GraphicScale.min.css';
import 'leaflet-graphicscale/dist/Leaflet.GraphicScale.min.js';
import 'leaflet-sleep/Leaflet.Sleep.js';
import Control from 'react-leaflet-control';
import { Button, ButtonToolbar } from 'react-bootstrap';
import { Sidebar, Tab } from 'react-leaflet-sidebarv2';
import '/imports/ui/stylesheets/leaflet-sidebar.min.css';
import { Button, ButtonGroup } from 'react-bootstrap';
import subsUnion from '/imports/ui/components/Maps/SubsUnion/SubsUnion';
import './SelectionMap.scss';
class SelectionMap extends Component {
@ -27,11 +27,9 @@ class SelectionMap extends Component {
this.state = {
center: props.center,
marker: props.center,
zoom: 11,
zoom: props.zoom,
distance: props.distance,
draggable: true,
sidebarCollapsed: true,
sidebarSelected: 'home'
draggable: true
};
this.getMap = this.getMap.bind(this);
@ -39,7 +37,8 @@ class SelectionMap extends Component {
this.updatePosition = this.updatePosition.bind(this);
this.fit = this.fit.bind(this);
this.addScale = this.addScale.bind(this);
this.onSubs = this.onSubs.bind(this);
this.onFstBtn = this.onFstBtn.bind(this);
this.onViewportChanged = this.onViewportChanged.bind(this);
}
componentDidMount() {
@ -56,20 +55,30 @@ class SelectionMap extends Component {
marker: nextMarker,
distance: nextProps.distance || this.state.distance
});
this.fit();
// this.fit();
}
componentDidUpdate() {
this.fit();
// this.fit();
}
onSubs() {
this.props.onSubs({
onFstBtn() {
this.props.onFstBtn({
location: { lat: this.state.center[0], lon: this.state.center[1] },
distance: this.state.distance
});
}
onSndBtn() {
this.props.onSndBtn();
}
onViewportChanged(viewport) {
if (this.props.onViewportChanged) {
this.props.onViewportChanged(viewport);
}
}
getMap() {
return this.selectionMap.leafletElement;
}
@ -83,101 +92,66 @@ class SelectionMap extends Component {
// console.log(`New marker lat ${lat} and lng ${lng}`);
const currentDistance = this.state.distance;
this.setState(update(this.state, { $merge: { marker: [lat, lng] } }));
this.props.onSelection({ lat, lng, currentDistance });
if (this.props.onSelection) {
this.props.onSelection({ lat, lng, currentDistance });
}
this.fit();
// this.addScale();
}
fit() {
// console.log("fit!");
if (this.selectionMap && this.distanceCircle) {
if (this.subsUnionElement) {
// has autofit
} else if (this.selectionMap && this.distanceCircle) {
this.getMap().fitBounds(this.distanceCircle.leafletElement.getBounds(), [70, 70]);
}
}
addScale() {
// https://www.npmjs.com/package/leaflet-graphicscale
const map = this.getMap();
const options = {
fill: 'fill',
showSubunits: true
};
// var graphicScale =
Leaflet.control.graphicScale([options]).addTo(map);
if (this.selectionMap) {
// https://www.npmjs.com/package/leaflet-graphicscale
const map = this.getMap();
const options = {
fill: 'fill',
showSubunits: true
};
// var graphicScale =
Leaflet.control.graphicScale([options]).addTo(map);
}
}
isValidState() {
return this.state.center && this.state.center[0] && this.state.distance;
return this.state.center && this.state.center[0];
}
onSidebarClose() {
this.setState({ sidebarCollapsed: true });
}
onSidebarOpen(id) {
this.setState({
sidebarCollapsed: false,
sidebarSelected: id
});
}
aTab(oid, name) {
return (
<Tab id={`sidetab-${oid}`} header={name} icon="fa fa-map-marker">
<div className="btn-group-vertical sidebar-tab-btn-group">
<Button
bsStyle="default"
><i className="fa fa-pencil-square-o" />
<Trans>Editar</Trans>
</Button>
<Button
bsStyle="default"
><i className="icons icon-target" />
<Trans>Centrar aquí</Trans>
</Button>
<Button
bsStyle="default"
>
<Trans>Desahabilitar</Trans>
</Button>
<Button
bsStyle="danger"
><i className="fa fa-times" />
<Trans>Borrar</Trans>
</Button>
</div>
</Tab>
);
handleLeafletLoad(map) {
if (this.props.readOnly && this.props.currentSubs && map && !this.props.loadingSubs) {
this.state.union = subsUnion(this.state.union, {
map,
show: true,
fit: true,
subs: this.props.currentSubs
});
}
}
render() {
// console.log('render map called');
return (
<div>
{ this.isValidState() &&
<div className="leaflet-container">
<Sidebar
id="sidebar"
collapsed={this.state.sidebarCollapsed}
selected={this.state.sidebarSelected}
closeIcon="fa fa-chevron-left"
onOpen={this.onSidebarOpen.bind(this)}
onClose={this.onSidebarClose.bind(this)}
>
<Tab id="home" header="Suscripciones" icon="fa fa-bars">
<p>Pulsa en alguna de tus suscripciones para editarlas, etc.</p>
</Tab>
{this.aTab('someid2', 'Some fire')}
{this.aTab('someid3', 'Some another fire')}
</Sidebar>
<Map
className="sidebar-map"
/* className="sidebar-map" */
center={this.state.center}
zoom={this.state.zoom}
ref={(map) => { this.selectionMap = map; }}
ref={(map) => {
this.selectionMap = map;
this.handleLeafletLoad(map);
}}
sleep={window.location.pathname === '/'}
sleepTime={10750}
wakeTime={750}
onViewportChanged={this.onViewportChanged}
sleepNote
hoverToWake
wakeMessage={this.props.t('Pulsa para activar')}
@ -187,6 +161,7 @@ class SelectionMap extends Component {
attribution="&amp;copy <a href=&quot;http://osm.org/copyright&quot;>OpenStreetMap</a> contributors"
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
{!this.props.readOnly &&
<Marker
draggable={this.state.draggable}
onDragend={this.updatePosition}
@ -194,7 +169,8 @@ class SelectionMap extends Component {
icon={positionIcon}
title={this.props.t('Arrastrar para seleccionar otro punto')}
ref={(ref) => { this.marker = ref; }}
/>
/> }
{!this.props.readOnly &&
<CircleMarker
center={this.state.marker}
color="red"
@ -202,7 +178,8 @@ class SelectionMap extends Component {
fillOpacity="1"
fill
radius={3}
/>
/> }
{!this.props.readOnly &&
<Circle
center={this.state.marker}
ref={(ref) => { this.distanceCircle = ref; }}
@ -210,16 +187,24 @@ class SelectionMap extends Component {
fillColor="green"
fillOpacity={0.1}
radius={this.state.distance * 1000}
/>
/> }
<Control position="topright" >
<ButtonToolbar>
<Button
bsStyle="success"
onClick={event => this.onSubs(event)}
>
{this.props.subsBtn}
</Button>
</ButtonToolbar>
<ButtonGroup>
{ this.props.sndBtn && this.props.onSndBtn &&
<Button
bsStyle="warning"
onClick={event => this.onSndBtn(event)}
>
{this.props.sndBtn}
</Button>
}
<Button
bsStyle="success"
onClick={event => this.onFstBtn(event)}
>
{this.props.fstBtn}
</Button>
</ButtonGroup>
</Control>
</Map>
</div>
@ -229,13 +214,28 @@ class SelectionMap extends Component {
}
}
SelectionMap.defaultProps = {
zoom: 11
};
SelectionMap.propTypes = {
t: PropTypes.func.isRequired,
center: PropTypes.arrayOf(PropTypes.number),
zoom: PropTypes.number,
distance: PropTypes.number,
onSelection: PropTypes.func.isRequired,
subsBtn: PropTypes.string.isRequired,
onSubs: PropTypes.func.isRequired
onSelection: PropTypes.func,
onViewportChanged: PropTypes.func,
fstBtn: PropTypes.string.isRequired,
onFstBtn: PropTypes.func.isRequired,
sndBtn: PropTypes.string,
onSndBtn: PropTypes.func,
readOnly: PropTypes.bool.isRequired,
edit: PropTypes.bool.isRequired,
loadingSubs: PropTypes.bool,
currentSubs: PropTypes.arrayOf(PropTypes.shape({
location: PropTypes.shape({ latitude: PropTypes.number, longitude: PropTypes.number }).isRequired,
distance: PropTypes.number.isRequired
}))
};
export default translate([], { wait: true })(withTracker(props => ({

View file

@ -26,9 +26,10 @@ class SubscriptionEditor extends React.Component {
if (error) {
Bert.alert(error.reason, 'danger');
} else {
const confirmation = existingSubscription ? t('Suscripción actualizada') : t('Suscripción añadida');
const confirmation = existingSubscription ? t('Zona actualizada') : t('Zona añadida');
Bert.alert(confirmation, 'success');
history.push(`/subscriptions/${subscriptionId}`);
// history.push(`/subscriptions/${subscriptionId}`);
history.push('/subscriptions');
}
});
}
@ -36,11 +37,12 @@ class SubscriptionEditor extends React.Component {
render() {
const { doc, t } = this.props;
const isEdit = doc && doc._id;
const focus = typeof this.props.focusInput !== 'undefined' ? this.props.focusInput : !isEdit;
return (
<FireSubscription
center={[doc.location.lat, doc.location.lon]}
distance={doc.distance}
focusInput={this.props.focusInput ? this.props.focusInput : !isEdit}
focusInput={focus}
subsBtn={isEdit ? t('Actualizar') : t('Subscribirme a fuegos en este rádio')}
onSubs={state => this.onSubs(state)}
/>

View file

@ -24,10 +24,6 @@ import Navigation from '../../components/Navigation/Navigation';
import Authenticated from '../../components/Authenticated/Authenticated';
import Public from '../../components/Public/Public';
import Index from '../../pages/Index/Index';
import Documents from '../../pages/Documents/Documents';
import NewDocument from '../../pages/NewDocument/NewDocument';
import ViewDocument from '../../pages/ViewDocument/ViewDocument';
import EditDocument from '../../pages/EditDocument/EditDocument';
import Subscriptions from '../../pages/Subscriptions/Subscriptions';
import NewSubscription from '../../pages/NewSubscription/NewSubscription';
import ViewSubscription from '../../pages/ViewSubscription/ViewSubscription';
@ -68,11 +64,11 @@ const App = props => (
<Grid> {/* bsClass="previously-container-but-disabled" > */}
<Switch>
<Route exact name="index" path="/" component={Index} />
<Authenticated exact path="/documents" component={Documents} {...props} />
{/* <Authenticated exact path="/documents" component={Documents} {...props} />
<Authenticated exact path="/documents/new" component={NewDocument} {...props} />
<Authenticated exact path="/documents/:_id" component={ViewDocument} {...props} />
<Authenticated exact path="/documents/:_id/edit" component={EditDocument} {...props} />
*/}
<Authenticated exact path="/subscriptions" component={Subscriptions} {...props} />
<Authenticated exact path="/subscriptions/new" component={NewSubscription} {...props} />
<Authenticated exact path="/subscriptions/:_id" component={ViewSubscription} {...props} />

View file

@ -28,6 +28,16 @@ class FireSubscription extends React.Component {
});
}
shouldComponentUpdate(nextProps, nextState) {
if (this.state.init &&
nextState.center === this.state.center &&
nextState.distance === this.state.distance) {
return false;
}
return true;
}
onAutocompleteChange(value) {
this.setState({ center: [value.lat, value.lng] });
}
@ -51,7 +61,7 @@ class FireSubscription extends React.Component {
render() {
// https://developers.google.com/places/web-service/search
// https://github.com/kenny-hibino/react-places-autocomplete/blob/master/demo/Demo.js
console.log(`Focus autocomplete input: ${this.props.focusInput}`);
if (!this.state.init) {
return <div />;
}
@ -77,9 +87,11 @@ class FireSubscription extends React.Component {
<SelectionMap
center={this.state.center}
distance={this.state.distance}
subsBtn={this.props.subsBtn}
fstBtn={this.props.subsBtn}
onFstBtn={state => this.onSubs(state)}
onSelection={state => this.onSelection(state)}
onSubs={state => this.onSubs(state)}
readOnly={false}
edit={false}
/>
</Row>
</div>

View file

@ -60,7 +60,7 @@ class SubsAutocomplete extends React.Component {
<form>
<FormGroup>
<ControlLabel>
<Trans parent="span">Indícanos la posición a vigilar (por ej. tu pueblo, una calle, etc):</Trans>
<Trans parent="span">Indícanos la posición de la zona a vigilar (por ej. tu pueblo, una calle, etc):</Trans>
</ControlLabel>
<PlacesAutocomplete
styles={myStyles}
@ -90,7 +90,7 @@ class SubsAutocomplete extends React.Component {
autoFocus: this.props.focusInput
}}
/>
<HelpBlock><Trans parent="span">También puedes seleccionar el lugar en el mapa arrastrando el puntero naranja.</Trans></HelpBlock>
<HelpBlock><Trans parent="span">También puedes seleccionar la zona en el mapa arrastrando el puntero naranja.</Trans></HelpBlock>
</FormGroup>
</form>
);

View file

@ -10,7 +10,6 @@ import { ReactiveVar } from 'meteor/reactive-var';
import { withTracker } from 'meteor/react-meteor-data';
import { Trans, translate } from 'react-i18next';
import { Map, TileLayer, LayersControl } from 'react-leaflet';
import LGeo from 'leaflet-geodesy';
import _ from 'lodash';
import 'leaflet/dist/leaflet.css';
import 'leaflet-graphicscale/dist/Leaflet.GraphicScale.min.css';
@ -19,7 +18,7 @@ import 'leaflet-sleep/Leaflet.Sleep.js';
import geolocation from '/imports/startup/client/geolocation';
import CenterInMyPosition from '/imports/ui/components/CenterInMyPosition/CenterInMyPosition';
import FireList from '/imports/ui/components/Maps/FireList';
import { unify } from '/imports/ui/components/Maps/Utils';
import subsUnion from '/imports/ui/components/Maps/SubsUnion/SubsUnion';
import Loading from '/imports/ui/components/Loading/Loading';
import ActiveFiresCollection from '/imports/api/ActiveFires/ActiveFires';
import FireAlertsCollection from '/imports/api/FireAlerts/FireAlerts';
@ -61,68 +60,24 @@ class FiresMap extends React.Component {
self.setState({ gkey: key });
});
mapSize.set([this.divElement.clientHeight, this.divElement.clientWidth]);
this.addScale();
if (this.fireMap) {
this.addScale();
}
}
/* componentWillReceiveProps(nextProps) {
* if (nextProps.loading) {
* // console.log('Loading new fires');
* }
* // this.setState({ loading: nextProps.loading });
* }
*/
/* shouldComponentUpdate(nextProps, nextState) {
* if (nextProps.loading) {
* return true; // false;
* }
* return true;
* }
*/
onViewportChanged(viewport) {
this.debounceView(viewport);
}
onClickReset() {
// console.log("onclick");
// this.setState({ viewport: DEFAULT_VIEWPORT })
}
getMap() {
return this.fireMap.leafletElement;
}
setShowSubsUnion(show) {
this.showSubsUnion(show);
}
showSubsUnion(show) {
const map = this.getMap();
// http://leafletjs.com/reference-1.2.0.html#layergroup
const unionGroup = new L.LayerGroup();
if (this.union) {
map.removeLayer(this.union);
}
if (show) {
// http://leafletjs.com/reference-1.2.0.html#path
const copts = {
parts: 144
};
UserSubsToFiresCollection.find().forEach((subs) => {
const circle = LGeo.circle([subs.lat, subs.lon], subs.distance * 1000, copts);
circle.addTo(unionGroup);
});
this.union = unify(unionGroup.getLayers());
this.union.setStyle({
color: '#145A32',
fillColor: 'green',
fillOpacity: 0.1
});
this.union.addTo(map);
}
setShowSubsUnion(showSubsUnion) {
this.setState({ showSubsUnion });
}
handleViewportChange(viewport) {
@ -135,14 +90,10 @@ class FiresMap extends React.Component {
zoom.set(viewport.zoom);
center.set(viewport.center);
this.setState({ viewport });
if (this.props.subsready && this.fireMap) {
this.showSubsUnion(this.state.showSubsUnion);
}
}
centerOnUserLocation(viewport) {
this.setState({ viewport });
// this.handleViewportChange(viewport);
}
useMarkers(use) {
@ -150,22 +101,29 @@ class FiresMap extends React.Component {
}
addScale() {
if (this.fireMap) {
// https://www.npmjs.com/package/leaflet-graphicscale
const map = this.getMap();
const options = {
fill: 'fill',
showSubunits: true
};
L.control.graphicScale([options]).addTo(map);
// https://www.npmjs.com/package/leaflet-graphicscale
const map = this.getMap();
const options = {
fill: 'fill',
showSubunits: true
};
L.control.graphicScale([options]).addTo(map);
}
handleLeafletLoad(map) {
console.log('Map loading');
console.log(map);
if (map) {
this.state.union = subsUnion(this.state.union, {
map,
subs: this.props.userSubs,
show: this.state.showSubsUnion,
fit: false
});
}
}
render() {
if (this.props.subsready && this.fireMap) {
// Show union of users
this.showSubsUnion(this.state.showSubsUnion);
}
console.log(`Rendering ${this.props.loading ? 'loading' : 'LOADED'} map ${this.props.activefires.length} of ${this.props.activefirestotal} total. Subs users ready ${this.props.subsready}, reactive ${this.state.viewport.zoom >= MAXZOOMREACTIVE}`);
const { t } = this.props;
const osmlayer = (
@ -181,7 +139,7 @@ class FiresMap extends React.Component {
<div
ref={(divElement) => { this.divElement = divElement; }}
>
{this.props.loading ?
{this.props.loading || !this.props.subsready ?
<Row className="align-items-center justify-content-center">
<Loading />
</Row>
@ -217,9 +175,11 @@ class FiresMap extends React.Component {
</Row>
<Row>
{/* https://github.com/CliffCloud/Leaflet.Sleep */}
<Map
ref={(map) => { this.fireMap = map; }}
ref={(map) => {
this.fireMap = map;
this.handleLeafletLoad(map);
}}
animate
minZoom={5}
preferCanvas
@ -277,6 +237,7 @@ class FiresMap extends React.Component {
FiresMap.propTypes = {
loading: PropTypes.bool.isRequired,
subsready: PropTypes.bool.isRequired,
userSubs: PropTypes.arrayOf(PropTypes.object).isRequired,
activefires: PropTypes.arrayOf(PropTypes.object).isRequired,
firealerts: PropTypes.arrayOf(PropTypes.object).isRequired,
activefirestotal: PropTypes.number.isRequired,
@ -312,7 +273,7 @@ export default translate([], { wait: true })(withTracker(() => {
// Warning with the performance of this log:
// console.log(`Active fires ${ActiveFiresCollection.find().count()} of ${Counter.get('countActiveFires')}`);
// console.log(`Active neighborhood fires ${FireAlertsCollection.find().fetch().length} and users subscribed ${UserSubsToFiresCollection.find().fetch().length}`);
// console.log(UserSubsToFiresCollection.find().fetch());
console.log(UserSubsToFiresCollection.find().fetch());
return {
loading: !subscription.ready(),
userSubs: UserSubsToFiresCollection.find().fetch(),

View file

@ -32,3 +32,7 @@
.mark-checkbox {
margin-left: 5px;
}
.leaflet-control-layers-toggle {
background-image: url(/images/layers.png);
}

View file

@ -5,7 +5,7 @@ import SubscriptionEditor from '../../components/SubscriptionEditor/Subscription
const NewSubscription = ({ history }) => (
<div className="NewSubscription">
<h4 className="page-header"><Trans>Nueva suscripción</Trans></h4>
<h4 className="page-header"><Trans>Nueva zona</Trans></h4>
<SubscriptionEditor history={history} />
</div>
);

View file

@ -2,99 +2,143 @@
/* eslint-disable import/no-absolute-path */
/* eslint-disable react/jsx-indent */
import React from 'react';
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Link } from 'react-router-dom';
import { Table, Alert, Button, Row } from 'react-bootstrap';
import { timeago, monthDayYearAtTime } from '@cleverbeagle/dates';
import { Table, Alert, Button } from 'react-bootstrap';
import { timeago } from '@cleverbeagle/dates';
import { Meteor } from 'meteor/meteor';
import { withTracker } from 'meteor/react-meteor-data';
import { Trans, translate } from 'react-i18next';
import { Bert } from 'meteor/themeteorchef:bert';
import UserSubsToFiresCollection from '/imports/api/Subscriptions/Subscriptions';
import SelectionMap from '/imports/ui/components/SelectionMap/SelectionMap';
import Loading from '../../components/Loading/Loading';
import './Subscriptions.scss';
const handleRemove = (subscriptionId) => {
if (confirm('Are you sure? This is permanent!')) {
Meteor.call('subscriptions.remove', subscriptionId, (error) => {
if (error) {
Bert.alert(error.reason, 'danger');
} else {
Bert.alert('Subscription deleted!', 'success');
}
});
class Subscriptions extends Component {
constructor(props) {
super(props);
this.t = props.t;
this.state = {
edit: false
};
this.onViewportChanged = this.onViewportChanged.bind(this);
this.onFstBtn = this.onFstBtn.bind(this);
this.onSndBtn = this.onSndBtn.bind(this);
}
};
const Subscriptions = ({
loading,
subscriptions,
match,
history
}) => (!loading ? (
<div className="Subscriptions">
<div className="page-header clearfix">
<h4 className="pull-left"><Trans>Suscripciones a fuegos en áreas de mi interés</Trans></h4>
<Link className="btn btn-success pull-right" to={`${match.url}/new`}><Trans>Añadir suscripción</Trans></Link>
</div>
<br />
{subscriptions.length ?
<Table responsive>
<thead>
<tr>
<th>Location</th>
<th>Last Updated</th>
<th>Created</th>
<th />
<th />
</tr>
</thead>
<tbody>
{subscriptions.map(({
_id,
location,
createdAt,
updatedAt
}) => (
<tr key={_id}>
<td>{location.lat},{location.lon}</td>
<td>{timeago(updatedAt)}</td>
<td>{monthDayYearAtTime(createdAt)}</td>
<td>
<Button
bsStyle="primary"
onClick={() => history.push(`${match.url}/${_id}`)}
block
>View
</Button>
</td>
<td>
<Button
bsStyle="danger"
onClick={() => handleRemove(_id)}
block
>Delete
</Button>
</td>
</tr>
))}
</tbody>
</Table> :
<Alert bsStyle="warning"><Trans>Todavía sin suscriptiones</Trans></Alert>
onFstBtn(value) {
// ${match.url}/new
}
onSndBtn() {
this.state.edit = true;
}
onViewportChanged(viewport) {
this.state.center = viewport.center;
this.state.zoom = viewport.zoom;
}
handleRemove(subscriptionId) {
if (confirm('Are you sure? This is permanent!')) {
Meteor.call('subscriptions.remove', subscriptionId, (error) => {
if (error) {
Bert.alert(error.reason, 'danger');
} else {
Bert.alert('Subscription deleted!', 'success');
}
});
}
</div>
) : <Loading />);
}
render() {
const {
loading,
t,
subscriptions,
match,
history
} = this.props;
return (!loading ? (
<div className="Subscriptions">
<div className="page-header clearfix">
<h4 className="pull-left"><Trans>Suscripciones a fuegos en zonas de mi interés</Trans></h4>
<Link className="btn btn-success pull-right" to={`${match.url}/new`}><Trans>Añadir zona</Trans></Link>
</div>
<br />
<SelectionMap
center={[null, null]}
zoom={11}
readOnly
edit={this.state.edit}
fstBtn={t('Añadir zona')}
onFstBtn={state => this.onFstBtn(state)}
sndBtn={this.props.subscriptions.length > 1 ? t('Editar') : null}
onSndBtn={() => this.onSndBtn()}
onViewportChanged={viewport => this.onViewportChanged(viewport)}
loadingSubs={this.props.loading}
currentSubs={this.props.subscriptions}
/>
{subscriptions.length ?
<Table responsive>
<thead>
<tr>
<th><Trans>Lugar</Trans></th>
<th><Trans>Actualizado</Trans></th>
<th><Trans>Creado</Trans>
</th>
<th />
<th />
</tr>
</thead>
<tbody>
{subscriptions.map(({
_id,
location,
createdAt,
updatedAt
}) => (
<tr key={_id}>
<td>{location.lat},{location.lon}</td>
<td>{timeago(updatedAt)}</td>
<td>{timeago(createdAt)}</td>
<td>
<Button
bsStyle="primary"
onClick={() => history.push(`${match.url}/${_id}`)}
block
>View
</Button>
</td>
<td>
<Button
bsStyle="danger"
onClick={() => this.handleRemove(_id)}
block
>Delete
</Button>
</td>
</tr>
))}
</tbody>
</Table> :
<Alert bsStyle="warning"><Trans>No estás suscrito a fuegos en ninguna zona</Trans></Alert>
}
</div>
) : <Loading />);
}
}
Subscriptions.propTypes = {
loading: PropTypes.bool.isRequired,
subscriptions: PropTypes.arrayOf(PropTypes.object).isRequired,
match: PropTypes.object.isRequired,
t: PropTypes.func.isRequired,
history: PropTypes.object.isRequired
};
export default translate([], { wait: true })(withTracker(() => {
const subscription = Meteor.subscribe('mysubscriptions');
// console.log(UserSubsToFiresCollection.find().fetch());

22
package-lock.json generated
View file

@ -21,17 +21,17 @@
}
},
"@turf/helpers": {
"version": "5.1.0",
"resolved": "https://registry.npmjs.org/@turf/helpers/-/helpers-5.1.0.tgz",
"integrity": "sha1-4whphlTb93C0rxOV34TkPEkmFL0="
"version": "5.1.5",
"resolved": "https://registry.npmjs.org/@turf/helpers/-/helpers-5.1.5.tgz",
"integrity": "sha1-FTQFInq5M9AEpbuWQantmZ/L4M8="
},
"@turf/union": {
"version": "5.1.0",
"resolved": "https://registry.npmjs.org/@turf/union/-/union-5.1.0.tgz",
"integrity": "sha1-UAT1fxZasGIPvmRMpaoksBKCATg=",
"version": "5.1.5",
"resolved": "https://registry.npmjs.org/@turf/union/-/union-5.1.5.tgz",
"integrity": "sha1-UyhbYJQEf8WNlqrA6pCGXsNNRUs=",
"requires": {
"@turf/helpers": "5.1.0",
"turf-jsts": "1.2.0"
"@turf/helpers": "5.1.5",
"turf-jsts": "1.2.2"
}
},
"@types/node": {
@ -11337,9 +11337,9 @@
}
},
"turf-jsts": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/turf-jsts/-/turf-jsts-1.2.0.tgz",
"integrity": "sha1-EnxOQzKlns7pF/yjHUk5luglS+A="
"version": "1.2.2",
"resolved": "https://registry.npmjs.org/turf-jsts/-/turf-jsts-1.2.2.tgz",
"integrity": "sha1-uZkjZZpGc3uBQT7P+b1w42C6F1M="
},
"tweetnacl": {
"version": "https://registry.npmjs.org/tweetnacl/-/tweetnacl-0.14.5.tgz",

View file

@ -8,7 +8,7 @@
"dependencies": {
"@cleverbeagle/dates": "^0.5.1",
"@cleverbeagle/seeder": "^1.3.1",
"@turf/union": "^5.1.0",
"@turf/union": "^5.1.5",
"babel-runtime": "^6.26.0",
"bcrypt": "^1.0.3",
"commonmark": "^0.28.1",