GEOGRAPHICAL INFORMATION ON THE WEB Geographical Web Aplication

GEOGRAPHICAL INFORMATION ON THE WEB Geographical Web Aplication Launch in T-minus 4!

What is javascript • Allows to build more interavtive web-pages • It is interpreted by the browser • Runs at client side (less load for the server) • Jacascript code inside the HTML code of the page • A powerful tool combined with HTML 5 to build applications that run on a browser • Syntax has similarities with java and C (but not too much)

Javascript • Javascript can control html content <html> <p id="demo"></p> </html> <script> var y = "hello world"; document. get. Element. By. Id("demo"). inner. HTML = y; </script> inner. HTML method sets HTML content to an element. In this case, the paragraph id demo is ‘filling’ with the y variable (hello world)

Javascript • Basic Data Types // Integer var x = 10; // Decimal var y = 3. 14; // String var s = "Hello World"; // Arrays of anything var z = ["Monday", "Friday", "Saturday", "Sunday"]; // JSON (useful object data structure) var u = { 'day 1': {"name": "Monday" , "description": "First day of week"} }

Javascript • Associative Array // Associative Array var my. Array = {key 1: "value 1", key 2: "value 2"}; // 2 differents ways to get a value var pointer = my. Array['key 2']; // object[string] var pointer 2 = my. Array. key 1; // object. key // Same goes in assignment my. Array['key 3'] = "value 3"; my. Array. key 4 = "value 4";

Javascript • Operation //Numbers var x = 5, y = 4. 5; // Arithmetic operations var z = x+y; z = x–y; z = x/y; z = x*y; z = x%y; //Strings var s = "not a number "; var p = "Im "; //Concatenation var k = p + s; // “Im not a number ” //Mixed Concatenation var mixed = k + x; // “Im not a number 5”

Javascript • if / else statement if(x == y) {. . . } //Condition is true else {. . . } //Condition is false // Variables can be Na. N (Not a Number) typical conversion problem between text and number, It happens a lot!!!! if(!is. Na. N(x)){. . . } • while statement --ok its just what are you thinking… • for statement for(var i=0; i<10; i++){ my. Array[i] // remember in Associative Arrays, keys are strings. . }

