GIS Book
GIS Book
My parents
My wife Rita
and
1         Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
1.1 This Book                                                                                                                                                                                                    11
1.2 Installation of QGIS                                                                                                                                                                                         11
1.3 QGIS Interface                                                                                                                                                                                               11
1.3.1 Layers Panel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
1.4 Understanding QGIS interface through exercise                                                                                                                                                                12
1.4.1 Example: Visualizing GIS data in QGIS . . . . . . . . . . . . . . . . . . . . . . . . . . 13
1.5 Elements of QGIS interface                                                                                                                                                                                   16
1.5.1   Layers panel .       .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   16
1.5.2   Browser panel        .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   17
1.5.3   Menus/Tools .        .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   19
1.5.4   Status Bar . . .     .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   19
1.6 Using menus and tools of QGIS.                                                                                                                                                                               20
4         Database Management . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
4.1 What is information system                                                                                                                                                 75
4.2 Basic tutorial for Database management                                                                                                                                     76
4.3 Using Selection Statements in Database Management                                                                                                                          80
4.4 Creating and editing table in a database                                                                                                                                   84
4.5 Information System vs Geographic Information System                                                                                                                        86
4.5.1 Converting non-spatial database to spatial database . . . . . . . . . . . . . 86
4.6 Summary of database management system                                                                                                                                      89
4.6.1 Definition of database and DBMS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
4.6.2 DBMS applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90
       In the popup window click browse and point to the folder where you extracted
       the data. See the Figure 1.1.
      Note : If All Files is selected in the filter, change it to ESRI shapefile so that you
 can see fewer files in the list.
      Select the file ne_50m_admin_0_countries.shp and click Open (in the file se-
 lection window), again click open in add vector layer window. You will see the map
 of the world added to the display area.
     2. Click on the Add Vector Layer tools under Manage Layers tool bar as shown
        in the Figure 1.1.
        You will get the same popup window as in the above step(Figure 1.1. Follow
        the steps as shown in above method.
            If you have completed the above exercise, your Layers Panel will look like Figure
        1.5. Inside the Layers panel, you will see all the layers you have added to the map.
        There are 8 tools as shown in the same figure. Each layer in the list of layers have three
        1.5 Elements of QGIS interface                                                          17
        components: 1) check box for showing/hiding the layer, 2)Symbol of the layer and 3)
        name of the layer. Some properties of the layer shown in the list of layers is enumerated
        below, try to learn by practicing.
            • When a layer is clicked, it becomes selected and the background changes to blue.
            • If you click on the check box on the left, it will toggle between hide and show.
              When the check box is checked, the layer is visible on the map. Try to show and
              hide each layer.
            • When you right click a layer, you will get a context menu. We will illustrate some
              of the context menu items in this chapter through exercise. Some of the items will
              be introduced in the upcoming chapters.
            • Double clicking a layer will show its properties.
            • Now let us look at some of the tools marked 1 to 8 in Figure 1.5. Details of each
              tool shall be explained through exercises.
                1. Open the layer styling dock: This tool can be used to change the style of the
                    layer.
                 2. Add group: This tool will add a group. This tool helps managing layers in
                    group.
                 3. Manage layer visibility: This tool will show or hide multiple layers in the
                    Layers Panel. You can try clicking on the tool and the subsequent menu
                    items.
                 4. Filter legend by map content: This tool will be explained later.
                 5. Filter legend by expression: This tool will be explained later.
                 6. Expand all: This tool will expand the layers inside a group.
                 7. Collapse all: When you select a group in the layers panel and click Collapse
                    all tool, the layers within the group will be hidden. It is opposite of Expand
                    all tool.
                 8. Remove layer or group: Select a layer in the layers panel and click on this
                    tool and see what happens.
1.5.3   Menus/Tools
        Many of the QGIS capabilities can be accessed through menus and tools of QGIS. Some
        of the tools and menus will be explained in the next example.
             As shown in Figure 1.7 and marked from 1 to 5, let us look at the functions of some
        of the toolbars.
            1. Project toolbar: You can create a new project, open an existing project, save an
               opened project with the tools in this toolbar. You can also create or open a canvas
               for printing. The same function can be accomplished by using sub menus of Menu
               ⇒ File.
             2. Map Navigation toolbar: You can zoom and pan the map with these tools. You can
                also zoom to a selected feature (What is feature? ⇒ see the next chapter). Many
                of the capabilities of this toolbar can also be accomplished by using sub menus of
                Menu ⇒ View.
             3. Attribute toolbar: The tools contained in this toolbar can be used to identify the
                features of different layers of map(identify tool). You can also select a feature of
                the map (Selection tool). Using Attribute tool, you can show attributes of a layer.
                You can also measure length, area or angle using Measure tool.
             4. Label toolbar: It is used to label the features of the map.
             5. Digitizing toolbar: It is used to edit the features of a layer.
         b. Click Zoom Out tool (with - sign) and draw a rectangle on the map and
            see what happens.
         c. Click Zoom Last tool and observe what happens. You will see that the
            area displayed just before using Zoom Out tool will be displayed. You
            can click on this tool as many times you like. When there is no history
            remaining for the last displayed area, the tool will be grayed out (disabled).
            Now you can click Zoom Next tool and see that display area will change
            in the forward direction. These tools are similar to the back and forward
            arrow in the web browser.
    • Using Identify tool: Click Identify Features tool on the Attribute toolbar.
      Click any country on the world map.
      You will see Identify Results panel displayed somewhere(probably on the right
      side) in the user interface. You will see the attributes of the feature displayed in
      tabular form as shown in following figure.
22                                                          Chapter 1. Introduction
         d. Now let us try to use Layer Diagram Options tool. You can see it beside
            Layer Labeling Options tool.
       Above figure shows the steps to show Label as diagram.
     • Step-1: Click the tool Layer Diagram Options. On the left pane of the dialog
       box, change No diagram Rightarrow Pie Chart.
     • Step-2: Select Attributes from the list on the left pane. Select Attribute
       “POPE ST ” and click on the plus(+) sign.
     • Step-3: Select Size from the list on the left pane. Select Scaled Size radio on
       the right pane. In the Attribute selection box, select POP_EST. Click Find
       button to fill the Maximum Value field. In the Size input box, write 6. Check
       the Increase size of small diagrams and set the value to 0.2.
     • Step-4: Click OK at the bottom of the dialog box.
                                                                                    
                            2. GIS Data Types and Symbology
        In the last chapter we learned how to add GIS data in the map display area and also
        acquainted to some of the menus and tools of QGIS. In this chapter we will talk a little
        bit more about the types of GIS data.
            GIS data represents the real earth in terms of geometry. There are several types of
        GIS data, but we will focus mainly on two types of data, namely, Vector and Raster data.
        Let us try to understand what is represented by these two types of data respectively.
raster data.
Figure 2.1: Elevation data (one of the most used GIS data)
          Figure 2.1 is an elevation data represented in black to white color. Black color
      represents lower elevation while white color shows higher elevation. Every cell in the
      raster data has some value which represents the elevation at corresponding point. Raster
      data can have more than one value for each cell. These are called raster bands. Elevation
      data shown above has single band.
          Figure 2.2 is an image taken by satellite called Sentinel. For every cell there are three
      values. This raster image has three bands. If we represent each band as red, green and
      blue color, we get a true color image same as what we see with our eyes. By the way,
      photographs we take with our digital camera also are three band raster data. We need to
      assign colors to each band so that we can see the image.
2.2   Symbology
      In the last chapter we displayed the map of countries of the world. All the polygon
      features were displayed with the same color (fill), and boundaries (boarder) of the
      countries were displayed in black color. We can change the fill color and boarder color
      of the polygons based on various attributes of the layer. Representing the GIS data with
      different colors and symbols is part of Symbology. In the following examples we will try
      to assign different symbols to vector and raster data.
        2.2 Symbology                                                                        27
            Download GIS data for Nepal administrative boundary and few other data from
        following URLs. Create a folder named Exercise02 in your workspace.
            • http://ngiip.gov.np/data-center/topographical-data (Data with file
              name 1000k.zip will be downloaded to your default path when you click on the
              link named 1000K. Move the file to Exercise02 folder.
            • http://ngiip.gov.np/data-center/admin-boundary (Click on the link Ad-
              min Palika to download the file. Move the file to Exercise02 folder.
              Note: The urls listed above were accessed on 23rd January, 2018.
               shown in Figure 2.3. Observe the table and click OK to close the dialog.
             • Now click Open attibute table tool. It will show you the list of values of each
               feature corresponding to each field.
            From the above observation we can understand that there are three types of attributes
        1) String, 2) Integer and 3) Real(in general). However, in the due course you can find
        few more types of attributes.
            From the Layer Properties dialog box, we know that - Attribute scalerank is an Inte-
        ger and it can hold 4-digit number (Length is 4). - Attribute featureda and SOVEREIGNT
        are Strings. Attribute featureda can be upto 30 characters long and SOVEREIGNT can
        be 32 characters long. - Attribute LABELRANK is Real and its length can be 5 including
        decimal and 2 digits after the decimal. You can check the data in the attribute table.
