Adde noise and scale

This commit is contained in:
vjrj 2017-12-04 17:44:08 +01:00
parent aced217a7d
commit 5bc9b0b040
12 changed files with 215 additions and 52 deletions

View file

@ -1,15 +1,33 @@
import React, {Component} from 'react';
import { Row, Button, Checkbox } from 'react-bootstrap';
import { Row, Col, Button, Checkbox } from 'react-bootstrap';
import PropTypes from 'prop-types';
import { Meteor } from 'meteor/meteor';
import { Trans, Interpolate, translate } from 'react-i18next';
import 'leaflet/dist/leaflet.css';
import { Circle, CircleMarker, Map, Marker, Popup, TileLayer, PropTypes as MapPropTypes } from 'react-leaflet'
import ActiveFiresCollection from '../../../api/ActiveFires/ActiveFires';
import FireAlertsCollection from '../../../api/FireAlerts/FireAlerts';
import UserSubsToFiresCollection from '../../../api/Subscriptions/Subscriptions';
import { withTracker } from 'meteor/react-meteor-data';
import Loading from '../../components/Loading/Loading';
import './FiresMap.scss';
import Leaflet from 'leaflet'
import LGeo from 'leaflet-geodesy';
import union from 'turf-union';
import 'leaflet-graphicscale/dist/Leaflet.GraphicScale.min.css';
import 'leaflet-graphicscale/dist/Leaflet.GraphicScale.min.js';
// https://stackoverflow.com/questions/35394577/leaflet-js-union-merge-circles
function unify(polyList) {
for (var i = 0; i < polyList.length; ++i) {
if (i == 0) {
var unionTemp = polyList[i].toGeoJSON();
} else {
unionTemp =union(unionTemp, polyList[i].toGeoJSON());
}
}
return L.geoJson(unionTemp);
}
const fireIcon = new Leaflet.Icon({
iconUrl: "/fire-marker.png",
@ -21,42 +39,56 @@ const fireIcon = new Leaflet.Icon({
* popupAnchor: [-3, -76]// point from which the popup should open relative to the iconAnchor*/
})
const nFireIcon = new Leaflet.Icon({
iconUrl: "/n-fire-marker.png",
/* shadowUrl: require('../public/marker-shadow.png'), */
iconSize: [16, 24], // size of the icon
/* shadowSize: [50, 64], // size of the shadow */
iconAnchor: [8, 26], // point of the icon which will correspond to marker's location
/* shadowAnchor: [4, 62], // the same for the shadow
* popupAnchor: [-3, -76]// point from which the popup should open relative to the iconAnchor*/
})
// http://leafletjs.com/reference-1.2.0.html#icon
const MyPopupMarker = ({ children, lat, lon}) => (
<div><Marker position={[lat, lon]} icon={fireIcon} >
const MyPopupMarker = ({ children, lat, lon, nasa}) => (
<div><Marker position={[lat, lon]} icon={nasa? fireIcon: nFireIcon} >
{/* <Popup>
<span>{children}</span>
</Popup> */}
</Marker>
<CircleMarker center={[lat, lon]} color="red" stroke={false} fillOpacity="1" fill={true} radius={1} />
<CircleMarker center={[lat, lon]} color={nasa? "red": "#D35400"} stroke={false} fillOpacity="1" fill={true} radius={1} />
</div>
)
const FireMark = ({ lat, lon, scan }) => (
const FireMark = ({ lat, lon, scan, nasa }) => (
<Circle center={[lat, lon]} color="red" stroke={false} fillOpacity="1" fill={true} radius={scan*1000} />
)
/* Less acurate (1 pixel per fire) but faster */
const Fire = ({ lat, lon, scan }) => (
<CircleMarker center={[lat, lon]} color="red" stroke={false} fillOpacity="1" fill={true} radius={1} />
const FirePixel = ({ lat, lon, nasa }) => (
<CircleMarker center={[lat, lon]} color={nasa? "red": "#D35400"}
stroke={false} fillOpacity="1" fill={true} radius={2} />
)
MyPopupMarker.propTypes = {
// https://github.com/PaulLeCam/react-leaflet/tree/master/src/propTypes
children: MapPropTypes.children,
lat: PropTypes.number.isRequired,
lon: PropTypes.number.isRequired,
nasa: PropTypes.bool.isRequired,
}
Fire.propTypes = {
scan: PropTypes.number.isRequired,
FirePixel.propTypes = {
lat: PropTypes.number.isRequired,
lon: PropTypes.number.isRequired,
nasa: PropTypes.bool.isRequired,
}
FireMark.propTypes = {
scan: PropTypes.number.isRequired,
lat: PropTypes.number.isRequired,
lon: PropTypes.number.isRequired,
nasa: PropTypes.bool.isRequired,
}
const MyMarkersList = ({ markers }) => {
@ -66,10 +98,16 @@ const MyMarkersList = ({ markers }) => {
return <div style={{ display: 'none' }}>{items}</div>
}
const FireList = ({ activefires, scale, useMarkers }) => {
const items = activefires.map(({ _id, ...props }) => (
useMarkers? <MyPopupMarker key={_id} {...props} />:
scale? <Fire key={_id} {...props} />:<FireMark key={_id} {...props} />))
const FireList = ({ fires, scale, useMarkers, nasa }) => {
/* if (nasa) {
* console.log(`Scale: ${scale}`);
* for (var i = 0; i < fires.length; i ++) {
* console.log(fires[i].scan);
* }
* }*/
const items = fires.map(({ _id, ...props }) => (
useMarkers? <MyPopupMarker key={_id} nasa={nasa} {...props} />:
(!nasa && !scale)? <FirePixel key={_id} nasa={nasa} {...props} />:<FireMark key={_id} nasa={nasa} {...props} />))
return <div style={{ display: 'none' }}>{items}</div>
}
@ -91,8 +129,10 @@ class FiresMap extends React.Component {
this.state = {
viewport: DEFAULT_VIEWPORT,
modified: false,
useMarkers: false
useMarkers: false,
showSubsUnion: true
}
this.unionGroup = new L.LayerGroup();
}
centerOnUserLocation = () => {
@ -122,6 +162,7 @@ class FiresMap extends React.Component {
componentDidMount() {
height.set(this.divElement.clientHeight);
width.set(this.divElement.clientWidth);
this.addScale();
}
onViewportChanged = viewport => {
@ -130,7 +171,8 @@ class FiresMap extends React.Component {
lat.set(viewport.center[0]);
lng.set(viewport.center[1]);
this.state.viewport = viewport;
this.state.modified = true
this.state.modified = true;
this.showSubsUnion(this.state.showSubsUnion);
}
onClickReset = () => {
@ -143,9 +185,57 @@ class FiresMap extends React.Component {
this.forceUpdate();
}
getMap = () => {
return this.refs['fireMap'].leafletElement;
}
showSubsUnion = (show) => {
this.state.showSubsUnion = show;
const map = this.getMap();
// http://leafletjs.com/reference-1.2.0.html#layergroup
var unionGroup = this.unionGroup;
if (this.union) {
map.removeLayer(this.union);
}
if (show) {
// http://leafletjs.com/reference-1.2.0.html#path
var copts = {
parts: 144,
};
UserSubsToFiresCollection.find().forEach( function(subs){
var 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: .1,
});
this.union.addTo(map);
}
}
addScale = () => {
// https://www.npmjs.com/package/leaflet-graphicscale
const map = this.getMap();
var options = {
fill: 'fill',
showSubunits: true,
}
var graphicScale = L.control.graphicScale([options]).addTo(map);
}
render() {
this.state.viewport = !this.state.modified && this.props.viewport && Array.isArray(this.props.viewport.center)? this.props.viewport: this.state.viewport;
if (this.props.subsready && this.refs['fireMap']) {
// Show union of users
this.showSubsUnion(this.state.showSubsUnion);
};
return (
/* Large number of markers:
https://stackoverflow.com/questions/43015854/large-dataset-of-markers-or-dots-in-leaflet/43019740#43019740 */
@ -159,43 +249,55 @@ class FiresMap extends React.Component {
:""}
<h4 className="page-header"><Trans parent="span">Fuegos activos</Trans></h4>
<Row>
{this.props.activefires.length === 0?
<Trans parent="p" i18nKey="noActiveFireInMapCount">No hay fuegos activos en esta zona del mapa. Hay un total de <strong>{{countTotal: this.props.activefirestotal}}</strong> fuegos activos detectados en todo el mundo.</Trans>:
<Trans parent="p" i18nKey="activeFireInMapCount">En rojo, <strong>{{count: this.props.activefires.length}}</strong> fuegos activos en el mapa. Hay un total de <strong>{{countTotal: this.props.activefirestotal}}</strong> fuegos activos detectados en todo el mundo.</Trans>
}
<Checkbox onClick={e => this.useMarkers(e.target.checked)}>
<Trans parent="span">Resaltar los fuegos con un marcador</Trans></Checkbox>
<Col xs={12} sm={6} md={6} lg={6} >
<p>
{this.props.activefires.length === 0?
<Trans parent="span" i18nKey="noActiveFireInMapCount">No hay fuegos activos en esta zona del mapa. Hay un total de <strong>{{countTotal: this.props.activefirestotal}}</strong> fuegos activos detectados en todo el mundo.</Trans>:<Trans parent="span" i18nKey="activeFireInMapCount">En rojo, <strong>{{count: this.props.activefires.length}}</strong> fuegos activos en el mapa. Hay un total de <strong>{{countTotal: this.props.activefirestotal}}</strong> fuegos activos detectados en todo el mundo por la NASA.</Trans>
}
</p>
<p><Trans parent="span" i18nKey="activeNeigFireInMapCount">En naranja, los fuegos notificados por nuestros usuarios/as recientemente.</Trans></p>
</Col>
<Col xs={12} sm={6} md={6} lg={6} >
<Checkbox inline={false} defaultChecked={this.state.showSubsUnion} onClick={e => this.showSubsUnion(e.target.checked)}>
<Trans className="mark-checkbox" parent="span">Resaltar en verde el área vigilada por nuestros usuarios/as</Trans>&nbsp;(*)
</Checkbox>
<Checkbox inline={false} onClick={e => this.useMarkers(e.target.checked)}>
<Trans className="mark-checkbox" parent="span">Resaltar los fuegos con un marcador</Trans>
</Checkbox>
<Button bsStyle="default" onClick={() => this.centerOnUserLocation()}>
<i className="location"/>
<Trans className="location" parent="span">Centrar el mapa en tu ubicación</Trans>
</Button>
</Col>
</Row>
<Row>
<Map
animate={true}
preferCanvas={false}
onClick={this.onClickReset}
viewport={this.state.viewport}
onViewportChanged={this.onViewportChanged}
>
<Map ref="fireMap"
animate={true}
preferCanvas={true}
onClick={this.onClickReset}
viewport={this.state.viewport}
onViewportChanged={this.onViewportChanged}>
{/* http://wiki.openstreetmap.org/wiki/Tile_servers */}
<TileLayer
attribution="&copy; <a href=&quot;http://osm.org/copyright&quot;>OpenStreetMap</a> contributors"
url="http://{s}.tiles.wmflabs.org/bw-mapnik/{z}/{x}/{y}.png"
/>
<FireList
activefires={this.props.activefires}
scale={this.state.viewport.zoom > 8}
fires={this.props.activefires}
scale={this.state.viewport.zoom > 7}
useMarkers={this.state.useMarkers}
nasa={true}
/>
<FireList
fires={this.props.firealerts}
scale={false}
useMarkers={this.state.useMarkers}
nasa={false}
/>
</Map>
</Row>
<Row>
<p>
<em><Trans parent="span">Fuente NASA y alertas vecinales de nuestr@s usuari@s.</Trans></em>
</p>
</Row>
<Row>
<Button bsStyle="default" onClick={() => this.centerOnUserLocation()}>
<i className="location"/>
<Trans className="location" parent="span">Centrar el mapa en tu ubicación</Trans>
</Button>
(*)&nbsp;<Trans parent="span"><em>Para preservar la privacidad de nuestros usuarios/as, los datos reflejados están aleatoriamente alterados y son solo orientativos.</em></Trans>
</Row>
</div>
);
@ -210,6 +312,7 @@ const width = new ReactiveVar(400);
FiresMap.propTypes = {
loading: PropTypes.bool.isRequired,
subsready: PropTypes.bool.isRequired,
activefires: PropTypes.arrayOf(PropTypes.object).isRequired,
activefirestotal: PropTypes.number.isRequired,
viewport: PropTypes.object.isRequired
@ -236,13 +339,21 @@ export default translate([], { wait: true }) (withTracker(() => {
});
Meteor.subscribe('activefirestotal');
// Right now to all neighborhood alerts
Meteor.subscribe('fireAlerts');
var userSubs = Meteor.subscribe('userSubsToFires');
// const subscription = Meteor.subscribe('activefiresmyloc', zoom.get());
console.log(`Active fires ${ActiveFiresCollection.find().fetch().length} of ${Counter.get('countActiveFires')}`);
// console.log(`Active fires ${ActiveFiresCollection.find().fetch().length} 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());
return {
loading: !subscription.ready(),
subsready: userSubs.ready(),
activefires: ActiveFiresCollection.find().fetch(),
activefirestotal: Counter.get('countActiveFires'),
firealerts: FireAlertsCollection.find().fetch().map(
doc => ( { _id: doc['_id'], lat: doc['location'].lat, lon: doc['location'].lon })),
userSubs: UserSubsToFiresCollection.find().fetch(),
viewport: {
center: [lat.get(), lng.get()], // a point in the sea
zoom: zoom.get(),

View file

@ -2,7 +2,7 @@
.leaflet-container {
height: 100%;
min-height: 75vh;
min-height: 70vh;
width: 100%;
min-width: 75vw;
display: flex;
@ -38,3 +38,7 @@ i.location {
width: 35px;
vertical-align: middle;
}
.mark-checkbox {
margin-left: 5px;
}