Thursday, 24 December 2015

Tracking the path of a mobile object using the HTML Geolocation API : Part 1

Knowing the goegraphical position of a stationary object or tracking the path of a mobile one can find enormous applications in Civil Engineering, particularly in fields like Traffic Engineering, Transport Planning, Advanced Surveying, etc. For example, tracking the path of a large set of moving vehicles in a city/town may help a traffic engineer in analysing the traffic patterns of the region and in  identifying the most busy roads of the city/town. Similarly, surveyors can use the geographical coordinates of the points at the boundary of a large region to find the enclosed area.

The applications are many, but if manual methods (and not digital ones) are used to complete these objectives, it may turn out to be extremely tedious and time-taking. In the present article, we will see how to track the position of a point, a stationary object or a mobile one using the HTML5 Geolocation API (Application Program Interface) with the basics of web development. The article has been divided into two parts. In the first part (current one), we will see what is Geolocation, how it works, and how to get your geograhical coordinates with the API and display it in a map. In the forthcoming discussion, i would recommend you to learn basic HTML for a better understanding of the topic, though i have tried to explain the building of the source code and its execution in great detail.

Knowing the geographical position of any object in the world primarily consists of knowing two major attributes associated with it: the lattitude and the longitude (and sometimes altitude as well). HTML5 Geolocation API helps in getting these position attributes (and more), associated with it's user. One simply needs to incorporate the API in one's website or app in order to get those attributes. This task is accomplished in two steps. The first step involves getting the geolocation of the target user as input, which is done with the help of basic HTML5 and Javascript. The second step involves transferring this data to the owner (or tracker) and display the data as part of map (using the Google Map API).

First of all, you would need a text-editor in order to write the code. Open Notepad++ in your computer. If you don't have Notepad++, you can also use other text-editors like Sublime or Windows' built-in text-editor Notepad. However, i would encourage you to avoid notepad and install Notepad++ (to download, click here). After opening the text-editor, start with the following code:

<!DOCTYPE html>
<html>
<body>

<p>Click the button to get your global position coordinates.</p>

<button onclick="getLocation()">Get your position</button>

<p id="demo"></p>

<div id="mapholder"></div>

<script>
var x = document.getElementById("demo");

function getLocation() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(showPosition);
    } else {
        x.innerHTML = "Geolocation is not supported by this browser.";
    }
}

function showPosition(position) {
    var latlon = position.coords.latitude + "," + position.coords.longitude;

    var img_url = "http://maps.googleapis.com/maps/api/staticmap?center="
    +latlon+"&zoom=14&size=400x300&sensor=false";
    document.getElementById("mapholder").innerHTML = "<img src='"+img_url+"'>";
 x.innerHTML = "Latitude: " + position.coords.latitude +
    "<br>Longitude: " + position.coords.longitude +  "<br>accuracy: " + position.coords.accuracy;
}


function showError(error) {
    switch(error.code) {
        case error.PERMISSION_DENIED:
            x.innerHTML = "User denied the request for Geolocation."
            break;
        case error.POSITION_UNAVAILABLE:
            x.innerHTML = "Location information is unavailable."
            break;
        case error.TIMEOUT:
            x.innerHTML = "The request to get user location timed out."
            break;
        case error.UNKNOWN_ERROR:
            x.innerHTML = "An unknown error occurred."
            break;
    }
}

</script>

</body>
</html>


 Quick Explanation

Before proceeding further, it is important to mention that the Geolocation API is not compatible with all the browsers, though it works well with Chrome 5.0 and above, IE 9 and above, and Firefox 3.5 above. The code above verifies if your browser supports Geolocation, if yes, then the getCurrentPosition function is used to record your position, which is then displayed in the "demo" division of the web page and if not, "Geolocation is not supported by this browser" is returned as output. The next part of the code displays the coordinates of your position in a map, held by the "mapholder" division of the webpage; in case in any errors occur in the above task, it is displayed as handled by the error handler in the last part of the this code.

Get your hands dirty by running the above code yourself; simply, copy the above code in notepad++ and save the file with .html extension (and file type as All files) and then open the saved file with your browser.
 
The above code detects the position of the user and displays it using the Google Map API in the same page the user visits. Thus, it helps the user in identifying his own position, and does no use to the surveyor or the owner of the web page.

Two Important Functions
The getCurrentPosition function gets the target's (preferably a stationary target) position only for one single time. It takes two arguments in the form of callbacks: one for a success position query and the other for a failure position query. The position object has the following properties:

