The use of maps. Leaflet and GeoJson

Leaflet is a JavaScript library for connecting interactive maps. GeoJson is a popular format for describing data about various geographical objects. Following is html code of the page with example including comments.

Screenshot from 2015-07-31 11:27:04.png

Leaflet_GeoJson
<!DOCTYPE html>
<html>
<head>
    <title>Leaflet-GeoJson example</title>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

<!-- First, we connect the styles and script Leaflet. The next two strings are needful just to get code working. -->

     <link rel="stylesheet" href="http://cdnjs.cloudflare.com/ajax/libs/leaflet/0.7.3/leaflet.css"/>
      <script src="http://cdnjs.cloudflare.com/ajax/libs/leaflet/0.7.3/leaflet.js"></script>
</head>
<body>

    <!--The document obligatory should contain div with id = "map".
        It is the div where the map will be displayed. It's sizes will define sizes of map -->

    <div id="map" style="width: 600px; height: 400px"></div>
    <script>  
          
          /*
We'll write content of file /geomongo/testdump/testservice- dump/points.json to array.
These data we'll display on map         
          */

        var data =[
            { "_id" : { "$oid" : "55282f3b5c0dd1178d37f7a6" }, "date" : { "$date" : 1428707691703 }, "location" : { "type" : "Point", "coordinates" : [ 11, 2.3 ] }, "name" : "" },
            { "_id" : { "$oid" : "55282f405c0dd1178d37f7a7" }, "date" : { "$date" : 1428707696350 }, "location" : { "type" : "Point", "coordinates" : [ 11, 2.4 ] }, "name" : "" },
            { "_id" : { "$oid" : "55282f4a5c0dd1178d37f7a8" }, "date" : { "$date" : 1428707706604 }, "location" : { "type" : "Point", "coordinates" : [ 1, 2.4 ] }, "name" : "" },
            { "_id" : { "$oid" : "5528334b5c0dd1178d37f7a9" }, "date" : { "$date" : 1428708731758 }, "location" : { "type" : "Point", "coordinates" : [ 12, 2.4 ] }, "name" : "" },
            { "_id" : { "$oid" : "552833515c0dd1178d37f7aa" }, "date" : { "$date" : 1428708737813 }, "location" : { "type" : "Point", "coordinates" : [ 22, 2.4 ] }, "name" : "" },
            { "_id" : { "$oid" : "552833515c0dd1178d37f7bb" }, "date" : { "$date" : 1428708737814 }, "location" : { "type" : "Point", "coordinates" : [ 24, 4.4 ] }, "name" : "point_GT_1318" },
            { "_id" : { "$oid" : "552833515c0dd1178d37f7cc" }, "date" : { "$date" : 1428708737814 }, "location" : { "type" : "Point", "coordinates" : [ 24, 4.4 ] }, "name" : "point_GT_1319" },
            { "_id" : { "$oid" : "55a624c09bf770b58a355f07" }, "location" : { "type" : "Point", "coordinates" : [ 1, 1 ] }, "alt" : 1, "date" : { "$date" : 1441927937814 }, "channel_id" : { "$oid" : "556721a52a2e7febd2744201" }, "json" : { "description" : "testGT-1332", "image_url":"http://www.dunbartutoring.com/wp-content/themes/thesis/rotator/sample-1.jpg"} },
            { "_id" : { "$oid" : "55a624c69bf770b58a355f08" }, "location" : { "type" : "Point", "coordinates" : [ 1, 1 ] }, "alt" : 2, "date" : { "$date" : 1441927937814 }, "channel_id" : { "$oid" : "556721a52a2e7febd2744201" }, "json" : { "description" : "testGT-1332", "image_url":"https://www.drupal.org/files/hr10_sample_image_02_original.jpg" } },
            { "_id" : { "$oid" : "55a624cb9bf770b58a355f09" }, "location" : { "type" : "Point", "coordinates" : [ 1, 1.2 ] }, "alt" : 1, "date" : { "$date" : 1442014337814 }, "channel_id" : { "$oid" : "556721a52a2e7febd2744202" }, "json" : { "description" : "testGT-1332", "image_url":"http://www.dunbartutoring.com/wp-content/themes/thesis/rotator/sample-1.jpg" } },
            { "_id" : { "$oid" : "55a624ce9bf770b58a355f0a" }, "location" : { "type" : "Point", "coordinates" : [ 1.3, 1 ] }, "alt" : 2, "date" : { "$date" : 1441927937814 }, "channel_id" : { "$oid" : "556721a52a2e7febd2744202" }, "json" : { "description" : "testGT-1332", "image_url":"http://www.dunbartutoring.com/wp-content/themes/thesis/rotator/sample-1.jpg"} },
        ]
        
          /*
       Create a map.
       In accordance with Leaflet's concept, map is an object which is able to work with coordinates, user input and some other data. But it is not able to draw the map for users, with houses or roads.
So, if we just add this line, div will contain only "a gray rectangle without map".
        The first parameter is geographical coordinates of the map center, real numbers in format <degree.fractions_of_a_degree>.
    The second parameter is the scale: 0 - continent are visible, 18 - houses are visible.        
          */

        var map = L.map('map').setView([5.0, 6.0], 4);
        
          /*
        Add the map layer. 
        So as Leaflet doesn't define a visual representation of the map, we can use various map services such  as GoogleMaps or OSM.
Here we'll use Mapbox.
        The first parameter is URL template.
        About it possible to read here: http://leafletjs.com/reference.html#url-template.
          */
        L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token=pk.eyJ1IjoibWFwYm94IiwiYSI6IjZjNmRjNzk3ZmE2MTcwOTEwMGY0MzU3YjUzOWFmNWZhIn0.Y8bhBaUMqFiPrDRW9hieoQ', {
            maxZoom: 18,
            id: 'mapbox.streets'
        }).addTo(map);
       
          /*
       GeoJSON is a format for recording data about different geographical objects.
GeoJSON object describes the shape and peculiarities of a geographical location.
    GeoJSON supports various types of shape: Point, LineString, Polygon, MultiPoint, MultiLineString, MultiPolygon, GeometryCollection.
    An object of type 'Feature' includes simultaneously information aboutthe shape of a geographical object and a description of its parameters.
     In Leaflet GeoJSON objects are drawn on the separate layer. Let's create it and add it to map.       
          */

        var myLayer = L.geoJson().addTo(map);
        
          /*
Draw our data on the map as points the following way:
for records with "name" attribute we will display a pop-up window with correspondent text value; for markers with link to the image we will display this image in pop-up. 
Also for few point we will change regular markers to customized ones.
First of all, we will cast type of our data to the Feature, taking useful and eliminating non-relevant attributes      
          */

        var featureArr = [];
        for(var i in data){
            var geojsonFeature = {
                "type": "Feature",
                "geometry": data[i].location,
                "customizeView":Math.floor(Math.random()*2) // randomly 0 or 1
            }
            if(data[i].hasOwnProperty('name'))
                geojsonFeature.popupContent = data[i].name;
            else if(data[i].hasOwnProperty('json') && data[i].json.hasOwnProperty('image_url'))
                geojsonFeature.popupContent = '<a href="'+ data[i].json.image_url+'" > image_link </a>';
            featureArr.push(geojsonFeature);
        }
        
          /*
       Object L has geoJson method. This method returns geojson object which could be attached to the map. GeoJson
Parameters  of geoJson:
 L.geoJson( <Object> geojson?, <GeoJSON options> options? )
        - first object which will be attached to map
        - second object which is describing attaching options
      More detailed here: http://leafletjs.com/reference.html#geojson
     One of the options is a function onEachFeature called for each object before adding it to GeoJSON layer. We use it to connect points to pop-up windows.       
          */

        function onEachFeature(feature, layer) {
            if(feature.hasOwnProperty('popupContent'))
                layer.bindPopup(feature.popupContent);
        }
        
          /*
      Some points we will show as circles. Define the style for these points.
      Style also is an object, later it will be passed to the function.
         */

        var geojsonMarkerOptions = {
            radius: 8, //radius in pixels
            fillColor: "#ff7800",
            color: "#000",
            weight: 1,
            opacity: 1,
            fillOpacity: 0.8
        };
        
          /*
      Define the function for visual presentation. 
It's a part of set of options and it will be called for each object before its addition.
In this function in depending on conditions we will return different objects of layer.
latlng - latitude and longitude will be automatically extracted from each Feature and passed futher. 
        */

        function pointToLayer(feature, latlng) {
            if(feature.customizeView)
                return L.marker(latlng);
            else
                return L.circleMarker(latlng, geojsonMarkerOptions);       
        }    
        
          /* 
       Let's add all points on GeoJSON layer, specifying in options our functions.       
          */

           L.geoJson(featureArr, {
           onEachFeature: onEachFeature,
           pointToLayer: pointToLayer 
        }).addTo(map);
        
          /*
       Let's add on map geometric figures which size is in difference of markers connected not to the screen but to the real landscape. So they will be scaled in and scaled out with zooming.
         */

        var circle = L.circle([7, 8], 100000/*radius in meters*/, {
            color: 'red',
            fillColor: '#f03',
            fillOpacity: 0.5
        }).addTo(map);
        var polygon = L.polygon([
            [6.1, 6.3],
            [7.3, 6.5],
            [5.1, 3.4],
            [3.3, 4.1]
        ]).addTo(map);
     
        // Let's create a polygon with GeoJson data

        var geoJson_polygon = {
           "type":"Feature",
           "geometry":{
                "type": "Polygon",
                "coordinates": [[
                    [6, 6],
                    [7, 7],
                    [5, 3],
                    [3, 4]
                ]]
            },
            "someOptionalData":"someData"
        }

        //And will add it on the map

        L.geoJson(geoJson_polygon,{
           style: {
               "color": "#ff7800",
               "weight": 5,
               "opacity": 0.65
            }
        }).addTo(map);
    </script>
</body>
</html>
ShareShare on FacebookShare on Google+Tweet about this on TwitterShare on LinkedInShare on VKEmail this to someone