can find drop down list of symbols beside Symbol layer type for you to chose. Following
example and exploring the layer properties dialog will make you conversant with layer
styling and symbols.
        b. Similary, find 1000k.zip. It consists of more than one GIS data. Therefore
           it has plus(+) sign on the left. Expand 1000k.zip and add following GIS
           data (ending with .shp) as layers.
              • hydro_ln.shp: Shapefile of rivers as lines
             • hydro_ar.shp: Shapefile of water bodies as polygons
             • elev_ln.shp: Shapefile of contour lines at interval of 1000m
             • trans_pt.shp: Location of airports as points
             • trans_ln.shp: Shapefile of roads as polylines
             • settl_pt.shp: Name of settlement areas as points
        c. Arrange the layers by dragging each layer so that the polygon layers are at
           the bottom and points layers are at the top as shown in Figure below.
           Save the project as ex02a.qgs. You can save the project during the next
           steps and pause your exercise and reopen the project again to restart from
           the last step.
30                                   Chapter 2. GIS Data Types and Symbology
             Alternatively, the dialog can be opened by double clicking the layer from
             Layers Panel.
          b. From the left pane of dialog box, select style. On the right pane change
             single symbol to categorized (See figure).
2.2 Symbology                                                                       31
      c. You can see a dropdown list beside Column. Select GN_TYPE from the list.
      d. Below the list of symbols (which is empty at present), click on Classify. You
         will see a list of unique values which is extracted from attribute GN_TYPE
         of the admin-palika layer listed as symbols.
      e. If you click on Apply button at the bottom right of dialog, you can observe
         the change in colors of the layer. In the list of symbols, you will see the
         following attributes:
            • Gaunpalika
            • Nagarpalika
            • Mahanagarpalika
            • Upamahanagarpalika
            • Wildlife Reserve
            • Watershed and Wildlife Reserve
            • National Park
            • Hunting Reserve
            • Development Area
      f. We need to plan the colors for each type based on our purpose. For the
         present exercise, let us follow the steps below.
           • Double click on the symbol beside Development Area. From the dialog
             box, click on the color selection dropdown list and change the color to
             white (See Figure).
32                                 Chapter 2. GIS Data Types and Symbology
              Alternatively we can select color from the color wheel and triangle
              shown in the figure above.
            • In similar way, select symbols for other GN_TYPES. For Wildlife
              Reserve, Watershed and Wildlife Reserve, National Park and Hunting
              Reserve select dark green color, for Gaunpalika dark-grayish-green
              and different shades of red for Nagarpalika, Upmahanagarpalika and
              Mahanagarpalika (Figure is shown below).
            • Click Apply button at the lower right corner of the properties dialog
              box. Now the map looks more recognizable and purposeful.
          In the fill color select blue and for outline color check Transparent Color
          (see Figure).
          You can see that the roads are all over Nepal and the map does not look good.
          We need a categorized road shapefile so that we can show Strategic road
          network (SRN) more highlighted than other roads. Or, we can symbolize
          each category of roads differently.
       f. Select roads (trans_ln layer) in Layers Panel then click Open Attribute
          Table tool. We can see that there are two attributes for this layer, i.e,
34                              Chapter 2. GIS Data Types and Symbology
        FCODE and NAME. If we scroll down the attribute table, we can see that
        there are many features which do not have NAME.
     g. Now we can change the symbol in such a way that the roads without any
        name will be shown only at low scale. Let us try to do this as explained
        below.
          • Open Properties dialog for trans_ln layer.
          • Click Style in the left pane. In the right pane change Single Symbol
            to Rule-based.
          • Delete any symbol in the list of symbols by selecting it and clicking
            minus(-) sign below the list. Click plus(+) sign. A dialog box (Edit
            rule) will appear as shown in Figure below.
          • Enter the name of Label as you like. Click the button with . . . sign
            beside Filter. Expression string builder dialog box will appear. You
            can find several functions in the list. Expand Fields and Values and
            double click NAME attribute. Add to the expression so that the expres-
            sion is:
             "NAME" IS NOT NULL
          • Change the symbol to double line by adding one more line in the
            symbol in Edit rule dialog box as explained before.
          • Now let us add symbol for the roads which does not have any name. In
            the Property dialog, add rule by clicking on Plus(+) sign. Label it as
            Other roads.
          • As explained above, set the rule expression as (Note the difference
            from above expression):
             "NAME" IS NULL
          • Set a single line symbol for this rule. To allow these roads to appear
            only at low scale, check scale range and in the minimum scale input
            box write 1:200,000.
2.2 Symbology                                                                          35
about the data. Opening the website and clicking the links to explanation for each types
of data, in itself, will be a great learning experience.
    Now let us try to understand the methods of downloading each of the second and
third data.
          a. Open file browser and go to the location where you downloaded Globcover2009_
             V2.3_Global_.zip.
          b. If you look inside the zip file, you will find an Excel file named GlobalCover2009legend.
             xls. Let us have a look at the file.
          c. Open the excel file with Microsoft Excel or LibreOffice Calc. For each
             value in the first column, you will see what it represents in the second
             column. In third to fifth column, it shows the red, green and blue color
             values suitable for the symbol. We will apply these colors to the raster data
             and see how our land cover data looks.
             Now follow the steps below.
             1. Open Property dialog for the layer.
              2. From Render type dropdown list, select Singleband pseudo color,
                 refer Figure. Singleband pseudo color is used to represent single-band
                 raster data in different colors. If you check the dropdown list for Colors
                 in the Property dialog, you can see a list of graduated colors. For
                 example, if you select a color ranging from red to blue, the lowest
                 value will be represented by red, highest by blue and others in between.
                 You can check this by selecting one from the Color dropdown list and
                 clicking Apply botton at the bottom.
              3. Change Interploation to exact. What does it mean? If you select linear,
                 all the values in the list will have some color. In case of exact, only those
2.2 Symbology                                                                          41
            values listed will have colors, others will not have any color.
         4. Change the Mode to Equal interval, so that we can select number of
            classes.
         5. Input 23 in the number of Classes. You can see that there are 23 classes
            listed in the Excel file, therefore we shall follow it. You will see that the
            list in the middle of the right pane is populated by values, colors and
            labels.
         6. Now let us change the list of values and the associated colors. When
            you double click a value in the list, you can edit by typing a new value.
            Similarly, if you double click a color in the list it is possible to change
            the color. It is also possible to change the label for each values.
      d. First value in the list is 11 and it is okay. Double click the color associated
         with this value. A dialog with caption Change color will be displayed. In
         the right pane, you can see input boxes for red, green and blue colors. Input
         170, 240 and 240 for each of these three colors (Refer the Excel file for the
         colors).
      e. Now change the second value to 14 and colors for red, green and blue to
         255,255 and 100 respectively.
      f. Change all the values and associated colors accordingly and click Apply or
         OK button.
    Before starting the practice let me explain what we are going to do in this exer-
cise. We will use Sentinel-2 satellite data downloaded already. The image data will
be located at D:\GIS_exercise\Exercise02\Sentinel-2\L1C_T45RUK_A011799_
20170925T045444(1).zip\S2A_MSIL1C_20170925T044701_N0205_R076_T45RUK_
20170925T045444.SAFE\GRANULE\L1C_T45RUK_A011799_20170925T045444\IMG_
DATA. To find the data you will need to explore the path using File Explorer. The name
of the zip file and and folders will be different but similar. You can check the file naming
system in the earthexplorer website. Inside IMG_DATA folder you will find files with
extension ‘jp2’.
2.2 Symbology                                                                             43
    In the Table 2.1 central wavelength of each band represents color or spectrum of
wave band. Band number 2, 3 and 4 falls in the visible band which our eyes can see as
blue, green and red respectively. Spatial resolution of each band represents the length
and width of each cell of the raster data of that particular band. We can see that each
band has different resolution. We will use visible bands of data for the present exercise.
For the purpose of this exercise we will combine three visible bands into one single raster
data. We can merge the three bands using QGIS using either of the following methods.
   1. Using menu Raster ⇒ Miscellaneous ⇒ Merge
   2. Using Processing toolbox
    Processing toolbox consists of hundreds of special tools provided by different
software such as SAGA, GRASS etc. We will talk about it in different chapter.
    We will use Processing toolbox for the current example. The toolbox is generally