Property                        Value               Unit                     
coords.latitudedoubledegrees
coords.longitudedoubledegrees
coords.altitudedouble or nullmeters
coords.accuracydoublemeters
coords.altitudeAccuracydouble or nullmeters
coords.headingdouble or nulldegrees clockwise
coords.speeddouble or nullmeters/second

The getCurrentPosition function is primarily for getting the position of a stationary object. Another function called the watchPosition returns constantly updated position attributes for a moving object.
To read the full documentation of the HTML5 Geolocation API, click here.
In the above code, getCurrentPosition has been used to return the values of three primary position object properties: lattitude, longitude and the accuracy.

Speaking of accuracy, it's value can largely vary with the type of device used for running the API code. Now, different devices have different degrees of accuracy. A cell phone that has a GPS unit inside of it that is switched on is usually accurate within thirty meters. A cell phone without a GPS unit, with the GPS unit switched off to maximize battery, or at a location where the GPS can’t contact the GPS satellites will have to use cell tower triangulation to estimate the users location and is typically accurate within 3000 meters which is almost completely useless for our purposes.
For our purpose, it is highly recommended that you use a phone with "GPS On" in order to get the most accurate tracking results of the moving object. What i mean to say is that, after the coding is done, and the web page is uploaded in a server(it has to be, so that the web page can be accessed from any device and not just your laptop), it should be accessed with a "GPS On" device for good results.

In this part of the article, we have seen what is Geolocation, how it works, and how to get your geograhical coordinates with the API and display it in a map. We will see the remaining portion in the second part of the article.

Did this article help you? Comment below and follow my blog for the second part...





Tuesday, 22 December 2015

How to plot the DEM (Digital Elevation Model) of any region in Matlab

GIS and Remote Sensing is the part and parcel of Civil Engineering. Water resources engineering, hydrology, advanced surveying, etc. are some of the branches of civil engineering which make extensive use of GIS technology. A majorly used data for the study associated with these branches is the DEM (Digital Elevation Model) or DSM (Digital Surface Model) data. In the present article, we will see what is DEM and how we can plot DEM data in Matlab. I have illustrated the plotting of a sample location of the Badrinath City in Uttarakhand, India for a better understanding.


Google earth image of the area, whose DEM data plotting in Matlab is illustrated. 

A digital elevation model data comprises of elevations of a desired set of geographical points. There are various sources to extract the DEM data of a region. One of the most widely used digital elevation models is given by the SRTM (Shuttle Radar Topography Mission), an international project to acquire radar data, used to create the first near-global set of land elevations. It is available for free at the famous United States Geological Survey's EarthExplorer website: http://earthexplorer.usgs.gov/. The website provides various versions of the data including the SRTM Non-Void Filled,  SRTM Void Filled, SRTM 1 Arc-Second Global types of dataset available for download in the DTED, BIL and GeoTIFF file formats. Click here to know about each type of available SRTM dataset in detail.

I recommend downloading the SRTM 1 Arc-Second Global dataset in the GeoTIFF format for general and research studies.This type of DEM data offers worldwide coverage of void filled data at a resolution of 1 arc-second (30 meters). This means that the dataset is freely available for any region world-wide at a spatial resolution of 30m. The GeoTIFF format means that the DEM data is in raster (TIFF format) format with embedded geographic information i.e. the dem itself is a 3d plot, with x-y plane representing the geographical coordinates and z-axis representing the associated elevation value of the coordinate. In simpler terms, it is a normal b&w (might vary with type of view) image with packed elevation and geographical coordinates information.

Figure 1: Screenshot of the US Government Geological Survey's Earthexplorer website, captured while selecting the coordinates-bound region whose DEM data is to be downloaded
The dem data after being downloaded can then be viewed in any picture viewer as a raster image or can be opened with a GIS software like the ArcGIS, QGIS, Microdem, etc. You can also crop the raster data in order to restrict it only to your needed set of coordinates using these softwares or process it according to your need. As already said, the downloaded data is in raster format, so to plot it in Matlab, we need to convert it into ASCII (basically, text format) format. This can be easily achieved using the built in "From raster" conversion tool of ArcGIS software, which gives you an option to convert the raster dem file that you have opened in ArcGIS into ASCII format and export it as a text file.