Javascript Associative Arrays have a different for implementation This saved my life a lot of times… for(var key in my. Array){ if(my. Array. has. Own. Property(key)){ // do something with my. Array[key] } }

Javascript Functions function sum(x, y){ return x+y; } var z = sum(4, 5); mysum = sum; //pointer to sum function mysum(z, sum(mysum(4, 5))); // its not illegal! = function(x, y){ return x+y+x; }; // yes, we ruin the sum function // A function name its just a variable which points to a function.

Javascript • Callbacks • Callback are functions associated to specific states of others functions (i. e. errors, success, etc) function plotdata(data){ /* code to plot */ } function showerror(msg){ /*code to show error*/ } function checkdata(data, callback, error){ if(. . . ) { //verifying data is OK callback(data); }else{ error("Please fix your data"); } } var dataset = [0, 2, 4, 2, 6, 74, 3, 5, 7, 4, 3]; checkdata(dataset, plotdata, showerror); Note that you can pass functions as parameters in Javascript. In this case, parameters callback and error are functions!

Example 1 basic interactivity Getting the element of the document • <script> Shows what is written in the text field when button is pressed function kk(){ n = document. get. Element. By. Id('name'). value; document. get. Element. By. Id('hola'). inner. HTML= "Hello "+n; } Changing its </script> value <body> <h 2> Type in your name and then press the button <input type="text" value="" id="name"/> <input type="button" value="click" On. Click="kk()"/> </h 2> Specifying what to call when <h 1 id="hola"> hola</h 1> a click event occurs on </body> element

Example 2: recognizing which button was pressed <script> • Shows what is written in the text field when button is pressed. Specifying a function kk(i){ parameter n = document. get. Element. By. Id('name'). value; document. get. Element. By. Id('hola'). inner. HTML= "Hello "+n+", you pressed button "+i; i++; } Giving value to </script> parameter <body> <h 2> Type in your name and then press any button <input type="text" value="" id="name"/> <input type="button 1" value="Button 1" On. Click="kk(1)"/> <input type="button 2" value="Button 2" On. Click="kk(2)"/> </h 2> <h 1 id="hola"> hola</h 1> </body>

Example 3: using a canvas and interacting <canvas style="top: 0; left: 0; background-color: #580" id="can" width="500" height="250" > • Shows what is written in the text field when button is pressed </canvas> <h 1 id="hola"> hola</h 1> Specifying a canvas <script> var canvas = document. get. Element. By. Id('can'); Getting the element and its var context = canvas. get. Context('2 d'); graphic 2 D context function draw(event) { var h = document. get. Element. By. Id('hola'). inner. HTML= '('+event. page. X+', '+event. page. Y+')'; context. begin. Path(); context. arc(event. page. X, event. page. Y, 40, 0, 2*Math. PI); Drawing a circle context. stroke(); } // click, mousedown, mouseup, click, dblclick, select, keydown, beforeinput, keyup canvas. add. Event. Listener('click', draw, false); Adding a listener </script>

Example 4: painting with the mouse (1) <canvas style="top: 0; left: 0; background-color: #580" id="can" width="500" height="250" > • Shows what is written in the text field when button is pressed </canvas> <h 1 id="hola"> hola</h 1> <button id="clean" type="button" onclick="callback. Clean()">clean</button> <script> var canvas = document. get. Element. By. Id('can'); var context = canvas. get. Context('2 d'); var que = 'no painting'; Where I am now var myx = 0; Cleaning the var myy = 0; canvas function callback. Clean() { context. clear. Rect(0, 0, context. canvas. width, context. canvas. height); } function iniciar(event) { myx = event. page. X; Mousedown detected: myy = event. page. Y; Preparing data to paint que = 'painting'; }

Example 4: painting with the mouse (2) function pintar(event) { Mouse moving • Shows what is written in the text field when button is pressed if (que == 'painting') { context. begin. Path(); Standing where I was context. move. To(myx, myy); x = event. page. X; y = event. page. Y; Asking where I am now a = 'line from ('+myx+', '+myy+') to ('+x+', '+y+')'; var h = document. get. Element. By. Id('hola'). inner. HTML= a context. line. To(x, y); context. move. To(x, y); context. stroke(); myx = x; myy = y; } Drawing a line } function finalizar(event) { que = 'no painting'; } canvas. add. Event. Listener('mousedown', iniciar, false) canvas. add. Event. Listener('mouseup', finalizar, false) Adding listeners canvas. add. Event. Listener('mousemove', pintar, false) </script>

Javascript • AJAX is a technic to update parts of a web page, without reloading the whole page. Also you can transfer small amount of data in the process. • Sends a request to an URL… and wait for states: 0: Request not initialized 1: Server connection established 2: Request received 3: Processing request If state 4 arrives, request as a status • 200: OK • 404: Page not found If status is 200, Ajax call was successful. Anything else is an error. 4: Request finished and response is ready

Javascript • Ajax • Jquery library simplify considerably Ajax calls <script src="//ajax. googleapis. com/ajax/libs/jquery/1. 1/jquery. min. js"></script> <script> $. ajax({ data: { mydata: [0, 1, 2, 3] }, //data to send in the call url: "http: //someurl. com", //destination URL type: 'post', //request method (post is recommended) success: function (response) { //callback function if status 200 achieved }, error: function (msg) { //callback function something goes wrong } }); </script>

Javascript … GO!

Geographical Data Types • Only based on latitude and longitude Vitruvius 70 BC maybe the most important architect and engineer of all times. Big roman cities were planned using his coordinate system… and yes, same guy trying to measure things using human body →
![Geographical Data Types Geometric Type Representation Point [lat, lng] Line [[lat 1, lng 1], Geographical Data Types Geometric Type Representation Point [lat, lng] Line [[lat 1, lng 1],](http://slidetodoc.com/presentation_image_h2/726847410355d23aa311ffb0d5aa4a81/image-20.jpg)
Geographical Data Types Geometric Type Representation Point [lat, lng] Line [[lat 1, lng 1], [lat 2, lng 2]] Polyline [[lat 1, lng 1], [lat 2, lng 2], [lat 3, lng 3], [lat 4, lng 4]] Polygon (Area) [[lat 1, lng 1], [lat 2, lng 2], [lat 3, lng 3], [lat 4, lng 4], [lat 1, lng 1]]

Geographical Data Types • Geographical Projections • Cylindrical • Pseudocylindrical • Azimuthal • Others…. • In web usually use Cylindrical • Specifically: Mercator (code 4326) – shapes does not distort on flat visualization. SCREEN!.

Geographical Data Types • REMEMBER : • WEB uses Mercator: 4326!!!!!

Geographical Data Types • Geographical Data Types GO!.

Web Visualization Components Google Maps Open. Layers Include Tiles (images) Use Tiles from: Google, bing, yahoo, openstreetmap or whatever you want. Even a jpg image!! Uses Mercator 4326 !!! Uses almost all popular coordinates systems Only 1 layer, visualization stack. Multiple layers and each layer has a stack visualization method. Great API, easy to use. API is just Hell.

Web Visualization Components • Example Google: Just a map <html> <script src="https: //maps. googleapis. com/maps/api/js? v=3. exp"></script> <div id="map-canvas"></div> <!-- Define properties for map-div in CSS like width, height --> </html> <script> var map; function init(){ //Initial options of the Map var map. Options = { zoom: 8, //Zoom level: 1 to 20 center: new google. maps. Lat. Lng(-34. 397, 150. 644) // MERCATOR!!!! }; map = new google. maps. Map(document. get. Element. By. Id('map-canvas'), map. Options); } //Constructs the Map on window load google. maps. event. add. Dom. Listener(window, 'load', init); </script>

Web Visualization Components Open. Layers <html> <body onload="init()"> <div id="map"></div> <!-- Define properties for map-div in CSS like width, height --> </body> </html> <script> var map, layer; function init(){ map = new Open. Layers. Map('map'); // Map Object layer = new Open. Layers. Layer. OSM("Simple OSM Map"); // Map Layer map. add. Layer(layer); // Add Layer to map. set. Center(new Open. Layers. Lon. Lat(-71. 147, 42. 472). transform( new Open. Layers. Projection("EPSG: 4326"), // Yes you must specify! map. get. Projection. Object() // yes you can have multiple projections engines ), 12 ); // Zoom Level } </script>

Web Visualization Components • Google Example: Adding a marker var marker = new google. maps. Marker({ position: , new google. maps. Lat. Lng(-25. 363882, 131. 044922) map: map, //Instance of Map Object title: 'Hello World!' // Tooltip, not info-label });

Web Visualization Components • Open. Layers Example: Adding a marker //Define a new layer for markers var markers = new Open. Layers. Layer. Markers("Markers"); map. add. Layer(markers); //Add the layer to the map //Define markers options var size = new Open. Layers. Size(21, 25); var offset = new Open. Layers. Pixel(-(size. w/2), -size. h); //Setting the marker icon var icon = new Open. Layers. Icon('http: //www. openlayers. org/dev/img/marker. png', size, offset); //Add the marker to the layer markers. add. Marker(new Open. Layers. Lon. Lat(0, 0), icon)); // USING DEFAULT PROJECTION OBJECT, MUST CHECK IF MERCATOR!!!

END • Web Visualization Components GO!. • Geographical Web Aplication Launch in T-minus 3!

DISPLAYING WEB MAPS T-minus 3!

GO no go for launch! • Displaying in Maps • Points • Lines • Polylines • Areas • Interactive Maps. • Events Handlers • Using Google web services: • Geocoding • Distance Matrix • Directions All examples in this section are from Google Maps. In order to use Open. Layers, all objects projections must be adapted.

Geographical web application • Displaying a Point as a Marker //Create a marker object var marker = new google. maps. Marker({ //Position of the marker position: new google. maps. Lat. Lng(-25. 36388, 131. 04492), map: map, //Map Object title: "marker of a point" //tooltip });

Geographical web application • Displaying a line //Array of Lat. Lng indicate the extreme points of the line var corners = [new google. maps. Lat. Lng(-29. 925626, -71. 281886), new google. maps. Lat. Lng(-29. 932767, -71. 259956)]; //Create a Polyline(Line) Object var line = new google. maps. Polyline({ path: corners, //Array of Lat. Lng map: map, //Map Object stroke. Color: "#CC 0000", //Line color stroke. Opacity: 0. 8, //Line Opacity stroke. Weight: 2 //Line width });

Geographical web application • Displaying polylines //Array of Lat. Lng indicate the extrem points of the line var corners = [new google. maps. Lat. Lng(-29. 925626, -71. 281886), new google. maps. Lat. Lng(-29. 932767, -71. 259956), new google. maps. Lat. Lng(-29. 926891, -71. 258153), new google. maps. Lat. Lng(-29. 915025, -71. 252317), new google. maps. Lat. Lng(-29. 913835, -71. 256694)]; //Create a Polyline Object var line = new google. maps. Polyline({ path: corners, //Array of Lat. Lng map: map, //Map Object stroke. Color: "#CC 0000", //Line color stroke. Opacity: 0. 8, //Line Opacity stroke. Weight: 2 //Line width });

Geographical web application • Displaying areas as polygons // Array of vertex: First point and last point must be equal! var triangle. Coords = [new google. maps. Lat. Lng(25. 774252, -80. 190262), new google. maps. Lat. Lng(18. 466465, -66. 118292), new google. maps. Lat. Lng(32. 321384, -64. 75737), new google. maps. Lat. Lng(25. 774252, -80. 190262)]; //Create a Polygon Object var polygon = new google. maps. Polygon({ path: triangle. Coords, //Array of Lat. Lng map: map, //Map Object stroke. Color: "#FFCC 00", //Line color stroke. Opacity: 0. 8, //Line Opacity stroke. Weight: 2 //Line width fill. Color: "#FFCC 00", //Fill color fill. Opacity: 0. 3 //Fill Opacity });

Geographical web application • Displaying areas as circles //Creating a Circle Object var circle = new google. maps. Circle({ //Position of the center: new google. maps. Lat. Lng(-25. 36388, 131. 04492), radius: 1000, //radius in meters map: map, //Map Object stroke. Color: "#0000 FF", //Line color stroke. Opacity: 0. 8, //Line Opacity stroke. Weight: 2 //Line width fill. Color: "#0000 FF", //Fill color fill. Opacity: 0. 3 //Fill Opacity });

Geographical web application • Interactive Maps: Adding events to maps. User Interface Events State Change Events click zoom_changed dblclick center_changed mouseup bounds_changed mousedown mouseover mouseout

Geographical web application • Interactive Maps: Example of Events Handlers. //Adding Listeners google. maps. event. add. Listener(map, 'center_changed', function() { //Function called when center changed alert("Wow!, do not move me, I will get dizzy!"); }); google. maps. event. add. Listener(marker, 'click', function() { //Function called when click marker alert("Hello my name is "+marker. get. Title()+" and I am a marker"); }); Event Handlers are functions which are called when the event happened.

Geographical web application • Example: Showing info when mouse over a marker //Info Window Object var info = new google. maps. Info. Window({ content: "Hello World!" //Content of Info. Window }); //Initiatlly Info. Window is closed google. maps. event. add. Listener(marker, 'mouseover', function(){ info. open(map, marker); //Open when mouse over }); google. maps. event. add. Listener(marker, 'mouseout', function(){ info. close(map, marker); //Close when mouse out });

Geographical web application • TIPS to manage multiple markers: • Store all your markers in a marker. Array before add them to the map. And set an id to them. • Create a function to handle events dynamically to markers. • Then from handler function you can ask for this. id and you will get the index. Same applies for polylines and polygons //Function to manage multiple markers function add. Marker(marker, txt){ //Set id according to marker. Array's length marker. id=marker. Array. length(); marker. Array. push(marker); //Add to Array //Event Handler google. maps. event. add. Listener(marker, 'click', function(){ alert("You click the marker id "+marker. id); //You can get the index }); } //Usage var mymarker = new google. maps. Marker({ position: location, //Some location map: map }); add. Marker(mymarker); //Add marker

Geographical web application • Using Google web services: • You can work with geographical Google web services via URL queries or just in Javascript Google Maps API v 3 • Main Google web services: • Geocoding: Obtaining coordinates -latitude and longitude- from an address • Distance Matrix: Obtaining time and distance to travel from a place to other • Directions: Obtaining a route based in N coordinates to travel from a place to other Directions service uses a lot of time and recourses, in order to know only the distance between 2 point use Distance Matrix instead

Geographical web application • JSON is a standard format to represent object data • It’s based on key-value pairs • Represent a valid Javascript object, that’s why JSON is widely used • General Syntax { "key 1": value 1, "key 2": value 2, "key 3": value 3, . . . } Values could be of any type: numbers, strings, booleans, arrays or even other objects with the same notation
![Geographical web application • JSON Example { "name": "Max F. ", "phone": [87322351, 2672536], Geographical web application • JSON Example { "name": "Max F. ", "phone": [87322351, 2672536],](http://slidetodoc.com/presentation_image_h2/726847410355d23aa311ffb0d5aa4a81/image-43.jpg)
Geographical web application • JSON Example { "name": "Max F. ", "phone": [87322351, 2672536], "foreign": true, "location": { "country": "United States", "city": "New York", "coordinates": { "lat": 40. 7526, "lng": -74. 2133 } } } You can read JSON data in Javascript using the predefined function JSON. parse(string)

Geographical web application • Geocoding: obtaining coordinates from addresses Using URL query: http: //maps. googleapis. com/maps/api/geocode/output? parameters output: json or xml Parameters: In Javascript use JSON because it’s easy to use and valid Javascript object address: the target address (Replace spaces to +) latlng: provide it if you want to do the inverse process sensor: true if you use a GPS to get location, false otherwise Coordinates results are in Json. Response. geometry. location. lat (or lng)

Geographical web application • Geocoding Example: Obtaining coordinates of King ST 92, Sidney, Australia http: //maps. googleapis. com/maps/api/geocode/json? address=King+ST+92+Sidney+Australia&sensor=false • JSON Result: (a lot of other information also is received) { "results" : [ { "address_components" : [ { "long_name" : "King Street Wharf", "short_name" : "King Street Wharf", "types" : [ "point_of_interest", "establishment" ] }, { "long_name" : "Sídney", "short_name" : "Sídney", "types" : [ "locality", "political" ] }, { "long_name" : "Nueva Gales del Sur", "short_name" : "NSW", "types" : [ "administrative_area_level_1", "political" ] }, { "long_name" : "Australia", "short_name" : "AU", "types" : [ "country", "political" ] }, { "long_name" : "2000", "short_name" : "2000", "types" : [ "postal_code" ] } ], "formatted_address" : "King Street Wharf, Sidney Nueva Gales del Sur 2000, Australia", "geometry" : { "location" : { "lat" : -33. 865662, "lng" : 151. 202115 }, "location_type" : "APPROXIMATE", "viewport" : { "northeast" : { "lat" : 33. 8643130197085, "lng" : 151. 2034639802915 }, "southwest" : { "lat" : -33. 8670109802915, "lng" : 151. 2007660197085 } } }, "partial_match" : true, "types" : [ "point_of_interest", "establishment" ] } ], "status" : "OK" }

Geographical web application • Geocoding Google Maps API Example: var geocoder = new google. maps. Geocoder(); //Instance a geocoding service //Request, indicate the address var request = {'address': "King ST 92, Sidney, Australia"}; geocoder. geocode(request, function(results, status){//Process the request // Always check status, it fails several times. if (status == google. maps. Geocoder. Status. OK){ //results is an array, index 0 is the most accurate result. map. set. Center(results[0]. geometry. location); var marker = new google. maps. Marker({ map: map, position: results[0]. geometry. location }); }else{ //Reasons to fail: address not found, to much queries, http errors, etc. alert('ERROR: ' + status); } });

Geographical web application • Distance Matrix: obtaining distance and time in a travel Using URL query: http: //maps. googleapis. com/maps/api/distancematrix/output? parameters output: json or xml Parameters: origins: address or Lat. Lng of the start point destinations: address or Lat. Lng of the end point sensor: true if you use a GPS to get location, false otherwise mode: transport means: driving, walking, bicycling Driving is the default value Distance and time results are in Json. Response. rows. elements. distance (or duration)

Geographical web application • Distance Matrix Example: Obtaining time and distance from Tokio to Kioto http: //maps. googleapis. com/maps/api/distancematrix/json? origins=Tokio&destinations=Kioto&sensor=false • JSON Result: { "destination_addresses" : [ "Kioto, Prefectura de Kioto, Japón" ], "origin_addresses" : [ "Tokio, Japón" ], "rows" : [{ "elements" : [{ "distance" : { "text" : "459 km", "value" : 458858 }, "duration" : { "text" : "5 h 33 min", "value" : 19951 }, "status" : "OK" }]}], "status" : "OK" } Distance values are in meters, and time values are in seconds

Geographical web application • Directions: obtaining a route (N coordinates) of a travel Using URL query: http: //maps. googleapis. com/maps/api/directions/output? parameters output: json or xml Parameters: origin: address or Lat. Lng of the start point destination: address or Lat. Lng of the end point sensor: true if you use a GPS to get location, false otherwise mode: transport means: driving, walking, bicycling waypoints: midpoints of the path Coordinates array results are in Json. Response. routes. legs. steps

Geographical web application • Directions Example: Obtaining directions of 2 Sidney places http: //maps. googleapis. com/maps/api/directions/json? origin=William+ST+155+Sidney+Australia &destination=King+ST+80+Sidney+Australia&sensor=false • JSON Result: (Direction results have much more information than others) { "routes" : [{ "bounds" : {"northeast" : {"lat" : -33. 8299489, "lng" : 151. 2036268}, "southwest" : {"lat" : -33. 8768538, "lng" : 151. 0093817}}, "legs" : [ { "distance" : {"text" : "22, 3 km", "value" : 22288}, "duration" : {"text" : "26 min", "value" : 1556}, "end_address" : "King Street Wharf, Sidney Nueva Gales del Sur 2000, Australia", "end_location" : {"lat" : -33. 8657065, "lng" : 151. 2021535}, "start_address" : "William St Granville Medical Centre, 68 William Street, Granville Nueva Gales del Sur 2142, Australia", "start_location" : {"lat" : -33. 8358626, "lng" : 151. 010326}, "steps" : [ { "distance" : {"text" : "77 m", "value" : 77}, "duration" : {"text" : "1 min", "value" : 10}, "end_location" : {"lat" : -33. 8357714, "lng" : 151. 0095003}, "start_location" : {"lat" : -33. 8358626, "lng" : 151. 010326}, "travel_mode" : "DRIVING"}, …

Geographical web application • Directions service Google Maps API example //Request service var directions. Service = new google. maps. Directions. Service(); //Rendering service var directions. Display = new google. maps. Directions. Renderer(); directions. Display. set. Map(map); //Set map object to render Use a Direction Service to get info, and a Direction Render to show the results var request = { //Set options for the travel origin: "Santiago, Chile", destination: "Valdivia, Chile", travel. Mode: google. maps. Travel. Mode. DRIVING //Walking , Bicycling , Transit }; //Process the request directions. Service. route(request, function(response, status){ if (status == google. maps. Directions. Status. OK){ //Show the route directions. Display. set. Directions(response); } });

Geographical web application • Directions using waypoints example var directions. Service = new google. maps. Directions. Service(); var directions. Display = new google. maps. Directions. Renderer(); directions. Display. set. Map(map); //Define Waypoints var waypts = [{location: "Rancagua, Chile", stopover: true}, {location: "Pucon, Chile", stopover: true} }]; var request = { origin: "Santiago, Chile", destination: "Valdivia, Chile", waypoints: waypts, //Set Waypoint array optimize. Waypoints: true, // OPTIMIZE ROUTE travel. Mode: google. maps. Travel. Mode. DRIVING }; directions. Service. route(request, function(response, status) { if(status == google. maps. Directions. Status. OK) directions. Display. set. Directions(response); } });

END • Geographical Web Aplication GO!. • Geographical Databases Launch in T-minus 2!

GEOGRAPHICAL DATABASE T-minus 2!

Geographical Databases • Post. GIS: • Postgre. SQL (object-relational database system) with support for geographic objects and GIS features. • WKT format • Well Known Text, special syntax used in Post. GIS to describe geographical objects (Points, lines, polygons, …) • Geo-operators and functions on Post. GIS • WKT to Web objects

Post. GIS - WKT • Post. GIS adds the geometry type to an database catalog. • Uses Well-Known Binary format (WKB) to store Well-Known text (WKT). WKT syntax examples: POINT(0 0) LINESTRING(0 0, -1 1, 2 2) Linestrings are equivalent to Google Maps polylines POLYGON((0 0, 4 4, 0 0), (1 1, 2 2, 1 1)) MULTIPOINT((0 0), (1 2), (-1 1), (-2 4)) MULTILINESTRING((0 0, 1 1, 1 2), (2 3, 3 2, 5 4)) MULTIPOLYGON(((0 0, 4 4, 0 0), (1 1, 2 2, 1 1)), ((-1 -1, -1 -2, -2 -1, -1 -1))) GEOMETRYCOLLECTION(POINT(2 3), LINESTRING(2 3, 3 4))

Post. GIS • In Google Maps we can easily represent POINT, LINESTRING (Polylines) and POLYGON. • If you use these ones your life will be so much easier.

Well Known Text • Transform WKT in WKB is done by a SQL-Post. GIS function ST_Geom. From. Text("WKT-STRING", projection) //You must use projection! 4326 rememeber? SQL-Post. GIS functions are usually called operators • Example: INSERT INTO geotable (the_geom, the_name) VALUES (ST_Geom. From. Text('POINT(-33. 4166667 -70. 5500000)', 4326), 'Santiago'); • You must build the WKT-STRING by concatenate the coordinates from Google Lat. Lng Object from. It’s easier than trying to use a conversion API.

Post. GIS Operators Operator Description ST_Distance(geometry, geometry) Return the cartesian distance between two geometries in projected units. ST_Intersects(geometry, geometry) Returns 1 (TRUE) if the Geometries spatially intersect. ST_Within(geometry A, geometry B) ) Returns 1 (TRUE) if Geometry A is spatially within Geometry B. A has to be completely inside B. // A is a polygon ST_Contains(geometry A, geometry B) // A is a polygon Returns 1 (TRUE) if Geometry A spatially contains Geometry B. ST_Centroid(geometry) Returns the centroid of the geometry as a point. ST_Length(geometry) The length of this Curve in its spatial reference. More about operators in: http: //postgis. refractions. net/docume ntation/manual-1. 3/ch 06. html

OPERATOR • Select geotable. the_name from geotable where ST_Distance( ST_Geom. From. Text('POINT(-33. 4166667 -70. 5500000)', 4326) , geotable. the_geom) < 1000; • Both geometries must be using the same projection. Post. GIS functions: GO • Distance is relative to the coordinate system, so in order to get meters: • ST_Distance( • ST_Transform(ST_Geom. From. Text(‘ geom ', 4326), 26986), • ST_Transform(ST_Geom. From. Text(‘geom 2', 4326), 26986) • ); • 26986 is a coordinate system that uses meters. Not compatible with Google Maps.

POSTGIS results to GOOLE MAPS • Lets asume that the resulting WKT is already loaded into a javascript variable on the browser. In the next section this will be done by creating a webservice. • var mywkt = 'POINT(-33. 4166667 -70. 5500000)‘; // easy to parse, but not so much if it’s a linestring or a polygon. • Google does not read wkt format … sorry… we are going to use Open. Layers API to parse, and the we are going to convert manually from Openlayers object to Google Maps objects.
![Converting a POINT var poi= ol. parser. WKT. read(mywkt ); lat= poi. a. coordinates[1]; Converting a POINT var poi= ol. parser. WKT. read(mywkt ); lat= poi. a. coordinates[1];](http://slidetodoc.com/presentation_image_h2/726847410355d23aa311ffb0d5aa4a81/image-62.jpg)
Converting a POINT var poi= ol. parser. WKT. read(mywkt ); lat= poi. a. coordinates[1]; lng= poi. a. coordinates[0]; // yes , lng is first … several days to get this Var google. Lat. Lng = new google. maps. Lat. Lng(lat, lng)

Converting a Line. String var poi= ol. parser. WKT. read(mywkt ); Var myp. Array = []; for(var k in poi. a. coordinates){ lat= poi. a. coordinates[k][1]; lng= poi. a. coordinates[k][0]; myp. Array[k] = = new google. maps. Lat. Lng(lat, lng) ; } var line= new google. maps. Polyline({ path: myp. Array //Set the array });

Converting a POLYGON var poi= ol. parser. WKT. read(mywkt ); Var myp. Array = []; for(var k in poi. a. coordinates){ // Array of rings. First is outer, any remaining are inner. lat= poi. a. coordinates[0][k][1]; //we load the first…… outer lng= poi. a. coordinates[0][k][0]; myp. Array[k] = = new google. maps. Lat. Lng(lat, lng) ; } var line= new google. maps. Polygon({ paths: myp. Array //Set the array }); WKT to WEB: GO

END • POSTGIS GO!. • Geographical Web Aplication Launch in T-minus 1!

CREATING WEB SERVICES FOR PROCESSING GEOGRAPHICAL INFORMATION T-minus 0!

GO NO GO • Introduction to Node. JS • Creating a web service based on Node. JS • Connecting to geographical databases, POSTIG • Conversion of results from querying databases to JSON • This results contains WKT descriptions • Showing results on a web page

NODE JS • Chrome's Java. Script runtime …. . • lightweight and efficient • Javascript on both sides: Client and Server… Node: GO How to: 1. Download node. . Nodejs. org 2. Create a js file: example. js -> contains 1 line -> console. log(“hello world”); 3. Run the file: node example. js

Lets make a http server var http = require('http'); http. create. Server(function(request, response) { response. write(“Hello World”); Http server: GO response. end(); }). listen(parse. Int(80, 10)); // PORT & CONCURRENT CLIENTS • Request contains POST data, Client data, etc… • Response is to write the http response….

Collaborative APPS? ? ? var http = require('http'), qs = require('querystring'); Var userlocations= {}; //Shared variable http. create. Server(function(request, response) { if(request. method === "POST") { //check type of request var data=""; request. on("data", function(chunk) { data += chunk; “loop” until data is loaded request. on("end", function() { thisclient= qs. parse(data); //parse data userlocations[thisclient. user] = thisclient. location; // update user location response. write(“Location updated”); response. end(); }). listen(parse. Int(80, 10)); ; // PORT & CONCURRENT CLIENTS }); //

Generic web service var http = require('http'), qs = require('querystring'); http. create. Server(function(request, response) { if(request. method === "POST") { //check type of request Webservice : GO var data=""; request. on("data", function(chunk) { data += chunk; }); request. on("end", function() { // Do something with data var; response. write(“write something”); response. end(); }). listen(parse. Int(80, 10)); ; // PORT & CONCURRENT CLIENTS

POSTGIS var http = require('http'), qs = require('querystring'), pg = require('pg'); // POSTGRESQL var con. String = "tcp: //juser: password@localhost/gis"; //CONNECTION CREDENTIALS var db= new pg. Client(con. String); ----------var sql = “SELECT st_ASTEXT(geotable. the_geom), geotable. the_name from geotable"; var q 1= db. query(sql); q 1. on('row', function(row, result) { // For each equivalent…. . }); query. on('end', function() { // when each ‘row’ has been readed. });
![POSTGIS var mydata = []; q 1. on('row', function(row, result) { mydata. push(row); }); POSTGIS var mydata = []; q 1. on('row', function(row, result) { mydata. push(row); });](http://slidetodoc.com/presentation_image_h2/726847410355d23aa311ffb0d5aa4a81/image-73.jpg)
POSTGIS var mydata = []; q 1. on('row', function(row, result) { mydata. push(row); }); query. on('end', function(){ response. write(“All data has been readed”); response. end(); }); ||||| Database Integration: GO
![POSTGIS to JSON var mydata = []; q 1. on('row', function(row, result) { mydata. POSTGIS to JSON var mydata = []; q 1. on('row', function(row, result) { mydata.](http://slidetodoc.com/presentation_image_h2/726847410355d23aa311ffb0d5aa4a81/image-74.jpg)
POSTGIS to JSON var mydata = []; q 1. on('row', function(row, result) { mydata. push(row); Send data in JSON format: }); GO query. on('end', function(){ response. write(JSON. stringify(mydata)); // write in plain text json format all the query response. end(); });

From POSTGIS to NODE to WEB <script> $. ajax({ data: { mydata: [0, 1, 2, 3] }, url: ‘’http: //nodeserver. com', type: 'post', data. Type: ‘json’, // Make it match with the node Output success: function (data) { //data object is an array containing each row result of the query in node. } }); </script>

LAUNCH!!!
- Slides: 76