visible on the right side of QGIS interface. If it is not visible, you can click menu
Processing ⇒ Toolbox.
               1. In the Processing toolbox search for merge. Few tools matching the
                  word will be listed in the toolbox.
               2. Double click Merge under GDAL.
               3. Merge dialog box will be displayed. Check ‘Place each input file into
                  a separate band’.
               4. In the Output raster type select Int16.
               5. Selected Merged output file by clicking on the button and select the
                  folder to save the file. Name the outfile, for example, as sentinel_rgb.tif.
               6. Click button for the Input layers and select all the images in the
                  Multiple selection dialog and click OK.
               7. Click Run in the Merge dialog box.
          e. In the resulting image, data acquired from the file ending with ‘B02.jp2’,
             ‘B03.jp2’ and ‘B04.jp2’ will be assigned to band-1, band-2 and band-3
             respectively.
     Step-II. Displaying and exploring multiband data in QGIS
          If everything you did as explained above, the tool will run for a few seconds to
          few minutes depending on the computer specification and the resulting image
2.2 Symbology                                                                         45
       will be displayed in QGIS as new layer. However, the image still does not look
       what we observe with our eyes. The colors are not satisfactory.
        a. Let us have a look at the properties of the rgb layer. The default colors for
            the image display is not correct.
        b. Display Properties dialog by double clicking or by right clicking.
        c. Select Style in the left pane. You can see on the right pane that the colors
           selected for red, green and blue colors are band-1, band-2 and band-3
           respectively. However, according to the information in the Sentinel, band-
           3 represents red color and band-1 represents blue color.
 Step-III. Apply proper symbol to the satellite data
         a. We need to swap bands for red and blue color on the right pane. For this,
            change the text in the dropdown list beside red channel to band-3 and text
            beside blue channel to band-1.
        b. Click Apply button. Now the color looks more natural.
           Still, the image is not very satisfactory. It is because, the color stretches
           to whole range of each band’s minimum and maximum value. To correct
           this, we need to correct the stretch. Select Histogram on the left pane.
           The histogram shows a graph of the number of pixels versus the range of
           values, refer Figure ??. From the figure, we can see that:
       c. Expand the zip file and select the file ending with dem.tif (see figure).
       d. Drag and drop to the display area.
       e. Save the project as ex02c.qgs.
48                                    Chapter 2. GIS Data Types and Symbology
            • Click and select (4) and change Relative position to 33.3 and color to
              green.
            • Double click around (5)
            • Click and select (6) and change Relative position to 66.7 and color to
               red.
          In this way, we are going to assign white color to highest point, blue color
          to lowest point and red and green colors to intermediate heights. We could
          have chosen other colors. But this is just a demonstration of one more ways
          of symbol application.
       g. Click OK on each dialog and have a look at our new map displayed in the
          display area.
 Step-III. Create hillshade from elevation data and display with transparency
       We can analyze elevation data in various ways. We will have special chapter
       for this. In the meantime, let us see how this terrain looks from above. Follow
       the steps below:
        a. From the Menu select Raster ⇒ Analysis ⇒ DEM(Terrain Models)
       b. Select output file (for example as hs.tif in your working directory under
          Exercise02) in the next dialog, keep other things as default. Click OK.
          Hillshade will be created and displayed.
       c. Open the property dialog for the newly created hillshade layer.
       d. Select Transparency in the left pane and set transparency to around 50%.
          You will get a beautiful display as in figure 2.9.
50                Chapter 2. GIS Data Types and Symbology
          explained previously.
       2. From menu select Project ⇒ Layout Manager. In the Layout Manager
          dialog box click button Create. Give some name to the new layout, such as
          map practice. Following figure shows the QGIS layout manager interface.
       3. First of all, check the mapping interface has all the desired layers are added
          and proper symbology applied. Now, in the layout window add new map.
          To do this click on Add new map tool and draw a rectangle where you
          want your map to appear. Once you draw the rectangle, your map will look
          like as shown below.
               we have the list of legend as shown in the figure below. Right figure
               shows the legend as displayed in the layout.
             • You can check other options inside Item properties and try changing
               them.
Step-III. Add title to the layout
        1. From the toolbox click Add text tool to add text to the layout.
       2. Default text is Lorem Ipsum. To edit the text, you need to check Item
          Properties tab on the right pane as shown below. Whatever you write in
          the textbox will appear in the title text. You can edit the text: font, color,
          vertical and horizontal alignment etc. Alternatively, you can add an HTML.
          For example, write the following HTML sentence in the text box and check
          Render as HTML checkbox.
          <p style="font-size:20px;color:red;"> A Simple Map of Nepal
          </p>
2.3 Map production and cartography                                                55
            • Width ⇒ 50 units
Step-VI. Add grid and coordinates to map
       1. Select the map by clicking it. In the Item properties expand Grid.
       2. Add a grid by clicking ‘+’ sign.
       4. Edit the items as shown in the figure above. Interval → X = 1.0; Y = 1.0 ;
          Frame style to Zebra or as you like.
       5. Scroll down the dialog to Draw coordinates and check it. Edit the items as
          shown in the following figure or as you like. In the following figure, the
          modified items are:
            • Format → Decimal with suffix
            • Right → Disabled
            • Top → Disabled
2.3 Map production and cartography                                                57
Producing an atlas
Let us use the same map as before to produce an atlas. The atlas will be based on the
province boundary of Nepal as feature class. Follow the steps in Exercise 2.6.
58                                 Chapter 2. GIS Data Types and Symbology
       3. You will see a map item added in the list of items on the right pane.
       4. Lock layers for this map too as explained before.
Step-III. Create overview
        1. While the new map is selected, add an overview from Item Properties on
           the right pane. For this check Overviews and add an overview by clicking
           ‘+’ sign.
2.3 Map production and cartography                                                59
      2. While overview 1 is selected, select main map (It is Map 2 in this example)
         in Map Frame.