Figure 2: A sample SRTM DEM data of a region in Uttarakhand, India, showing a b&w image.The brightest regions depict the highest elevation values and the darkest regions depict the lowest elevation values.
Figure 3: The raster SRTM DEM data shown in figure 2, cropped to the desired coordinates-bound (bounded by 79029’24’’ E- 79029’42’’E Latitude and 30044’42’’N - 30044’24’’N Longitude) region in ArcGIS
The dem data in ASCII format is basically a text file consisting of an array of elevation values for the respective geographical coordinates of the given area. The range of geographical coordinates(lattitudes and longitudes) depends on the coordinates of the edges of the desired region to be plotted (for example, in the present case(fig. 3) it is 79.49003 to 79.4950 degrees E Lattitudes and 30.74003 to 30.7450 N Longitudes). Now, as the spatial resolution of the data is 1 second, i.e. 1/3600 degrees, take the least count of the coordinates as 1/3600 degrees. The ASCII dem text file is opened in notepad to get the elevation values corresponding to the respective coordinates.

Finally, the code to be written in Matlab is shown below:

X= 79.49003:1/3600:79.4950;
Y= 30.74003:1/3600:30.7450;
Z= [
 3126 3119 3112 3106 3097 3092 3093 3100 3104 3106 3106 3109 3114 3119 3123 3126 3128 3128;
 3123 3116 3111 3105 3096 3089 3093 3099 3106 3108 3108 3110 3116 3120 3123 3126 3128 3129;
 3124 3115 3108 3103 3093 3087 3091 3099 3106 3109 3109 3113 3117 3121 3126 3128 3129 3129;
 3123 3114 3105 3097 3088 3086 3093 3100 3109 3112 3114 3116 3119 3123 3127 3128 3128 3128;
 3119 3112 3102 3091 3084 3086 3095 3102 3109 3115 3116 3118 3121 3124 3127 3127 3126 3126;
 3112 3106 3100 3092 3086 3091 3096 3103 3110 3115 3118 3120 3123 3125 3125 3124 3124 3126;
 3107 3103 3099 3094 3092 3093 3098 3105 3113 3117 3120 3124 3125 3125 3124 3123 3124 3128;
 3108 3103 3098 3093 3091 3091 3098 3105 3113 3118 3122 3124 3125 3124 3124 3125 3126 3129;
 3109 3101 3095 3092 3084 3086 3094 3101 3110 3117 3121 3123 3123 3123 3125 3127 3128 3127;
 3112 3100 3095 3091 3083 3080 3088 3095 3102 3111 3116 3119 3119 3121 3123 3127 3126 3124;
 3117 3103 3095 3089 3081 3079 3083 3089 3095 3102 3107 3115 3117 3119 3121 3123 3124 3123;
 3114 3104 3096 3090 3083 3079 3081 3085 3089 3093 3099 3107 3112 3117 3118 3120 3121 3122;
 3111 3107 3099 3094 3088 3084 3082 3084 3083 3086 3092 3099 3105 3110 3115 3116 3119 3121;
 3107 3104 3097 3095 3092 3089 3088 3082 3081 3084 3088 3095 3101 3104 3109 3114 3118 3120;
 3102 3098 3095 3096 3095 3092 3089 3081 3079 3082 3085 3091 3097 3102 3107 3111 3113 3115;
 3107 3101 3098 3100 3100 3095 3089 3082 3079 3080 3084 3086 3092 3099 3103 3106 3108 3110;
 3115 3110 3108 3106 3103 3095 3089 3083 3078 3079 3082 3086 3092 3098 3101 3106 3110 3109;
 3114 3112 3111 3108 3105 3099 3092 3084 3078 3077 3081 3086 3093 3096 3102 3108 3112 3112;];

surf(X,Y,Z);
xlabel('EAST(Decimal Deg.)');
ylabel('NORTH(Decimal Deg.)');
zlabel('Elevation(m)');
axis tight
colorbar

The 2d matrix Z represents the set of elevations( in meters), copied from the dem ASCII text file, whereas the row-matrices X and Y represent the coordinate axes for the given region. Note the dimensions of the row matrices X (18, here) and Y (18, here), and that of Z (18*18, here).

Figure 4: Screenshot of the above code being run in Matlab to plot the SRTM DEM

The code is run in Matlab, and the extracted plot can then be exported and saved as a jpeg image, as shown in Figure 5.



Figure 5: Final 3-D plot of the SRTM DEM data of the desired region in Matlab, with the X-Y plane showing the geographical coordinates of a point in the region, and the Z-axis showing the elevation of the respective point.


From the SRTM Digital elevation data that was extracted for the region of interest, it is evident that the selected region consists of undulating topography. As we have seen, the downloaded SRTM DEM data consists of elevations of square grid cells of 30m x 30m size (30m spatial resolution). This makes it difficult to visualise the slope of points in the study area, within each  cell. This problem, as we can see, has been very well solved by Matlab; and inspite of resolution as low as 30m and the region being as small as 0.3 sq. km, we can clearly picturise the topography of the region and use this plot for further estimations. 

Did this article help you? Comment Below