Improved firesmap

This commit is contained in:
vjrj 2017-12-15 17:43:45 +01:00
parent 4c5aef6e4f
commit 56a7468ae3
7 changed files with 214 additions and 132 deletions

View file

@ -1,15 +1,17 @@
/* global Counter */
/* eslint-disable import/no-absolute-path */
/* eslint-disable prefer-arrow-callback */
import { Meteor } from 'meteor/meteor';
import { check, Match } from 'meteor/check';
import IPGeocoder from '/imports/startup/server/IPGeocoder';
import { localize } from '/imports/startup/server/IPGeocoder';
import ActiveFires from '../ActiveFires';
const counter = new Counter('countActiveFires', ActiveFires.find({}));
Meteor.publish('activefirestotal', () => counter);
Meteor.publish('activefirestotal', function total() {
return counter;
});
const validZoom = Match.Where((zoom) => {
// http://wiki.openstreetmap.org/wiki/Zoom_levels
@ -54,9 +56,9 @@ const activefires = (zoom, lat, lng, height, width) => {
const distUnt = resolution * Math.max(height, width);
const distance = Math.trunc(distUnt);
// console.log(`so ${height}x${width} gives ${Math.trunc(resolution*height/1000)} x ${Math.trunc(resolution*width/1000)} km, so looking in ${distance}`);
console.log(`so ${height}x${width} gives ${resolution} of resolution, so looking in ${distance}`);
console.log(`So ${height}x${width} gives ${Math.trunc(resolution)} of resolution, so looking in ${Math.trunc(distance / 1000)}km`);
return ActiveFires.find({
const fires = ActiveFires.find({
ourid: {
$near: {
$geometry: {
@ -74,9 +76,42 @@ const activefires = (zoom, lat, lng, height, width) => {
scan: 1
}
});
console.log(`Fires total: ${fires.count()}`);
return fires;
};
Meteor.publish('activefiresmyloc', (zoom, lat, lng, height, width) => {
Meteor.publish('allActiveFires', function allActive() {
// latitude -90 and 90 and the longitude between -180 and 180
const { latitude, longitude } = localize().location;
console.log(`${latitude}, ${longitude}`);
check(latitude, NumberBetween(-90, 90));
check(longitude, NumberBetween(-180, 180));
// https://docs.meteor.com/api/collections.html#Mongo-Collection-find
return ActiveFires.find({
ourid: {
$near: {
$geometry: {
type: 'Point',
coordinates: [longitude, latitude]
},
$minDistance: 0,
$maxDistance: 1000 // 156412000
}
}
}, {
fields: {
_id: 0,
lat: 1,
lon: 1,
scan: 1
},
maxTimeMs: 30000
});
});
Meteor.publish('activefiresmyloc', function activeInMyLoc(zoom, lat, lng, height, width) {
check(zoom, validZoom);
check(lat, NullOr(Number));
check(lng, NullOr(Number));
@ -84,19 +119,8 @@ Meteor.publish('activefiresmyloc', (zoom, lat, lng, height, width) => {
check(width, NullOr(Number));
console.log(`Check active fires in ${lat},${lng} with zoom ${zoom} pixels in ${height}x${width} map`);
if (lat === null || lng === null) {
let clientIP;
if (this.connection && this.connection.clientAddress) {
clientIP = this.connection.clientAddress;
} else {
console.warn('We cannot get this meteor connection IP');
clientIP = '127.0.0.1';
}
if (clientIP === '127.0.0.1') {
clientIP = '80.58.61.250'; // Some Spain IP address
}
// https://www.npmjs.com/package/maxmind
const location = IPGeocoder.get(clientIP);
console.log(location);
const location = localize();
console.log(`${location.latitude}, ${location.longitude}`);
return activefires(zoom, location.latitude, location.longitude, height, width);
}
return activefires(zoom, lat, lng, height, width);

View file

@ -1,6 +1,13 @@
/* eslint-disable prefer-arrow-callback */
import { Meteor } from 'meteor/meteor';
import maxmind from 'maxmind';
process.env.HTTP_FORWARDED_COUNT = Meteor.settings.private.proxies_count;
if (!Meteor.isDevelopment) {
console.log(`Number or proxies (needed for client IP lookup): ${process.env.HTTP_FORWARDED_COUNT}`);
}
// https://stackoverflow.com/questions/13969655/how-do-you-check-whether-the-given-ip-is-internal-or-not
function isPrivateIP(ip) {
const parts = ip.split('.');
@ -13,22 +20,30 @@ function isPrivateIP(ip) {
const IPGeocoder = maxmind.openSync(`${process.env.PWD}/private/GeoLite2-City.mmdb`);
export default IPGeocoder;
// Warning: Meteor cannot access to this.connection with arrow functions
export function localize() {
// https://stackoverflow.com/questions/14843232/how-to-get-the-user-ip-address-in-meteor-server/22657421#22657421
let clientIP;
if (this.connection && this.connection.clientAddress) {
clientIP = this.connection.clientAddress;
} else {
console.warn(`We cannot get this meteor connection IP for this connection (${this.connection})`);
clientIP = '127.0.0.1';
}
if (isPrivateIP(clientIP)) {
clientIP = '80.58.61.250'; // Some Spain IP address
}
// console.log(`Geolocating ${clientIP}`);
// TODO: cron download GeoLite-City
// http://dev.maxmind.com/geoip/geoip2/geolite2/
const location = IPGeocoder.get(clientIP);
// console.log(location);
return location;
}
Meteor.methods({
geo() {
// https://stackoverflow.com/questions/14843232/how-to-get-the-user-ip-address-in-meteor-server/22657421#22657421
let clientIP = this.connection.clientAddress;
if (isPrivateIP(clientIP)) {
clientIP = '80.58.61.250'; // Some Spain IP address
}
// console.log(`Geolocating ${clientIP}`);
// TODO: cron download GeoLite-City
// http://dev.maxmind.com/geoip/geoip2/geolite2/
const location = IPGeocoder.get(clientIP);
// console.log(location);
return location;
},
geo: localize,
getMapKey() {
// http://meteorpedia.com/read/Environment_Variables
// https://developers.google.com/maps/documentation/javascript/get-api-key

View file

@ -11,15 +11,17 @@ export default function FireList(props) {
const {
fires, scale, useMarkers, nasa
} = props;
const items = fires.map(({ _id, ...otherProps }) => {
if (useMarkers && scale) {
return (<FireIconMark key={_id} nasa={nasa} {...otherProps} />);
}
if (!nasa && !scale) {
return (<FirePixel key={_id} nasa={nasa} {...otherProps} />);
}
return (<FireCircleMark key={_id} nasa={nasa} {...otherProps} />);
});
const useMarks = useMarkers && scale;
const usePixel = !nasa || !scale;
/* console.log(`Using marks: ${useMarks}, using pixels: ${usePixel}`); */
let items;
if (useMarks) {
items = fires.map(({ _id, ...otherProps }) => (<FireIconMark key={_id} nasa={nasa} {...otherProps} />));
} else if (usePixel) {
items = fires.map(({ _id, ...otherProps }) => (<FirePixel key={_id} nasa={nasa} {...otherProps} />));
} else {
items = fires.map(({ _id, ...otherProps }) => (<FireCircleMark key={_id} nasa={nasa} {...otherProps} />));
}
return (<div style={{ display: 'none' }}>{items}</div>);
}

View file

@ -1,10 +1,19 @@
/* eslint-disable react/jsx-indent-props */
import React from 'react';
import { CircleMarker } from 'react-leaflet';
import PropTypes from 'prop-types';
/* Less acurate (1 pixel per fire) but faster */
const FirePixel = ({ lat, lon, nasa }) => (
<CircleMarker center={[lat, lon]} color={nasa ? 'red' : '#D35400'} stroke={false} fillOpacity="1" fill radius={2} />
<CircleMarker
center={[lat, lon]}
color={nasa ? 'red' : '#D35400'}
stroke={false}
fillOpacity="1"
fill
radius={nasa ? 1 : 2}
/>
);

View file

@ -13,38 +13,38 @@ import './Navigation.scss';
const Navigation = props => (
<nav className="navbar fixed-top navbar-expand-lg navbar-dark bg-dark">
<div className="container">
{/* <Navbar bsClass="navbar navbar-dark bg-dark"> */}
{/* https://github.com/react-bootstrap/react-bootstrap/blob/master/src/Navbar.js */}
<Navbar.Header>
<Navbar.Brand>
<Link to="/">{props.t('AppNameFull')}</Link>
</Navbar.Brand>
{/* <Navbar.Toggle/> */}
<button className="sr-only navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span className="navbar-toggler-icon"></span>
{/* <Navbar bsClass="navbar navbar-dark bg-dark"> */}
{/* https://github.com/react-bootstrap/react-bootstrap/blob/master/src/Navbar.js */}
<Navbar.Header>
<Navbar.Brand>
<Link to="/">{props.t('AppNameFull')}</Link>
</Navbar.Brand>
{/* <Navbar.Toggle/> */}
<button className="sr-only navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span className="navbar-toggler-icon" />
</button>
</Navbar.Header>
<button className="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle navigation">
<span className="navbar-toggler-icon" />
</button>
</Navbar.Header>
<button className="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle navigation">
<span className="navbar-toggler-icon"></span>
</button>
{/* <Navbar.Collapse> */}
<div className="collapse navbar-collapse" id="navbarNavDropdown">
<ul className="navbar-nav ml-auto ">
{/* <LinkContainer className="nav-item" anchorClassName="nav-link" to="/sandbox">
<NavItem eventKey={1.1} href="/sandbox">Sandbox</NavItem>
</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>}
</NavItem>
</LinkContainer>
<LinkContainer className="nav-item" anchorClassName="nav-link" to="/fires">
<NavItem eventKey={2} href="/fires">{props.t('activeFires')}</NavItem>
</LinkContainer>
</ul>
{!props.authenticated ? <PublicNavigation /> : <AuthenticatedNavigation {...props} />}
{/* </Navbar.Collapse> */}
</div>
{/* <Navbar.Collapse> */}
<div className="collapse navbar-collapse" id="navbarNavDropdown">
<ul className="navbar-nav ml-auto ">
{/* <LinkContainer className="nav-item" anchorClassName="nav-link" to="/sandbox">
<NavItem eventKey={1.1} href="/sandbox">Sandbox</NavItem>
</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>}
</NavItem>
</LinkContainer>
<LinkContainer className="nav-item" anchorClassName="nav-link" to="/fires">
<NavItem eventKey={2} href="/fires">{props.t('activeFires')}</NavItem>
</LinkContainer>
</ul>
{!props.authenticated ? <PublicNavigation /> : <AuthenticatedNavigation {...props} />}
{/* </Navbar.Collapse> */}
</div>
</div>
</nav>
);

View file

@ -31,13 +31,11 @@ import './FiresMap.scss';
const { BaseLayer } = LayersControl;
const MAXZOOM = 6;
const MAXZOOMREACTIVE = 6;
const zoom = new ReactiveVar(8);
const lat = new ReactiveVar();
const lng = new ReactiveVar();
const height = new ReactiveVar(400);
const width = new ReactiveVar(400);
const center = new ReactiveVar([null, null]);
const mapSize = new ReactiveVar([400, 400]);
// TODO share only the used part of fires data
// Remove map in subscription
class FiresMap extends React.Component {
constructor(props) {
@ -62,11 +60,26 @@ class FiresMap extends React.Component {
Gkeys.load((err, key) => {
self.setState({ gkey: key });
});
height.set(this.divElement.clientHeight);
width.set(this.divElement.clientWidth);
mapSize.set([this.divElement.clientHeight, this.divElement.clientWidth]);
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);
}
@ -81,7 +94,6 @@ class FiresMap extends React.Component {
}
setShowSubsUnion(show) {
this.setState({ showSubsUnion: show });
this.showSubsUnion(show);
}
@ -115,35 +127,38 @@ class FiresMap extends React.Component {
handleViewportChange(viewport) {
console.log(`Viewport changed: ${JSON.stringify(viewport)}`);
if (viewport.center === this.state.viewport.center &&
viewport.zoom === this.state.viewport.zoom) {
// Do nothing, in same point
return;
}
zoom.set(viewport.zoom);
lat.set(viewport.center[0]);
lng.set(viewport.center[1]);
center.set(viewport.center);
this.setState({ viewport });
/* this.state.viewport = viewport;
* this.state.modified = true; */
if (this.props.subsready && this.fireMap) {
this.showSubsUnion(this.state.showSubsUnion);
}
}
centerOnUserLocation(viewport) {
this.handleViewportChange(viewport);
this.setState({ viewport });
// this.handleViewportChange(viewport);
}
useMarkers(use) {
this.setState({ useMarkers: use });
// this.state.useMarkers = use;
// this.forceUpdate();
}
addScale() {
// https://www.npmjs.com/package/leaflet-graphicscale
const map = this.getMap();
const options = {
fill: 'fill',
showSubunits: true
};
L.control.graphicScale([options]).addTo(map);
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);
}
}
render() {
@ -151,7 +166,7 @@ class FiresMap extends React.Component {
// Show union of users
this.showSubsUnion(this.state.showSubsUnion);
}
console.log('Rendering map');
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 = (
<BaseLayer checked name={t('Mapa gris de OpenStreetMap')}>
@ -175,10 +190,10 @@ class FiresMap extends React.Component {
<Row>
<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>
}
{ 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>
@ -188,17 +203,25 @@ class FiresMap extends React.Component {
</Checkbox>
{(this.state.viewport.zoom >= MAXZOOM) &&
<Checkbox inline={false} onClick={e => this.useMarkers(e.target.checked)}>
<Trans className="mark-checkbox" parent="span">Resaltar los fuegos con un marcador</Trans>
<Trans className="mark-checkbox" parent="span">Resaltar los fuegos con un marcador</Trans>
</Checkbox>}
<CenterInMyPosition onClick={viewport => this.centerOnUserLocation(viewport)} />
<p>
<em>{ this.state.viewport.zoom >= MAXZOOMREACTIVE ?
<Trans>Los fuegos activos se actualizan en tiempo real.</Trans> :
<Trans>Haga zoom en una zona de su interés si quiere que los fuegos se actualicen en tiempo real.</Trans>
}
</em>
</p>
</Col>
</Row>
<Row>
{/* https://github.com/CliffCloud/Leaflet.Sleep */}
<Map
ref={(map) => { this.fireMap = map; }}
animate
// minZoom={4}
minZoom={5}
preferCanvas
onClick={this.onClickReset}
viewport={this.state.viewport}
@ -212,32 +235,34 @@ class FiresMap extends React.Component {
sleepOpacity={0.6}
>
{/* http://wiki.openstreetmap.org/wiki/Tile_servers */}
{!this.props.loading &&
<FireList
fires={this.props.activefires}
scale={this.state.viewport.zoom >= MAXZOOM}
useMarkers={this.state.useMarkers}
nasa
/>
/>}
{!this.props.loading &&
<FireList
fires={this.props.firealerts}
scale={false}
useMarkers={this.state.useMarkers}
nasa={false}
/>
/>}
<LayersControl position="topright">
{osmlayer}
{ this.state.gkey &&
<BaseLayer name={t('Mapa de carreteras de Google')}>
<GoogleLayer googlekey={this.state.gkey} maptype="ROADMAP" />
</BaseLayer>}
<BaseLayer name={t('Mapa de carreteras de Google')}>
<GoogleLayer googlekey={this.state.gkey} maptype="ROADMAP" />
</BaseLayer>}
{ this.state.gkey &&
<BaseLayer name={t('Mapa de terreno de Google')}>
<GoogleLayer googlekey={this.state.gkey} maptype="TERRAIN" />
</BaseLayer>}
<BaseLayer name={t('Mapa de terreno de Google')}>
<GoogleLayer googlekey={this.state.gkey} maptype="TERRAIN" />
</BaseLayer>}
{ this.state.gkey &&
<BaseLayer name={t('Mapa de satélite de Google')}>
<GoogleLayer googlekey={this.state.gkey} maptype="SATELLITE" />
</BaseLayer>}
<BaseLayer name={t('Mapa de satélite de Google')}>
<GoogleLayer googlekey={this.state.gkey} maptype="SATELLITE" />
</BaseLayer>}
</LayersControl>
</Map>
</Row>
@ -261,13 +286,21 @@ FiresMap.propTypes = {
export default translate([], { wait: true })(withTracker(() => {
let subscription;
let init = true;
Meteor.autorun(() => {
if (geolocation.get()) {
lat.set(geolocation.get()[0]);
lng.set(geolocation.get()[1]);
if (geolocation.get() && init) {
center.set(geolocation.get());
init = false;
}
if (zoom.get() || lat.get() || lng.get()) {
subscription = Meteor.subscribe('activefiresmyloc', zoom.get(), lat.get(), lng.get(), height.get(), width.get());
if (mapSize.get()) {
subscription = Meteor.subscribe(
'activefiresmyloc',
zoom.get(),
center.get()[0],
center.get()[1],
mapSize.get()[0],
mapSize.get()[1]
);
}
});
@ -276,18 +309,21 @@ export default translate([], { wait: true })(withTracker(() => {
Meteor.subscribe('fireAlerts');
const userSubs = Meteor.subscribe('userSubsToFires');
// const subscription = Meteor.subscribe('activefiresmyloc', zoom.get());
console.log(`Active fires ${ActiveFiresCollection.find().fetch().length} of ${Counter.get('countActiveFires')}`);
// 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());
return {
loading: !subscription.ready(),
userSubs: UserSubsToFiresCollection.find().fetch(),
subsready: userSubs.ready(),
activefires: ActiveFiresCollection.find().fetch(),
// Not reactive query depending on zoom level
activefires: ActiveFiresCollection.find({}, { reactive: zoom.get() >= MAXZOOMREACTIVE }).fetch(),
// 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: geolocation.get(),
zoom: zoom.get()

View file

@ -1,22 +1,18 @@
/* eslint-disable import/no-absolute-path */
import React from 'react';
// import PropTypes from 'prop-types';
import { translate } from 'react-i18next';
class Sandbox extends React.Component {
constructor(props) {
super(props);
/* this.state = {
* init: false
* }; */
}
componentDidMount() {
// this.setState({init: true});
}
render() {
return (
<div></div>
<div>
<div />
</div>
);
}
}
@ -25,4 +21,4 @@ Sandbox.propTypes = {
// history: PropTypes.object.isRequired
};
export default translate([], { wait: true }) (Sandbox);
export default translate([], { wait: true })(Sandbox);