Pages

header

Sensors data online streaming via Arduino + Python

Sometimes we need to stream our yielded data into Internet, and display them, for instance, as a chart.

arduino strema live data online


So, let`s go.

For instance we need to stream data from multiple sensors or devices directly to server and display them with minimal delay.

This solution could be used for smart-house systems, air quality devices, and other, and other.

We used this solution for streaming data from graphene sensors during hackathon.

Described system includes:

  • Arduino board which send data via serial port, 
  • Python script, which catch data from serial and send it to web API,
  • PHP API which receive data via POST and hold last record into mysql database;
  • JS+html frontend, which get and display latest updated data from database via PHP API.

Arduino sketch

As can you see, the sketch is extremely simple. It just get data from analogue pins and send it to serial as delimited string.
 
----------------------

int sensor1 = 0;
int sensor2 = 1;
int sensor3 = 2;
int sensor4 = 3;

int val1,val2,val3,val4 = 0;
void setup()
{
  Serial.begin(9600); 
}
void loop()
{
  val1 = analogRead(sensor1);
  val2 = analogRead(sensor2);
  val3 = analogRead(sensor3);
  val4 = analogRead(sensor4);

  Serial.print(val1);
  Serial.print(";");
  Serial.print(val2);
  Serial.print(";");
  Serial.print(val3);
  Serial.print(";");
  Serial.print(val4);
  Serial.print("\n"); 
  delay(1000);
}

----------------------

Python script for data transmitting

After we have sent data via serial, we need to transmit them to the server
----------------------

import urllib
import urllib2
import serial
import time
ser = serial.Serial('/dev/ttyUSB3', 9600, timeout=5)
time.sleep(5) # wait for Arduino
while True:
    bytesToRead = ser.inWaiting()
    linen = ser.readline()
    value = linen.split(";")
    print int(value[0])
    print int(value[1])
    print int(value[2])
    print int(value[3])
    url = 'http://path_to_your_website.com/signal.php'
    values = {'sensor1' : int(value[0]),'sensor2' : int(value[1]),'sensor3' : int(value[2]),'sensor4' : int(value[3]),}
    
    data = urllib.urlencode(values)
    req = urllib2.Request(url, data)
    response = urllib2.urlopen(req)
    print response.read(),"+"

----------------------

PHP API

API includes 2 parts and 1 config file. db_conf.php - here we hold database connection settings
----------------------

//Database Information
$db_host = "localhost"; //Host address (most likely localhost)
$db_name = "spatial"; //Name of Database
$db_user = "root"; //Name of database user
$db_pass = ""; //Password for database user

mysql_connect($db_host, $db_user, $db_pass);//database connection
mysql_set_charset( 'utf8' );
mysql_select_db($db_name) or die(mysql_error());

----------------------
signal.php - this file we use to get POST data and update database with fresh values
----------------------

require_once('db_conf.php');

$lastval1 = mysql_real_escape_string($_POST['sensor1']);
$lastval2 = mysql_real_escape_string($_POST['sensor2']);
$lastval3 = mysql_real_escape_string($_POST['sensor3']);
$lastval4 = mysql_real_escape_string($_POST['sensor4']);

$sql = 'UPDATE sensor_last
        SET value1="'.$lastval1.'",value2="'.$lastval2.'",value3="'.$lastval3.'",value4="'.$lastval4.'"
        WHERE id=1';
$retval = mysql_query($sql);
if(! $retval ){
  die('Could not update data: ' . mysql_error());
}

----------------------
reader.php - this file we use to get latest data from database as response to ajax request.
----------------------

require_once('db_conf.php');

$sql = "SELECT * FROM `sensor_last` where `id`= 1";
$result = mysql_query($sql);
if(mysql_num_rows($result)>0){
  while ($par1 = mysql_fetch_array($result)){
    echo json_encode(['value1' => $par1['value1'],
                      'value2' => $par1['value2'],
                      'value3' => $par1['value3'],
                      'value4' => $par1['value4']
                     ]);
  }
}

----------------------
This is just mysql for database table creation. As log as we use 4 sensors, we need 4 table cells.
----------------------

CREATE TABLE IF NOT EXISTS `sensor_last4` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `value1` int(11) NOT NULL,
  `value2` int(11) NOT NULL,
  `value3` int(11) NOT NULL,
  `value4` int(11) NOT NULL
); 
ALTER TABLE `sensor_last4`
  ADD PRIMARY KEY (`id`);
----------------------


JavaScript frontend


The really interesting thing is javascript frontend.  To visualize data I have used the Chart.Js open-source charting library. Data from API obtained via simple jquery ajax. Some Javascript components, which used in this streaming system, was stolen from this link: http://stackoverflow.com/questions/333664/how-do-i-implement-basic-long-polling In this case is used chart.js 2.0 version, so detailed information you could get from this link: http://nnnick.github.io/Chart.js/docs-v2/ 


----------------------

   var ctx;
   var myLineChart;
   var colors = ['#ff4b00', '#bac900', '#EC1813', '#55BCBE', '#D2204C', '#FF0000', '#ada59a', '#3e647e']; // the list of colors, it is used to create charts with different colors

   ctx = document.getElementById("areachart").getContext("2d"); 
   var chartData = {
       labels: timelabel(),
       datasets: []
   };
   var chartOpt = { // chart options
      scaleShowGridLines : true,
      scaleGridLineColor : "rgba(0,0,0,.05)",
      scaleGridLineWidth : 1,
      scaleShowHorizontalLines: true,
      scaleShowVerticalLines: true,
      bezierCurve : true,
      bezierCurveTension : 0.4,
      pointDot : true,
      pointDotRadius : 5,
      pointDotStrokeWidth : 1,
      pointHitDetectionRadius : 20,
      datasetStroke : true,
      datasetStrokeWidth : 2,
      datasetFill : false,
      legendTemplate : "<ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i=0; i
  • <span style=\"background-color:<%=datasets[i].strokeColor%>\"></span><%if(datasets[i].label){%><%=datasets[i].label%><%}%>
  • <%}%></ul>" } myLineChart = new Chart(ctx, { //
    chart object type: 'line', data: chartData, options: chartOpt }); myLineChart.options.animation=false; //turn-off weird animation to make possible dynamically stream data myLineChart.options.scales.yAxes[0].ticks.suggestedMin=50; //scale range defining myLineChart.options.scales.yAxes[0].ticks.suggestedMax=150; // function timelabel(){ // function to append timescale var times = []; var date = new Date; var seconds = date.getSeconds(); var minutes = date.getMinutes(); var hour = date.getHours(); for (var i = 0; i < 20; i++) { times.push(hour+" : "+minutes+" : "+seconds); } return times; }; function dataUpd (chart,dataset,newdata){ // function to update datasets chart.data.datasets[dataset].data.push(newdata); chart.data.datasets[dataset].data.shift(); } function timeUpd (chart){ // function to update timescale var date = new Date; var seconds = date.getSeconds(); var minutes = date.getMinutes(); var hour = date.getHours(); chart.data.labels.push(hour+" : "+minutes+" : "+seconds); chart.data.labels.shift(); } function insertNewDataset(chart,label,color){ // function to insert new data var dataset = { label: label, fill:false, borderColor: color, pointBorderColor: "rgba(220,220,220,1)", pointBackgroundColor: "#fff", pointBorderWidth: 1, pointHoverRadius: 5, pointHoverBackgroundColor: "rgba(220,220,220,1)", pointHoverBorderColor: "rgba(220,220,220,1)", pointHoverBorderWidth: 2, data: [null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null] }; chart.data.datasets.push(dataset); chart.update(); } for (var i = 0; i < 4; i++) { // for 4 sensors we need to insert 4 datasets insertNewDataset(myLineChart,"Sensor "+i, colors[i]); function waitForMsg(){ //check for new data in database and load it $.ajax({ type: "GET", url: "reader.php", async: true, /* If set to non-async, browser shows page as "Loading.."*/ cache: false, dataType: "json", timeout:10000, /* Timeout in ms */ success: function(data){ $(data).each(function(key, data) { //insert data into 4 datasets dataUpd(myLineChart,0,data.value1); dataUpd(myLineChart,1,data.value2); dataUpd(myLineChart,2,data.value3); dataUpd(myLineChart,3,data.value4); }); myLineChart.update(); timeUpd(myLineChart); setTimeout( waitForMsg, /* Request next message */ 200 /* ..after 200 milliseconds */ ); }, error: function(XMLHttpRequest, textStatus, errorThrown){ addmsg("error", textStatus + " (" + errorThrown + ")"); setTimeout( waitForMsg, /* Try again after.. */ 250); /* milliseconds */ } }); }; $(document).ready(function(){ waitForMsg(); /* Start the inital request */ }); ----------------------
    Total project you can download here
    Read more ...

    Exhaust gases multi-band air quality sensor on arduino - part 2

    It's almost year has left after I had done my air quality monitor on Arduino.
    During this year I have had a lot of accidents and adventures, but now I'm ready to return to blogging.

    After successful master's dissertation defense and further graduation I have collected a lot of materials and data to write a couple science papers, but... but I still have no time to do this (moreover, some aspects of Ukrainian science are frustrating me so much), so I would better post this collected information into this blog, without any research paper structure and formalities.

    I hope it would be useful to somebody.

    The previous part with description of  idea you could find by this link.




    Arduino air quality monitor for exhaust gasses measurement
    Arduino air quality monitor for exhaust gasses measurement

    Idea and issues


    Main requirement for mobile monitoring devices is mobility, of course.
    So, based on this idea, designed air quality monitor should have such features as:
    1. autonomy with a help of battery,
    2. autonomy in data output with a help of LCD.
    Both these issues could be solved with help of old stuff that everybody has in a home (or in a buddy's home).

    You can use any accumulators, the main problem is that single li-ion battery could give you only 3.7v, but for normal workflow you should have at least 5v.

    The quickest way to solve this issue is just to connect sequentially 2 batteries. A problem of charging you can solve with help of controller from old laptop battery or with any other diy circuits for li-ion charging.

    Siemens LPH8836 display + Arduino


    Many years ago I had, maybe, the most useful phone in my life - Siemens m65. Luckily, LCDs from Siemens phones  are very convenient to connect. Also it is possible to use displays from cx65, and s65.



    Inside the phone I have found the LPH8836-A display. In some other cases you could find LCD with another model. The difference between the ones is only in firmware features and circuit connection way, in fact, they are not significant.
    The lph88 known as the most problematic Siemens display, but only problem I have found is that it need to be connected via all contacts.


    siemens lph88 for arduino
    Siemens lph88, ready to use


    Layout of this display is very clear, the big area of contacts make able to solder wires easily.

    Air quality monitor circuit


    air quality monitor exhaust gases circuit arduino
    Total device circuit

    The total circuit of my device includes:

    • LCD LPH88
    • sensor MQ-138
    • sensor MQ-138;
    • sensor MQ-131;
    • sensor TGS-2201;
    • sensor AM-2301;
    • Arduino UNO r3 (DCCduino UNO);
    • resistor 470 Ω — 5 units;
    • resistor 820 Ω — 5 units;
    • resistor 120 Ω — 5 units;
    • diode 1N4148 — 1unit;
    • diode Schottky — 1 unit;
    • transistor — КТ972 — 1 unit;
    • induction 680 μH — 1 unit.

    Assembling



    arduino + siemens m65 display lph88
    first test

    Before using soldering iron I had tested circuit on a breadboard

    arduino uno + siemens m65 display lph88
    second test

    After test on the mobile phone, I have soldered wires to display and tested my assembling with simple Arduino program.

    arduino + siemens m65 display lph88 circuit board

    As long as in a result I have wanted to have the solid construction, I was obliged to create a circuit board. The quickest way to make it - just cut it out. Of course, the better way to produce circuit boards is chemistry, but if you do not need to have 0.5 mm ways on it, cutting is a possible variant.


    arduino + siemens m65 display lph88 circuit board

    After soldering of all components I had a solid module, matched witrh Arduino board.


    arduino + siemens m65 display lph88 circuit board

    After soldering of display wires I tested it - all works fine.

    arduino air quality monitor assembling

    As a battery I have used 2 li-ion cells with controller from laptop battery.

    arduino air quality monitor exhaust gases display

    Assembled device with flashed firmware.

    Field testing and the wind problem

    After assembling, I had tested this device indoor and everything works fine.
    But the first outdoor test with cold air shows that direct hitting of wind flows on sensor heads make these sensors feel bad.
    The solution of this problem was developed from 2 beer cans, with a help of which I had successfully formed a wind shield.

    arduino air quality monitor exhaust gases display
    wind defence shield

    When windflow hits the windshield it is influenced by Venturi effect. The speed of airflow inside the can would be slower than outside, and pressure - higher. Furthermore, holes split windflow to little flows inside a can.

    Another positive effect - this solution would work even in winter, as long as this windshield is a good insulator.


    arduino air quality monitor exhaust gases display


    arduino air quality monitor exhaust gases display


    arduino air quality monitor exhaust gases display

     

    Firmware

     

    My Arduino ExhaustGasMeter project *.ino

    You can use it in any way you want under MIT license.

    Additional libraries which are needed for display connection you would find here:
    https://github.com/watterott/Arduino-Libs

    (updated)

    IMPORTANT

    Before fleshing, you need to edit a bit the S65LPH88.cpp library code.

    For default pins this library uses

    RESET: 17 pin (A3 for arduino)
    SC: 16 pin (A2  for arduino).

    In my case, the analogue pins are engaged by sensors. Thet's why for my circuit you need to change RESET pin number from 17 to 9; SC pin number from 16 to 8.



    arduino air quality sensor exhaust gasas monitor
    hungry electronics


    Best regards, Andrii.
    Read more ...

    DIY table LED lamp

    let's make the eco-friendly DIY table LED lamp, or first step to the sustainable energy use.


    diy table led lamp

    Components:
    • wooden planks (thin and more wider)
    • abrasive glasspaper
    • bolts
    • foiled textolite
    • wire
    • powerful warm-white LEDs (I have used 5x1w)
    • wood stain
    • wood putty
    • supply from old cell phone (800-1000 mAh ~5 volts)
    • hands

    The LED table lamp wooden skeleton


    So, we will use wooden lath for skeleton
    At first we need make the "head" of the lamp in which the LEDs will be placed. For this we need to cut the piece of wider wooden plank

    wood for diy table led lamp

    Then we need make the layout by fitting our LEDs to the future lighter's head

    leds for diy table lamp

    Third step. We should use the milling tool with which we should to remove the wood inside the layout for LEDs placing.

    wooden diy table lamp

    wooden diy table lamp

    wooden diy table lamp

    Next step. Make a hole for fastening and a ditch for the led lamp's supply wire.

    wooden diy table lamp

    Then cut pieces of thin plank for other parts of led table lamp's skeleton.

    wooden diy table lamp

    Next step. Make holes in all other components and finish these by a glasspaper 

    wooden diy table lamp

    Let's try this set of wood to fitting each to one using the fastening

    diy table LED lamp

    Yes! It is okay. So, next step - color finishing.
    I want to make these planks look "old" so i need use black wood stain.

    wooden diy table lamp finishing

    wooden diy table lamp finishing


    Electric part of DIY LED table lamp

    Of course, for the led lamp we need make a led-module.
    Prepare the set of 4-5 1w leds and fit them on the "head" of your table lamp for finding the optimal distance.
    Cut the piece of foiled textolite and separate the copper foil for "+" and "-" part for make the circuit board.

    diy table led lamp circuit

    diy table led lamp circuit

    Solder the LEDs on your textolite with holding the distance between leds (papers between circuit board and leds is for isolation whereas leds have metal basement for heat transfer)

    diy table led lamp circuit

    Next - connect the wires and isolate the rest of circuit with leds by electrical tape.

    diy table led lamp circuit

    Another side of wire connect to the cellphone supply with proper mAh properties.

    LED table lamp compillation


    Let's fit our led-module to the lamp skeleton. Then fix the wire by putty and finish the putty with glasspaper and dark color.

    diy table led lamp head

    So, what we have totaly

    diy table led lamp parts

    Next step - lets compile our wooden DIY LED table lamp!

    diy table led lamp

    diy table led lamp

    Read more ...

    Exhaust gases multi-band air quality sensor on arduino - part 1

    For my graduation project I need to develop a model of exhaust gases distribution between city buildings.
    The model will made with help of PyQGIS and about this i will write later.
    For source data collecting i `m  going to use the self made multiband exhaust gas detector (air quality monitor) based on arduino-like board (dccduino - with love from China) and set of specialized gas sensors.

    What I'm going to use:

    exhaust gas sensor components, air quality monitor
    Components for future exhaust gas sensor 

    From left to right:

    1. MQ-138 with module. This sensor will be used for detecting of organic components of air. The description of this module says that it is sensitive to aldehydes, alcohols, ketones, and aromatic compounds :
      • 1 to 100ppm benzene
      • Toluene 10 to 100ppm
      • Methanol 5 to 100ppm
      • Alcohol 30 to 300ppm
      • Acetone 10 to 300ppm
      • Formaldehyde 1 to 10ppm 
    2. MQ-131with module. This sensor will used for ozone detection. In description is written that it is able to detect concentration range 10ppb-2ppm.
    3. NAP-505 (top, grey with white round) - electrolytic CO (Carbon Monoxide) gas sensor with high selectivity and sensitivity. The only sensor from set that not depends from humidity and need own circuit with expensive operative amplifiers.
    4. TGS-2201 (Figaro - 5N2201) (little black, bottom) - exhaust gases sensor. This sensor is interesting because this is dual sensor. Under one pack we have 2 sensors for diesel and petrol exhaust gases. About this one i had not found a lot of info, official website of FIGARO have not contains the datasheets, but i had found the one. As like as NAP-505 this sensor deeds own circuit but luckily this circuit needs only resistors. 
    5. DHT21 (AM2301) (right, top) - digital temperature and humidity sensor - 2 in one. This is  simple digital module that needs to make correlation between humidity-temperature and data from sensors. The practice shows that this sensor is very passive for data stabilization when it is needs to be used as a mobile monitoring device. I think that this passivity is effected by big plastic casing. In future I will check this.
    6. DCcduino UNO - full copy of Arduino Uno with price of 7$ (cost includes USB cable + pin dapters).

    MQ modules and DHT has been connected with arduino without any problems. In MQ I had used only analog outputs because now i need only make a test.

    NAP-505 i will connect later, where i will have operative amplifiers from it`s circuit.

    TGS-2201 connecting process

    The datasheet for this exhaust gas sensor i had found only on this page.
    You can download this datasheet.

    TGS-2201 circuit is not difficult


    As we can see in datasheet - the R1 and R2 range can be between 10k to 200k and depends on weather and measurement environment (i think).


    TGS-2201 (5N2201) exhaust gases detector, exhaust gases monitor datasheet

    The pins of sensor

    TGS-2201 (NA2201) exhaust gases detector, exhaust gases monitor circuit

    Resistor circuit

    I had used both resistors with resistance near 15k and that was a bad idea because one channel of this exhaust gas sensor (petrol channel) shows a much big values, so it needs to be calibrated. (see screenshot of serial monitor)

    The first compilation of air quality exhaust gases sensor 

    air quality exhaust gases sensor

    This is arduino with connected air quality sensors (except carbon monoxide and humidity\temperature).  100% chaos :)

    air quality exhaust gases sensor

    This is a beta for outdoor measurement.

    air quality exhaust gases sensor

    This is an attempt to make it not so ugly. Unsuccessful.
    In future i will make for this one the normal casing and LCD display from cellphone.

    ubuntu arduino serial minitor
    sudo screen /dev/ttyUSB0
    As you see on this screenshot - values are not adequate and need to be calibrated, about which i will write later. (overall is a pseudo-overall because it considers gases "importance rate")

    To be continued.. 



    Read more ...

    Biodiversity conservation framework problems - abstract

    The short review of three articles describes the main problems of biodiversity conserving. The “hotspot method” shows that this approach have more disadvantages than benefits. This method selects the limited spectrum of species only from terrestrial vertebrates and vascular plants of region that have endemic status and ignores all other species. The method from second article (the method of terrestrial ecozones) is much more objective, but not solves the question for aquatic ecosystems. Furthermore, in the map developed by authors ignored the existing of coastal ecosystems. The main problem of biodiversity conservation is determined a bit by Bjørn Lomborg. In his book “The Skeptical Environmentalist” He gives good point that we cannot properly know how many species really are.


    INTRODUCTION

    During the human progress, anthropogenic pressure to the Earth becomes higher and higher. This pressure causes much of phenomenons that force wildlife species extinction. In parallel with increasing of this pressure, during many years environmental scientists try to develop methods to save species and communities. However, number of scientist are very often equally to the number of methods that they are propose. Almost all of these are unique and good-looking, but sometimes noone can be used effectively because of broad spectrum of causes. In this review I will try to accent your attention on problems that I have found in three publications: “Biodiversity hotspots for conservation priorities”, “Terrestrial Ecoregions of the World”, “The Skeptical Environmentalist: Measuring the Real State of the World . Ch.23. Biodiversity”.

    BIODIVERSITY CONSERVATION FRAMEWORK PROBLEMS

    During the conservation studies were created two different paradigms of biodiversity measuring. The first of these two is based on counting of species number, second paradigm based on systematizing of biodiversity clusters. Both have own benefits and disadvantages. In the article named “Biodiversity hotspots for conservation priorities”, group of scientists show serious forces to develop conservation framework based on selecting regions with maximum concentration of unique endemic species. In second article, that named “Terrestrial Ecoregions of the World”, scientists try to develop conservation framework with ecoregions map. Third article, that factually is Bjørn Lomborg`s book chapter, is a critique of classic bioconservation scientists and showing the disadvantages of evaluation methods.
    At first article, scientists made huge accent on the number of endemic species and made the map of 25 biodiversity hotspots. Each hotspot must consist at least 0,5 % world`s species as endemics and should have lost 70 % or more of its primary vegetation. In sum that 25 hotspots consists near 35 % vertebrate and 44 % of vascular plants. At first sight everything in this method is logic: places with maximum amount of endemic species must be saved first (500 million $ annual dotation per one point, by the all), but this hotspot method has a lot of problems. First of them is that endemic species list is not identically for each other country, territory of which hotspot covered. Concentration of species can be other by location. Io one country this specific specie can be endemic, in other country it can be the simple specie that just usual specie. Overall, problem consist in the fact that not each species that even be on Earth have been discovered and described as endemics or not. That’s mean that this method representative only for properly discovered and described species.
    Next, and more serious problem is that this 35 % of vertebrates include only high animals lake a mammals, birds and amphibian animals. This method ignores not only microbiota but also insects and fishes. 44 % of vascular plants forced to ask a question “why only vascular plants?” Are unique species of lichen and moss can’t be endemic or mustn’t to be saved at all? Considering the air pollution tendencies, exactly lichen and moss suffering first.
    Second article shows a framework based on Earth zonation by biomes and biogeographic realms. This method gives widely sight on biodiversity conservation principles. The group of scientists made review of existing biogeographic maps with hi-resolution of ecoregions and proposed their own variant of such map: separate terrestrial world onto 8 biogeographic regions and 14 main biomes. Combination of this 8 and 14 gives 112 potential ecoregions with own complex of treats and unique variants of conservation. So broad zonation helps with classification that can show specific and unique zones that can be unique. The main disadvantage of ecoregion method is a difficulty with ocean zonation, as long as ecozones in oceans situated not in 2 dimensions but in 3. Furthermore, new and optimized map of scientists developed on other`s map base, but after optimization new map has lost the coastal ecological zones.
    In third article Bjørn Lomborg gives constructive critic to apocalyptic posts of classicists with predictions. Especially he appellate to Mayer’s declamation that every year extents near 40 000 species, which he does in 1979. Author also make trying to determinate the real amount the annual extinction and make a conclusion that real extinction now is near to 0,7 % per 50 years.

    CONCLUSION

    As we can see after analyzing of these 3 articles, the main problem of biodiversity conserving is that nobody know completely how many species and communities really are, and nobody know completely, which of them really extinct. That’s why so difficult to determine the priorities in case of biodiversity conserving. Moreover, such method as “hotspots” can`t make the real objective evaluation because it makes conclusion only by concentration of terrestrial vertebrates and vascular plants species that have a label “endemic”, without taking the attention to other species that can be unique. Both of described methods accents the attention on the unique concentration of biodiversity as like as on object to save, but noone solves the problem of single unique species that can extinct too.
    Maybe the better way to solve the biodiversity extinction problem is to use or develop the new approach that will based not only on the biodiversity conservation or biocenosis uniqueness but on zonation of anthropogenic pressure. This strategy is useful to save at first the live objects and ecosystems that in process of extinction.

    SOURCES


    1.       Norman Myers  et al. Biodiversity hotspots for conservation priorities .
    [  Nature 403, 853-858 (24 February 2000)].
    2.       David  M. Olson et al. Terrestrial Ecoregions of the World: A New Map of Life on Earth
    [ BioScience.  Vol. 51 No. 11,2001. P. 933-938]. 
    3.        Bjørn Lomborg.  The Skeptical Environmentalist: Measuring the Real State of the World . Ch.23. Biodiversity.
    [Cambridge University Press , 2001].



    P.S. sorry for my English :D

    Read more ...

    OpenLayers3 GeoJSON clustering - first steps troubleshooting guide, part 2

    OL2 had the specific layer strategy that makes clusters from points.
    But OpenLayers3 haven't yet.
    OpenLayers 3 has own method to do that, but you need use the feature array with points stack as source.

    Everything is okay if we use stack of coordinates or array of independent points.
    The panic starts when you should to make clusters from geojson points.
    But what you should do if you want to load geojson with points created in QGIS?

    openlayers 3 geojson clustering


    At first we need to transform geojson object to stack of point objects.
    How to do that without nervous i don't found, but we can to extract the lat\lng from geojson with
    jQuery.getJSON() or with AJAX json request.

    Example


    $.getJSON( "file.geojson", function( data ) {
      var features = [];
      $.each( data, function(key, value) {
        features.push(value);
    });

    /// - "file.geojson" - path to your geojson

    var fln = features[2].length;

    /// - features contents 3 elements: ["FeatureCollection", Object, Array[92]]
    We need to get length of array that includes features, so we need to use features[2].

    var points = [];
    for (var i = 0; i < fln; ++i) {
      points.push(new ol.Feature(new ol.geom.Point(features[2][i]['geometry']['coordinates'][0])));
    }
    console.log(points);

    /// - now we need to extract coordinates of every feature and create point objects.
    features[2][i]['geometry']['coordinates'][0]
    features[2] - array with geojson points
    [i] - points number (0-91)
    ['geometry'] - point attribute with geometry
    ['coordinates'] - attribute that consist coordintes
    [0] - array with lat\lng that we should use to create ol.geom.Point. 

    var source = new ol.source.Vector({
      features: points
    });

    /// - creating of vector source from array of ol.Feature point objects 

    var clusterSource = new ol.source.Cluster({
      distance: 40,
      source: source
    });

    /// - creating of cluster source from our vector source

    var styleCache = {};
    var clusters = new ol.layer.Vector({
      source: clusterSource,
      style: function(feature, resolution) {
        var size = feature.get('features').length;
        var style = styleCache[size];
        if (!style) {
          style = [new ol.style.Style({
              radius: 20,
              stroke: new ol.style.Stroke({
                color: 'rgba(225,225,225,0.2)',
       width: 10
              }),
              fill: new ol.style.Fill({
                color: '#3399CC'
              })
            }),
            text: new ol.style.Text({
              text: size.toString(),
              fill: new ol.style.Fill({
                color: '#fff'
              })
            })
          })];
          styleCache[size] = style;
        }
        return style;
      }
    });

    /// - styling as in OL3 clustering example

    map.addLayer(clusters);

    /// - adding cluster layer to the map
    });


    About styling with response to cluster size i will write later
    Read more ...

    OpenLayers 3: onload, moveend events, kml, geojson layers - first steps troubleshooting guide, part 1

    When I started my familiarity with OpenLayers 3, this map library has looked like a hell for me because... because before that I had used only Google Maps API for interactive maps coding.
    So, this is my first part of first step troubleshooting guide
    In this post i want to make a review of a few solutions for a first-step problems that i had with OL3.
    P.S.
    I`m not  a professional in webmaps, so if you know best solutions - comment please.


    OpenLayers 3 events

    Often everybody thinks that information about events in openlayers 3 is something elementary and writes nothing about that. OL3 API contains some info, but it is smashed like a butter on a bread (moreover, you need turn off 'stable only' checkbox). 

    OpenLayers 3 onload events

    OL3 do not contains clean version of onload event, but it contains some another triggers that should help to realize onload event in openlyers 3 :

    'postrender' - event that shoots after the map has beer rendered.


    map.on('postrender', function(){ 
     alert('Loaded!'); 
    });


    But this realization have one little problem. Method .on() will activate your target action each time when map will render. Practically you will have alert('Loaded!')  after each zooming or map dragging (any map change that needs to be rendered).

    Solution is simple.

    Near the .on() method OL3 includes .once() - method that activate target action only once, and this is very useful for us.


    map.once('postrender', function(){
     alert('Loaded once!');
    });


    In this realization out`s target alert('Loaded!') loaded only once, after first render of the map.

    OpenLayers 3 map move events (onmove)

    For these needs we should use 'moveend' - map event that shoots after each completed map dragging.


    map.on('moveend', function(){ 
     alert('The map has been moved!'); 
    });

    OpenLayers 3 map click events

    In OL3 implemented few types of click events:

    'click' - for each click on the map.


    map.on('click', function(){ 
     alert('Any click'); 
    });


    'dblclick' - for double click on the map.


    map.on('dblclick', function(){ 
     alert('Double click'); 
    });


    'singleclick' - event of one single click without doubling.


    map.on('singleclick', function(){ 
     alert('True single click'); 
    });

    OpenLayers 3 geoJSON and KML layers.

    Using of layers is a GIS basics. OL3 has flexible abilities to add layers to your map, but this flexibility needs some attention.

    For creating a layer object OpenLayers 3 uses source object. That's means that before creating layer you need to create source object from your source file.

    The most frequently used types of geometry source are GeoJSON and KML.
    For geoJSON source we should use ol.source.GeoJSON, for KML we should use ol.source.KML.

       
    var LayerSource = new ol.source.GeoJSON({
    url: "filename.geojson"
    });


    And then create vector layer from this source


    var VectorLayer = new ol.layer.Vector({
    source: LayerSource, 
    style: yourstyle
    });


    'VectorLayer' - your layer with geojson\KML geometry.

    'yourstyle' - features style. Simple example of OpenLayers 3 styling:

    var yourstyle = new ol.style.Style({
    fill: new ol.style.Fill({
    color: 'rgba(255,105,91,0.5)' // use rgba for opacity
    }),
    stroke: new ol.style.Stroke({
    color: '#fff',
    width: 1
    })
    });

    To be counted....
    Read more ...