Step-IV. Create atlas
       1. Change the text of title to make it variable.
          <p style="font-size:20px;color:red;"> Map of Province No.
          [% state_code %] </p>
      2. Select the main map. From menu click Atlas ⇒ Atlas Settings. In the right
         pane, a new tab Atlas will appear. As shown in the figure set the items as
         follows:
                output. Page name displayed in the atlas will be like province_1 etc.
              • Check Sort by and set the expression as state_code. The images will
                be produced from province number 1 to 7.
         3. Now select tab Item Properties in the right pane. Scroll down to Con-
            trolled by atlas and check the checkbox.
         4. In the tool bar find the tool name Preview atlas and click it. Now you will
            see the main map is zoomed to Province 1.
         5. Everything is OK, however, size of scale bar is not appropriate. You can
            edit its properties.
         6. The atlas can be output as raster imagge (png, jpeg etc), vector image (svg)
            or pdf. Click menu Atlas ⇒ Export atlas as images. Select a folder to
            output images. Multiple images from province 1 to 7 will be created.
      After reading and practicing the first two chapters that you can do everything in GIS or
      QGIS. But, many things are still to know. We might want to know how QGIS knows
      where to place a point or a line or a polygon or a raster image. It requires the location
      of these features. Locations are expressed in terms of coordinates. Now is the time to
      upgrade yourself and learn a few things about coordinate reference system. We might
      be able to display maps without the knowledge of coordinates, but for analysis and
      understanding of GIS data we need to know how the locations are conceived in GIS.
           The frame (above) shows a movable and zoomable 3D image of sphere with latitude
      and longitude. Somewhere on the sphere you can see a map of Nepal. It is made with R
      programming language. By draging with mouse or moving the mouse wheel the image
      can be rotated and zoomed. You can see that Nepal is situated between around 26 to 30◦
      latitude and 80 to 90◦ longitude. Any point on the earth can be, now, expressed in terms
      of latitude and longitude. As we can see, the latitude varies from −90◦ to 90◦ . The
      negative value represents locations south from the equator and positive means north
      of equator. Similarly, longitude varies from −180◦ to 180◦ . Negative value represents
      locations west from the prime meridian and positive means east of prime meridian.
      A point on earth can be reprsented for example as (85.5732, -27.3456) or (85.5732E,
      27.3456S). ‘E’, ‘W’, ‘N’, ‘S’ is, obviously, short form for the four directions. Try the
      following exercise.
           1. Open https://www.google.com/maps.
           2. In the search box type ‘27.7, 85.312’ (without quotes) and click enter.
           You will find the map centered at the point (85.312E, 27.7N). Google maps uses
      latitude first.
          We have shown the latitudes and longitudes on sphere in the above images. You might
      think that your knowledge of coordinates is complete with this information. However, in
      GIS we don’t work with 3-dimensional display. You might recall the map of the world
      we created in the first exercise 1.4.1. When you display the map in cartesian coordinates,
      the map stretches from -180 to 180 degress in x-direction and -90 to 90 degrees in
      y-direction. However, if you check the sphere above, you can see that -180 degrees (180
      degrees west) and 180 degrees (180 degrees east) represents the same line. Simiarly,
      we can see that the circles parallel to the equatorial one get smaller as we go towards
      north or south. However, on the flat display, it is not the same. The distance between
      places get highly exaggerated as we go farther from equator. These and few more things,
      make it essential to devise better ways to represent the locations more accurately on the
      plane map. In simple words, we can say that ‘it is impossible to reprsent any part of earth
      accurately on a two dimensional plane’. Only a three dimensional globe can represent
      the locations close to the actual. Many approaches has been devised and in practice to
      minimize the loss of accuracy. We will try to understance some of them in the following
      sections.
      In the first exercise 1.4.1, we used latitude and longitude as x-coordinate and y-coordintae
      respectively. This is called *geographical coordinate system** (GCS).
          We can not put whole the globe on a plane paper. However, we can represent a small
      portion of globe with higher accuracy. The methods of representing curved surface of
      globe on a plane surface is called projection. Let us think how we can do this.
        3.2 Projection and projected coordinate system                                            65
          Datum (the assumed shape of earth) and the projection in combination is used to
      define a Coordinate Reference System. Following combinations and many more are
      possible:
          • WGS84 (datum) and Geographic coordinate system (Without projection)
         • WGS84 and UTM 45N (It can represent only 84◦ to 90◦ East only)
         • JGD2000 and Geographic coordinate system
         • JGD2000 and UTM 53N (some portion of Japan)
         We will try to understand some details with exercise.
        with extension .prj contains the information about the type of Coordinate Reference
        System used in the shapefile.
     Let us see the contents of the shapefile inside WGS84 folder. You will see a file
 with extension .prj. Zoom the map to the extent of admin_ar layer. Move the cursor
 on the map and observe the coordinates in the status bar. The x-coordinates will be
 80 to 90 and y-coordinate will be 25 to 30.
     Repeat the above exercise for other shapefiles, for example, admin_ln in the
 directory 1000k. Let us compare the projection (.prj) files created for each shapefile.
 You can open these projection files with Notebook or any text editing software. By
 examining the two files you can see that they are completely identical. Which means
        70                                      Chapter 3. Coordinate Reference System
          you can:
             • copy admin_ar_wgs.prj which is created in the new directory (WGS84) and
               • paste into 1000k directory and change the name of file to admin_ar.prj.
               • Now, if you add the admin_ar shapefile in QGIS it will not show any warning.
               • In the same way, you can copy-paste the projection file and rename it to match
                 the remaining shapefiles.
                                                                                             
        We saw in the last section that CRS is represented in the form EPSG:n, where n is a
        number. So, what is EPSG? It is short form of ‘European Petroleum Survey Group’.
        There are many CRS’s in use and EPSG coded all (most of) the CRS and gave a code to
        each. Hence, the CRS can be expressed as EPSG:n where n is the EPSG code.
           Some EPSG codes and there are name are given below:
           • EPSG:4326 WGS84 (World Geodesic System 1984) Geographic coordinate sys-
             tem
           • EPSG:32644 Project coordinate system at zone UTM 44N based on WGS84 datum
           • EPSG:32645 Project coordinate system at zone UTM 45N based on WGS84 datum
            http://spatialreference.org/ is the best place to find different spatial refer-
        ences (Coordinate reference system), their meaning, locations and codes. You are advised
        to spend at least an hour or two to acquaint yourself to the meaning of CRS.
        72                                    Chapter 3. Coordinate Reference System
         a) Select Metadata in the dialog box, left pane. You can see various proper-
            ties associated with the data. (Note: all GIS data has associated metadata
            which gives you many important information).
         b) Scroll down the right pane to view the properties section which has its
            own vertical scroll bar.
         c) Scroll down this section to find various properties such as Statistics,
            Dimensions, Pixel Size, Extent etc.
         d) You can see that size of each pixel is around 0.000278◦ . The extent of the
            data is from around 86 to 87 in x-direction and 27 to 28 in y-direction.
         e) If we need to change the data to UTM projection, we need to select the
            UTM zone. From the data, it is clear that it lies in UTM 45N zone.
    3. From menu, click Raster ⇒ Pro jections ⇒ warp(Repro ject). In the next
       steps the numbers in brackets are associated with the numbers in the figure.
    4. Select Output file (1) and save the output in the UTM folder.
      74                                    Chapter 3. Coordinate Reference System
            5. Check Target CRS (2). Select CRS by writing 45N in the filter and selecting
               EPSG:32645 from the list (3).
            6. Set the resampling method as Near(4).
            7. Set No data values as -9999 (5).
            8. Click OK (6). In the confirmation dialogs click OK and finally click Close on
               Warp(reprojection) dialog. You may save the project as ‘ex03b.qgs’.
            9. Click New tool from the Projection toolbar. Add the newly created raster
               elevation data to the map. You can observe the corners by zooming. You can
               also find the cell size of the newly created raster data. How?
                                                                                           
      Database is the backbone of any information system. In this chapter we will learn about
      database and its handling in QGIS.
     We can see that a single database can have multiple tables. Now let us see what
 we can do with these tables. Click one of the tables under spatialite. As shown in
 the following figure, information about the table will appear on the right pane of DB
 Manager window.
     Now click Table tab on the right pane. You can see the contents of table. See
 figure below (it shows part of the table).
78                                              Chapter 4. Database Management
        You can check the information and contents of each table. Use horizontal and
    vertical scroll bars to see the hidden contents. Let us try to observe what kind of data
    are kept in each tables. You can easily find the number of records in each table by
    just scrolling up and down.
                                                                                          
        window tab on the right pane. Remember to select the flights database before
        opening SQL Editor tool.
     • Let us try with simplest SQL. Write SELECT * from airlines; in the Query
       window.
     • Click execute. See the figure below.
   In the above example, we displayed all the rows of the table airlines. Now try some
more complex SQL queries. Try following queries one by one and observe the output.
  1. SELECT * FROM airlines WHERE country=’Russia’;
   2. SELECT * FROM airlines WHERE country=’Russia’ ORDER BY icao;
   3. SELECT id, name, icao, country, active FROM airlines
      WHERE country=’Russia’ ORDER BY icao;
   4. SELECT id, name, city, country, code, icao, altitude FROM airports
      WHERE country=’Nepal’;
   5. SELECT id, name, city, country, code, icao, altitude FROM airports
      WHERE country=’Nepal’ AND id>2000 AND id<2100;
   6. SELECT airline, airline_id, source, dest, codeshare, stops
      FROM routes
      WHERE source=’KTM’ ORDER BY dest DESC;
   The SQL statements are fairly simple and follow general spoken language. Let us
summarize what we observed by executing above SQL statements.
  1. General structure of SQL statement is SELECT [columns] FROM [table name]
     WHERE [Where clause joined with AND] ORDER BY [columns] LIMIT
     [number of rows].
   2. Check the information of any of the 3 tables as explained in above exercise. We can
      see that each column has a type. For example, airlines table has 9 columns. The
      80                                              Chapter 4. Database Management
              column named index is INTEGER while all the others are TEXT. SQLite database
              table can have three types of columns (also called fields). They are:
                 • INTEGER (Can have integer numbers eg., 1, 10, 299,12568833 etc)
                 • REAL (Represents decimal numbers, such 1.25, 2.5)
                 • TEXT (Consists of strings such as name of the places etc which are repre-
                    sented by text)
           3. While SQLite supports several types of column such as INTEGER,TEXT, REAL,
              DATE, time etc.
           4. In the above SQL statements, the words have different colors. The blue colored
              words are keywords. Column names are black. Structure of where clause is
              writeen in the form: column <operator> value. Where operator can be =, >, <,
              LIKE, UNLIKE etc. Note that while comparing text column, the value should
              be enclosed in single quote. Integer and real values should not be enclosed into
              quotes.
           What is the fullname of airline in the above table? What does BHR mean in the dest
      column? These data are kept in other two tables airlines and airports. Can you find
      which column of routes is related to airlines table? Similarly, which column of routes
      is related to airports?
           We can query multiple tables in a single query when one column of a table is
      related to any column of another table. Write the following SQL statement and execute.
4.3 Using Selection Statements in Database Management                                  81
Following SQL is a single SQL. It can be written in multiple lines with semicolon at the
end.
SELECT routes.airline, routes.airline_id, routes.source, routes.dest,
   airlines.name,
   airports.city, airports.country
FROM routes, airlines, airports
WHERE source=’KTM’
AND routes.airline_id =airlines.id
AND routes.dest_id=airports.id
ORDER BY dest LIMIT 5;
     What did we do in the above statement? We selected columns from three tables
such that airline_id column of route table and id column of airlines table are equal.
Similarly, dest_id column of routes table is equal to id column of airports table. With
practice, this type of simple SQLs can be easily mastered. However, it is possible to write
fairly complex SQLs for which you need to refer some proper reference on database
management.
     Now let us try to answer the questions in Example 4.1. Following is the solution to
each question. The SQL statements is self explanatory. Try to test some more questions.
    • Which and how many countries are listed in the airlines table?
       This question needs to be split into two. First let us try to find which countries are
       listed in airlines table. If you try to list all the rows, same country will be listed
       multiple times. Therefore, we need to us UNIQUE keyword. Try the following
       SQL.
       SELECT DISTINCT(country) FROM airlines;
       You can see that one row in the result shows NULL value. Which means that some
       of values in the country column are empty. To omit NULL values in the result,
       we use IS NOT NULL as shown in following SQL.
       SELECT DISTINCT(country) FROM airlines
       WHERE country IS NOT NULL;
       You can find the number of countries listed in the airlines table by simply scrolling
       down the output of the SQL. However, there is standard SQL query for counting
       the number of results, as shown below.
       SELECT COUNT( DISTINCT(country)) FROM airlines
       WHERE country IS NOT NULL;
   • How many airports are listed for each country?
     This question is simple one. We need to use (group by) keyword to find the
     number of airports in each country as shown in the following SQL example.
     SELECT country, count(*)           FROM airports
     GROUP BY country;
   • Which routes are operated by RNA (Nepal Airlines)?
     This is question is not very hard. You can try by yourself before looking at the
82                                         Chapter 4. Database Management
     SQL below. Remember that you need to combine all the three tables as the routes
     table does not have the listing of the name of airlines or the full name of source
     and destination.
     SELECT      airlines.name, airports.city, routes.dest
     FROM routes, airlines, airports
     WHERE airlines.icao = ’RNA’ –-International Civil Aviation Organization
     (ICAO) code for airport name
     AND airlines.id = routes.airline_id
     AND airports.id = routes.source_id;
     In the above code, we introduced comment. Anything written after – is treated as
     comment and will not be executed. We get following table as output by executing
     the above SQL.
     This table does not show the destination. If you replace airports.id = routes.source_id
     by airports.id = routes.dest_id then you will get only the name of destination city.
     Therefore, you need to join two different selection statements as below. We create
     two selections. The first selection statement compares the id of table airports
     with source_id of routes table. In the second statement we compare the id of
     airports table with dest_id of routes table. The two tables are named as t1 and
     t2 respectively. Finally we compare the outputs of two selection statements by
     using common column which is index column of routes table. Here we need
     to remember that some words such as index are reserved words for SQLite and
     should be written inside double quote.
     SELECT t1.name, t1.city AS from_city, t2.city AS to_city
     FROM
     (SELECT      routes."index", airlines.name, airports.city, routes.dest
     FROM routes, airlines, airports
     WHERE airlines.icao = ’RNA’              –- ICAO code for airport name
     AND airlines.id = routes.airline_id
4.3 Using Selection Statements in Database Management                                83
LEFT JOIN
          Observe the information contents of each table again and think about what further
      information you can get from these tables. You need to practice writing SQL to improve
      your understanding of SQL.
            Above SQL creates a new database. After executing the SQL, if the daily_flights
        table does not appear in the list then click on the Refresh tool in DB Manager window.
        Select Info tab on the right pane. You will see the information about the table as
        follows.
                                                                                            
         After creating a table, we need to fill it. New rows are add by using INSERT
      keyword. Practice the following exercise.
4.4 Creating and editing table in a database                                        85
       Write the following SQL statements in the SQL window and execute one by one.
       Remember that time column needs to be written as HH:MM or HH:MM:SS.
       INSERT INTO daily_flights
       (departure, arrival, price, route_id)
       VALUES (’09:30’, ’13:30’, 313.55, 4078);
       INSERT INTO daily_flights
       (departure, arrival, price, route_id)
       VALUES (’21:30’, ’01:30’, 400.0, 10418);
       INSERT INTO daily_flights
       (departure, arrival, price, route_id)
       VALUES (’12:15’, ’16:15’, 425.70, 4078);
       INSERT INTO daily_flights
       (departure, arrival, price, route_id)
       VALUES (’12:45’, ’17:30’, 290.00, 17582);
       INSERT INTO daily_flights
       (departure, arrival, price, route_id)
       VALUES (’18:10’, ’23:00’, 600.00, 10418);
       INSERT INTO daily_flights
       (departure, arrival, price, route_id)
       VALUES (’19:30’, ’23:40’, 520.00, 24160);
       INSERT INTO daily_flights
       (departure, arrival, price, route_id)
       VALUES (’04:30’, ’07:50’, 250.0, 44970);
                Now observe the contents in the table by selecting table tab in the right pane
                of the DB Manager window.
             3. Update table
                Now let us try to find the duration of each flight. Add duration column to the
                table as follows.
                ALTER TABLE daily_flights ADD COLUMN duration REAL;
                In the newly created column let us try to enter the value of duration. When the
                new column is created, all the values are filled by NULL. To change any value
                in a column we need to use UPDATE keyword. To do mathematical operation
                with time column we need to use a function called julianday. Try the following
                SQL to update duration column.
                Following syntax is used to update column(s) of table.
                UPDATE [Table name] SET [[Column = value],[Column=value]. . . ] WHERE
                [Where clause]
                UPDATE daily_flights SET duration=round((julianday(arrival) -
                julianday(departure))*24.0,2);
                Try to use the above SQL without round function. You can also create another
                column and fill it with price in different currency.
                                                                                              
LEFT JOIN
        Rules of DBMS
        There are some rules of DBMS which needs to be considered while managing database.
          1. Each column in a table must be unique. No two columns should have same name.
             2. Order of columns does not matter.
             3. Order of rows does not matter.
             4. Each column (field) should have same type of data (text, integer, double, timestamp
                etc). We cannot put text and integer data in the same column. Once we create
                table, all the column types are also defined. Whatever data we keep in the column,
                it will be either treated as defined type or it will raise error. For example, if we
4.6 Summary of database management system                                                 91
      insert real (decimal) data in a text column, the data will be treated as text. If we try
      to insert text data into a integer column, the DBMS will not accept such operation.
   5. Each table should have a primary key. It is suggestion rather than rule. There
      should be at least one column which should have only unique values. We can
      define a column to accept unique values by adding primary key to the definition.
      Such as :
      Create Table abc
      fid integer primary key,
      name text,
      ...
      In the above table, fid column will not accept repeated values.
   6. Tables are related to each other.
      As we saw in the flights database we used in the exercises, routes table is related
      to both airlines and airports table. As the tables are related to each other, it is
      also called relational database. Similarly, DBMS is sometimes called RDBMS.
      Main purpose of GIS is to display the features on earth in an understandable way and
      to make it possible to analyze the location based data. First of all we need to represent
      features on the earth in the form which computer can understand. As we practiced in
      first two chapters, we know that features on the earth can be represented as vector data
      and raster data. In this chapter, we will talk about vector data in some more details.
      In chapter 2 we learned that vector data are mainly of three types. They are
         1. Point: Features on the earth such as airports, buildings, trees, sports stadium can
            be represented in the form of points.
            Points are stored in GIS in the form of a pair of x and y coordinates.
         2. Line (or polyline): Linear features such as road, river, electric power line, water
            supply pipe lines, contour lines etc can be represented as lines.
            Polylines are stored as list of points which form the line.
         3. Polygon: Enclosed areas such as political boundaries, lakes and ponds, land use
            boundaries etc are represented as polygon geometry.
            Polygons, same as polylines, are also stored as a list of points with last point
            coinciding with the first one.
          There is no fixed rules regarding what features should be represented by which type
      of geometry. Sometimes we need to show the details of roads, buildings and rivers. In
      such cases, these features are represented as polygons.
        94                                             Chapter 5. Working with Vector Data
              Let us have a look at some of these file based vector data formats.
             1. ESRI shapefiles: This is one of the most used vector data formats. Every single
                single shapefile consists of at least three files with the same name and different
                extensions (viz. shp, shx and dbf). Files with extensions shp and shx stores the
                location information of all the features of vector data. Files with dbf extension
                consists of the attribute data which can be opened with MS Excel or any spread-
                sheet software such as Libreoffice Calc etc. Each shapefile consists of single type
                of vector data. That is, you can not have multiple types of geometry in a single
                shapefile.
             2. Geopackage: A GeoPackage is an open, standards-based, platform-independent,
                portable, self-describing, compact format for transferring geospatial informa-
        5.2 Vector GIS Data Formats                                                             95
              tion. The GeoPackage standard describes a set of conventions for storing the
              following within a SQLite database: vector features. (source: https://www.
              opengeospatial.org/standards/geopackage).
           3. Spatialite: SQLite is a file based relational database management system. Spatialite
              is a spatial extension to SQLite. In the last chapter we covered spatialite in detail.
              One single database should be used for one project.
           4. Comma seperated value: You can create a text file and enter attributes and x,y
              coordinates separated by comma as shown below.
              place, country, latitude, longitude
              Eiffel tower, France, 48.8584, 2.2945
              Taj Mahal, India, 27.1750, 78.0422
              Pashupati Nath, Nepal, 27.7105, 85.3487
           5. Keyhole markup language (kml or kmz): kml is an xml based format developed
              by google and used by google earth. It is similar to html with user defined tags.
              You can try drawing points, lines and polygons in google earth. After drawing
              these shapes you can save it as kml. As such, one single kml file can have multiple
              vector data types (viz. point, line and polygons).
           6. GPS eXchange format (gpx): GPX, or GPS Exchange Format, is an XML schema
              designed as a common GPS data format for software applications. It can be used
              to describe waypoints, tracks, and routes. The format is open and can be used
              without the need to pay license fees. Location data (and optionally elevation, time,
              and other information) is stored in tags and can be interchanged between GPS
              devices and software (source: wikipedia). Recently, most of the smart phones
              have GNSS (Global navigation satellite system) chips which gives location of the
              device by communicating to the navigation satellites. Many smart phone apps
              record location data in gpx format. We will talk in detail about GNSS in next
              chapter.
  5. Quality: Quality of GIS data refers to accuracy. While selecting a GIS data, we
     need to take account of different types of errors. It is not possible to get perfect
     data by any means. Let us discuss about the different kinds of accuracy and error
     in GIS data.
        • Positional accuracy: Positional accuracy is related to the error in the geometry.
           It is impossible to determine the exact position of any point. However, it
           is possible to talk about the level of precision. For example, engineering
           surveys using high precision equipment may provide an accuracy in the range
           of millimeters while accuracy of data collected by smart phone GNSS can be
           in the range of tens of meters. Acceptable level of precision depends upon
           the purpose. If we want to do reconnaissance survey of location of landslides
           along a road corridor, level of accuracy provided by GNSS based survey
           can be acceptable and most economic and fast. But if we want to map the
           land property boundary, we will need accuracy in the range of few tens of
98                                     Chapter 5. Working with Vector Data
       centimeters.
     • Attribute accuracy: GIS data always consists of attribute data. An attribute
       data especially quantitative data may not be always correct. Different means
       are used to collect attribute data. Let us suppose that we have to find number
       of buildings in different wards of a municipality. If we have high resolution
       imagery (e.g. aerial photograph), we can easily count exact number of
       buildings. However, if we want to do household economic survey, it will be
       very difficult to get exact data due to different but obvious reasons. In this
       case also, acceptable accuracy of attribute data depends upon the purpose of
       analysis.
     • Temporal accuracy: Temporal accuracy refers to whether a GIS data is
       accurate for the time it is being considered. For example, a data gathered 10
       years ago cannot be correct at present. Therefore, we should check the time
       of the data collection and its utility for the purpose.
     • Logical consistency: Some GIS data are not logically consistent. Logical con-
       sistency generally applies to the adjacent features of a vector data. The Seven
       Bridges of Königsberg written by Leonhard Euler in 1736 is a historically
       notable problem in mathematics which laid the foundations of graph theory
       and prefigured the idea of topology.(See https://www.esri.com/news/
       arcuser/0401/topo.html and https://en.wikipedia.org/wiki/Seven_
       Bridges_of_K%C3%B6nigsberg).
       GIS provides some tools for checking and repairing logical inconsistency.
       However, for some of logical inconsistencies, it will be necessary to find
       some work around. Following examples elaborate the meaning of logical
       consistency.
         a. Boundaries of two adjacent districts overlap or have gaps. This type
            of error occur when the GIS data is created by digitizing (as explained
            later).
         b. Same boundary is traced multiple times while digitizing.
         c. Sometimes two separate adjacent polygons having gaps or overlap are
            merged together to form a single feature. Small polygons appear where
            there at the gaps. These polygons are called silver polygons.
         d. When manually digitizing contour lines, error may accrue as a result of
            overlapping contour lines.
         e. Intersecting lines, in some cases, may be inconsistent. For example, if
            a road network does not have any overpasses, then there should not be
            any line feature crossing other line. They should meet at some vertices.
     • Data completeness: While doing a GIS project, we need to gather data from
       various sources. We need to check whether the data covers whole of the
       geographical area of the project and whether all the attributes needed for our
        5.4 Sources of vector data                                                                99
purpose is available.
              These data and their can be searched through their websites or by visiting the
              concerned organizations.
    For using an excel file as data layer for QGIS, the excel file should be properly
formatted. We will format the excel file properly before adding to QGIS as data layer.
    There are two ways to use the excel file to create vector layer:
   1. Add excel file to the QGIS Layers panel and create vector data using SQL.
   2. Save excel file as CSV and add to QGIS as delimited text layer.
    Each of the above methods will be explained in the following examples.
  Exercise 5.1 Method-I: Add excel as data layer and create vector data
     In this exercise we will use the excel file directly. Follow the steps below.
  Step-I. Edit the excel file.
        1. Open the excel file with MS Excel or LibreOffice Calc or any other spread-
           sheet software.
        2. Create one more sheet which will be named as Sheet3 by default.
        3. Copy only the data rows from the first sheet to the newly created sheet.
           Keep the first row empty, that is, paste the data to the second row.
        4. Add headings in the first row. Your new sheet should look like as shown in
           the Figure .
            SELECT      *,
            makepoint(
            (floor(long * 0.01) +
             (long*0.01 - floor(long*0.01)) * 5.0/3) ,
            (floor(lat * 0.01) + (lat*0.01 - floor(lat*0.01)) * 5.0/3)
            , 4326
            ) AS geom
             FROM "metStations Sheet3";
            Note that the latitude and longitude in the excel file are written as degree
            and minute without any separator. As such, we need a bit complex formula
            to convert them in to decimal degrees.
        4. Load the output of the SQL as vector layer (see figure).
        5. You can add the vector data of national or state boundary of Nepal. Change
           the symbol based on station type etc to make it more presentable as shown
           in Figure 5.2.
                                                                                        
   After categorizing the metStations layer and applying proper symbols, the image is
produced in layout manager as follows.
Concept of Georeferencing
First order polynomial transformation is used to align a non-georeferenced image. Let us
suppose that a point in pixel coordinate is represented by P(x, y) and the same point in
the geographic coordinate is represented by (x0 , y0 ). Then the following two equations
will be used to transform pixel coordinates to geographic coordinates.
x0 = Ax + By +C (5.1)
and
y0 = Dx + Ey + F (5.2)
    QGIS has georeferencing plugin pre-installed and available under Raster menu. If
you cannot find the sub-menu for georeferencing, you can display it by following the
steps below.
    • Select menu Plugins ⇒ Manage and Install plugins.
    • In search box, type georeference.
    • While typing in the search box, you will see the list of matching plugins. Check
       the box for Georeferecer GDAL.
       Now, the Georeferecer menu appears under Raster menu.
    Now, let us try to practice georeferencing. As we explained earlier, we need to know
the geographic locations of three points. We can see that image we have downloaded has
grid lines as well as coordinate values written over it. In such cases, it is possible to find
the coordinates of various locaions easily. However, sometimes, we cannot find labeled
images. In such cases, we need to find some vector data with known coordinates and
match the locations visually. We will practice both of these methods in the following
exercises.
  Exercise 5.3 Georeferencing by visual matching
      For this exercise we need vector data for matching. There are various sources
  of GIS data. However, for this exercise, we will download vector data from Open-
  StreetMap. We will match this vector data with the image as explained in the following
  steps.
   Step-I. Download osmdownloader plugin.
         Osmdownloader can be downloaded as follows (You will need internet connec-
         tion to accomplish this task):
            • Select menu Plugins ⇒ Manage and Install plugins.
            • In search box, type osmdownloader.
            • While typing in the search box, you will see the list of matching plugins.
              Select OSMdownloader and click Install button on the bottom right
              corner of the dialog.
              Now, an icon with a rectangle and an arrow will appear in the toolbox.
              This is OSMDownloader tool.
 Step-II. Download osm data and display it in QGIS.
        1. If you don’t have QuickMapServices plugin installed, then install it in the
           same way as other plugins.
         2. Select menu Web ⇒ QuickMapServices⇒ OSM ⇒ OSM Standard. A world
            map will appear in the map canvas.
         3. Zoom the map to the area of Kathmandu.
         4. Click OSM Downloader tool and draw a rectangular area around Kathmandu
            valley. The extent of the rectangle will appear in a new dialog (see figure
5.5 Deriving GIS data from text documents and images                              107
below).
       9. Zoom the image in Georeferencer interface around Singh Durbar. Once you
          find the matching location in both the interface, follow the steps below (see
          figure):
           transformation type to use depends upon the type of image. In some cases
           we may need to choose other types of transformation. We will not go into
           detail about each transformation type.
       11. To set the transformation type, use Georeferencer menu Settings ⇒ Trans-
           formation settings. Set the parameters as follows:
             • Transformation type Polynomial1
             • Resampling method       Nearest neighbour
             • Target SRS EPSG:4326
               Other parameters can be left as default.
             • Click OK
       12. Click Start georeferencing tool to complete the task.
                                                                                    
    In the next exercise, we will describe how to georeference an image which has known
coordinate locations. In some reports and documents, we can find well produced maps
with labels, grids and coordinates written on the map. In such cases, it is possible to
georefernce the image using coordinates printed on the frame of map. Follow the steps
in the next exercise.
  Exercise 5.4 Georeferencing from known locations
     Open the image eqKTM.jpg in any image viewer. You will see that two types of
  coordinates are printed beside the map frame as shown in following figure.
      The two coordinate values printed on the image represent two different CRSs,
  viz: UTM45N and geographic coordinates. However, horizontal and vertical grid
  lines represent UTM projection. Therefore, it is now clear that the map has used
  UTM45N for the grids. We will use UTM45N projection and the intersection of grids
  for georeferencing. The process is explained in the following steps.
        1. Open new QGIS window. We will not use any GIS data in the map canvas.
       2. Start Georeferencer.
      110                                          Chapter 5. Working with Vector Data
             5. Click Add point tool and click on one of the grid intersections. Before
              clicking the intersection point, it will be better to note down the coordinates.
             6. In the next dialog, write the coordinates directly and click OK.
             7. Repeat the above two steps for two more corners. You may use all the four
              corners.
             8. Set the transformation type and complete georeferencing as explained in the
              previous exercise.
                                                                                               
      With advent of smart phones, Global Navigation Satellite System(GNSS) has become
      part of our daily life, rather unknowingly. Check whether you have used any of the
      following features in your smart phone:
          • When you open google website, it asks for permission to access your location.
          • In the facebook, have you ever used check-in function?
          • In the google maps have you ever searched for direction to a place? Have you ever
            navigated using any of the mapping apps while walking or driving?
          • Many places are still missing in Google maps. Have you ever contributed to add a
             place you know to Google maps.
          Smart phone can know your location using the wifi you are connected to or using
      the location service provided by GNSS. The location provided by wifi is very coarse
      and its accuracy may range in few hundred meters, while smart phone GNSS provide
      10-20 meters of accuracy. This chapter describes the theory and practical applications of
      GNSS.
        United States military and became fully operational in 1995. It was allowed for civilian
        use in the 1980s. Advances in technology and new demands on the existing system have
        now led to efforts to modernize the GPS and implement the next generation of GPS
        Block IIIA satellites and Next Generation Operational Control System (OCX).
            Later, several other countries started developing and launching navigation satellites.
        Navigation satellites launched by different countries are listed below:
           1. GPS: It is owned by US government and operated by US Department of defense.
               GPS is a constellation of 32 navigation satellites some of which may be retired or
               replaced over time.
           2. GLONASS: GLONASS is abbreviation of Global’naya Navigatsionnaya Sputniko-
              vaya Sistema in Russian and is owned by Russian government. Similar to GPS,
              GLONASS also has global coverage with 24 number of satellites.
           3. Galileo: Galileo is operated by European Space Agency (ESA) and started to
              provide service after 2016.
           4. BeiDou-2: BeiDou or BDS is a navigation satellite system developed and operated
              by the government of China.
           5. NAVIC: NAVIC or NAVigation with Indian Constellation is an autonomous re-
              gional satellite navigation system developed by Indian Space Research Organisa-
              tion (ISRO) (Source: Wikipedia).
           6. QZSS: Quasi-Zenith Satellite System (QZSS) has 4 navigation satellites which
              cover Asia Pacific region. It is being developed by Japan Aerospace Exploration
              Agency (JAXA).
        Air Force Base in Colorado, Cape Canaveral, Florida, Hawaii, Ascension Island in
        the Atlantic Ocean, Diego Garcia Atoll in the Indian Ocean, and Kwajalein Island in
        the South Pacific Ocean. Similarly, Galileo has 2 Ground Control Centres, located in
        Oberpfaffenhofen and Fucino for Satellite and Mission Control. Ground stations are
        used to monitor the position and health of the satellites and also to upload the ephimeris
        and almanac data to the satellites at every fixed interval. Ground based stations can also
        upload other data to the satellite.
        or synchronize with a particular satellite using this signature. Satellites transmit signals
        all these three frequencies (Note: Some more frequencies bands may be added in the
        future). These signals contain various information related to the position of the satellite.
             An L1 signal provide following information.
             • GPS date and time.
            • Satellite status and health. When the satellite has some problem, it will transmit
              the out-of-service message.
            • Satellite ephemeris data, which allows the receiver to calculate the satellite’s
              position with extremely high accuracy. Receivers can determine the exact position
              of satellite at the time of transmission of the signal.
            • Almanac: It contains information about all the satellites in the same constellation.
R1 = c × t1 (6.1)
            Similarly, let us suppose that the next satellite gives the distance R2. Now, the
        receiver should be located somewhere on the ring where the two spheres intersect (see
        Fig. 6.1.
            Let us suppose that the third satellite makes a sphere of radius R3. Now we have
        an intersection of three spheres with radii R1, R2 and R3 as shown in Figure 6.2. Third
        6.4 Errors in computation of location                                                     117
        sphere intersects with the ring at two points. One is shown in the figure while the other
        point is just on the opposite side which is not visible. As the point should be on the earth,
        one of the points on the ring can be excluded.
        different frequency bands (L1 and L2 frequency). This can minimize the error due to the
        effect of the varying conditions of ionosphere.
            Another way to reduce the effect of atmospheric error is to use high grade receiver
        as a base station with precisely known position. The base station can provide correction
        which is almost same for any particular geographic area. The other receivers (known as
        rover) which receive only L1 frequency signal can use this correction value to correct its
        location. Details of this error and methods of corrections can be found in various links.
        Figure 6.3: Multipath problem (image of satellite and receiver created by Iconicbestiary -
        Freepik.com)
            Specially big buildings cause obstruction to the path of the signals and some satellites
        are not visible at some locations due to such obstructions. Futher, the signal is refracted
        while passing different layers of atmosphere. As such, the satellite may receive multiple
        signals: directly, reflected by obstructions and refracted by atmosphere. This causes
        some error in the computed location. This type of error is known as multipath error.
        6.5 Practical use of GNSS                                                            119
        Figure 6.4: Google Maps        Figure 6.5: Google Maps        Figure 6.6: Search the di-
        home                           features                       rection
            As shown in Figure 6.6, we can search for places and get the details of the searched
        place. We can also ask for direction to the place as shown in Figure 6.6, by tapping on
        Directions at the bottom left. Google Maps gives the shortest route and other one or two
        alternative routes 6.7. Additionally, we can contribute to the Google Maps (see Fegure
        6.8) in various ways such as:
            • Contribute photos of visited places.
            • Contribute opinions about visited places and give ratings to restaurants, temples
               and many touristic and other places.
            • Answer questions to the people who ask questions in the Google Maps.
            • Add places that are missing in the Google Maps.
            Google Maps is owned by Google, however, many people have contributed to it in
        various ways.
6.6.2   OSMTracker
        OSMTracker is freely available app which can record the track while moving. It also
        allows one to record features on the way (such as: bridges, hospitals, restaurants etc) as
        waypoints. The interface of OSMTracker is quite simple and easily comprehensible. Few
        screen-shots below illustrates the use of OSMTracker. It will be explained in more detail
        in section ??. Unlike Google Maps, it can be used offline. However, it is necessary to be
        online to download background maps of the nearby locations. Google Maps uses its own
        proprietary map as background, however, OSMTracker uses its own, freely available
        Openstreetmap background.
            Some features of OSMTracker
            • Home screen provide various self-explanatory functions through the 3-dot icon at
6.6 Mapping and navigation related apps                                        121
   Figure 6.7: Google Maps direction         Figure 6.8: Google Maps contribu-
   feature                                   tion
6.6.3   OsmAnd
        OsmAnd is freely available app which provides offline navigation. It provides map
        download facility for displaying offline maps. It is possible to add favorite places and
        record the track. Following figures show the functionality of OsmAnd. For detail, it is
        advisable to visit the website.
6.6.4   GPSTest
        Unlike above three apps, GPSTest does not provide map background. However, it
        provides very useful information regarding GNSS. Look at the following figures. Let us
        look at some of the features:
6.6 Mapping and navigation related apps                                              123
Figure 6.15:    GPSTest       Figure 6.16: Satellites and     Figure 6.17: Location of
home screen                   their SNR                       satellites in the sky
   • As in every location based apps, it needs to get a GPS fix to start showing location.
     Buttons at the bottom are toggle buttons and provide link to various informative
     interfaces. Try to use these buttons multiple times to get used to the interfaces.
   • Home screen provide the coordinates of the location (Fig. 6.15). The format of
        124                                           Chapter 6. An Introduction to GNSS
6.6.5   SW Maps
        SW Maps is also a freely available GNSS app developed by Softwel Pvt. Ltd, Nepal. It
        is heavily packed with features compatible with modern GIS. It is not possible to explain
        all the features of this app owing to the space requirement. Some of the features of this
        app is explained below. A tutorial using SW Maps in section ?? explains how we can
        use the app.
             Some features of SW Maps are listed below along with the screen-shots.
             • Home screen of the app displays the map, logo and few menus.
           • On the top left of the screen you can see the logo of app. Tapping the logo of the
             app will show different options, each providing different functions. Some of those
             functions will be addressed in the tutorial.
           • SW Maps is based on the basic concept of GIS. It can have multiple projects which
             are managed separately from each other. Each project may consist of multiple
             vector layers. The project icon is the third from the top right. Tapping on project
             icon will show project management screen.
        6.7 Working with GNSS apps                                                         125
           • Record icon right to the project icon is used to record a feature or just record a
             track. The recorded tracks or features can be exported as shapefiles.
           • Three dot icon on the top right has options to export the project or as multiple
             shapefiles (Zipped).
      • After completing your track you need to go back to previous screen and from
        the menu you need to tap stop current track.
      • You can continue the once stopped track (refer to the right figure above).
        Long-press the track in the list and tap Resume tracking in the context menu.
        Also check other options in the context menu which you can use as needed.
        Alternatively, you can tap 3-dot icon at the top right corner and then tap
        Continue track in the context menu.
      • Any or all tracks can be exported. To export individual track, you need to long
        press on the track and tap Export as GPX. The track can also be exported
6.7 Working with GNSS apps                                                           127
Now let us display the track in QGIS. Following exercise explains how to do it.
              5. We can add popular map backgrounds such as Google Maps, Bing Maps,
                 OpenStreetMap etc. Let us install plugin called QuickMapServices to display
                 background. You will need internet connection to install the plugin and also to
                 show the background layer.
              6. Go to menu Plugins ⇒ Manage and Install Plugins.
              7. A popup window will be displayed showing the list of installed and available
                 plugins in the left pane.
              8. In the search box type quic. As you go on typing, the list will show only the
                 plugins matching the search keyword. From the list select QuickMapServices.
                 You will see the explanation of the plugin and the links. Click Install Plugin
                 button on the right bottom of the dialog.
              9. Link to the plugin is available under Web menu. Select menu Web ⇒ QuickMapSer-
                 vices. Then test various map backgrounds.
                                                                                              
            The above exercise just shows how GNSS app, such as OSMTracker, can be used for
        tracking and displaying vector data. It depends upon our need to decide how to use such
        apps.
6.7.2   SW Maps
        General concept of SW Maps
        SW Maps is based on the concept of GIS and data layers. While working with SW Maps
        we work in the following order.
          1. Create project: We can create a new project from scratch or use a template. A
             template consist of a set of feature classes without any data. When we use a
             template we don’t need to do next two of the following steps.
           2. Add layers of data: We can add layers of data as required. Each layer of data can
              be point, polyline or polygon.
           3. Add attributes: It is necessary to create attributes for each layer of data.
           4. Record features: Once the layers and attributes are created we can record features
              of different classes.
            In the following exercise we will try to understand the concept and possible use of
        SW Maps. While the concept of the SW Maps will not change, the interface may change
        with version upgrade. You will need to modify the steps accordingly.
6.7 Working with GNSS apps                                                         129
        3. Tap on New Project (see figure above, left). In the new dialog write the
           name of the project as you like. In the present example, name of the project
           is Campus Survey. Tap Create button (see figure above right).
 Step-II. Add layers
        In this step, we will add three layers with three different geometries (point, line,
        polygon) to understand how each type of geometry are recorded.
        1. To show the list of projects, tap on 3-dot icon on the top-right and select
            Projects (See figure below, left). Note: You can add or delete projects using
            this screen.
        2. While your project Campus Survey is selected, tap on the layers icon
           (third from top right), as shown in figure above right.
6.7 Working with GNSS apps                                                     131
      3. Tap on the + sign beside Layers and select GPS Recorded Feature. Note:
         You can add existing vector data or raster data stored in the mobile from
         this context menu.
      4. Write the name of the layer as building, geometry as polygon. You can also
         change the symbol.
         Similarly, we can add other layers in the same way so that we have total
         three layers: Building, Road and trees, with three different geometries.
132                                            Chapter 6. An Introduction to GNSS
      4. Now we will create another field which can have only limited values. Again
         tap + beside Layer Attributes. Write bldType in the Attribute Name and
         attribute type as OPTIONS (above, right figure). A + sign appear beside
         Options. Click on the + sign to add options.
      5. Add following options:
          • Academic
          • Administrative
          • Other
      6. In the same way as explained above, add two more attributes: nfloors as
134                                         Chapter 6. An Introduction to GNSS
      4. Point features will be recorded once you tap on the icon. Therefore, you
         need to be careful to fill all the attribute values before recording the feature.
      5. In case of line or polygon, you need to tap STOP icon to end recording the
         feature.
      6. When you record a new line or polygon feature, check whether the radio but-
         tons New or Existing is checked. If Existing is checked then the recording
         will continue for existing feature.
      7. After recording a feature, use back button to go to previous screen. It
         will show you recorded features (see left figure below). When you click a
         feature, it will show you details of that feature and options to delete or edit
         (right figure, below).
136                                           Chapter 6. An Introduction to GNSS
         8. After finish the recording of features, the project can be exported to the
            storage. Alternatively, the project can be directly uploaded to a ftp. You can
            create a ftp in your PC and upload it directly to PC using upload feature.
            Long press logo icon and tap on the Export menu. Check the items you
            want to export. For this exercise, export only 2D shapefiles including photos.
            The exported file resides inside SW_Maps/Exports as zip file.
         9. Transfer the zip file to your PC and display in QGIS as explained in the
            next exercise.
                                                                                        
     There are several things we can do with SW Maps. SW Maps supports external GPS
device connected through bluetooth or OTG cable. You can also create a template from
your project which can be shared to others. Templates can be used where same features
are to be recorded by different users. By using template, creation of same feature classes
and attributes in multiple devices can be avoided. This can be used in a multi-user project
such as economic survey, building damage survey after an earthquake etc. It is suggested
to try all the capabilities of SW Maps and take full advantages of these functionalities.
     Now let us try to display these shapefiles exported from SW Maps in QGIS. We
have already displayed GIS data in map canvas and also created layouts in the previous
chapters. In the present exercise we will show how we can create a report from the data
exported from SW Maps.
  Exercise 6.4 Part-2: Display shapefiles and create report in QGIS
       Following steps will show you how to create a new project with all the layers and
  attributes.
        1. Unzip the exported data inside, for example, D:\GIS_exercise\Exercise_
6.7 Working with GNSS apps                                                      137
      06_GNSS.
     2. Add building and road layer to the map canvas. Symbolize them properly.
     3. From menu click Project ⇒ New Report. New report window will open.
     4. Click + sign below Report Organizer and select Static layout section.
      6. Let us add title section (Static layout section) for Road feature class as shown
       in the figure below.
      7. Now let us add Field group section. By adding a Field group section, we
       are adding multiple pages to the report. The number of pages is equal to the
       number of features in the feature class. Follow the steps below to complete
       adding road features. Refer the figure below.
            ’D:/GIS_exercise/Exercise_06_GNSS/CampusSurvey’ + replace(
            "photo1", ’\\’, ’/’).
140                                  Chapter 6. An Introduction to GNSS
      k. Then add the map canvas with map elements. We need to set the map
         scale to fixed so that the surrounding area is clearly visible.
6.7 Working with GNSS apps   141
                              
                 Bibliography