1 / 76

Geographical Information on the web

Discover the power of Javascript to build interactive web pages and applications that run on a browser. Learn about Javascript syntax, basic data types, associative arrays, operations, if/else statements, loops, functions, callbacks, and more.

karleen
Télécharger la présentation

Geographical Information on the web

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Geographical Information on the web Geographical Web Aplication Launch in T-minus 4!

  2. What is javascript • Allowstobuild more interavtive web-pages • Itisinterpretedbythe browser • Runs at clientside (less load forthe server) • Jacascriptcodeinsidethe HTML code of the page • A powerfultoolcombinedwith HTML 5 tobuildapplicationsthatrunon a browser • Syntax has similaritieswith java and C (butnottoomuch)

  3. Javascript • Javascriptcan control html content <html> <pid="demo"></p> </html> <script> • var y ="helloworld"; document.getElementById("demo").innerHTML= y; </script> innerHTML method sets HTML content to an element. In this case, the paragraph id demo is ‘filling’ with the y variable (hello world)

  4. Javascript • Basic Data Types • // Integer • varx =10; • // Decimal • vary =3.14; • // String • vars ="HelloWorld"; • // Arrays of anything • var z = ["Monday", "Friday", "Saturday", "Saturday", "Saturday", "Saturday","Sunday"]; • // JSON (usefulobject data structure) • varu = { 'day1': {"name": "Monday" , "description": "Firstday of week"} }

  5. Javascript • AssociativeArray • // AssociativeArray • varmyArray= {key1: "value1", key2: "value2"}; • // 2 differentswaystoget a value • varpointer =myArray['key2']; // object[string] • varpointer2 = myArray.key1; // object.key • // Samegoes in assignment • myArray['key3'] ="value3"; • myArray.key4 ="value4";

  6. Javascript • Operation • //Numbers • varx =5, y =4.5; • // Arithmeticoperations • varz =x+y; z = x–y; z = x/y; z = x*y; z =x%y; • //Strings • vars ="not a number "; • varp = "Im "; • //Concatenation • vark = p + s; // “Imnot a number ” • //MixedConcatenation • varmixed= k + x; // “Imnot a number 5”

  7. Javascript • if / elsestatement • whilestatement --ok itsjustwhat are youthinking… • forstatement • if(x == y) {...} //Condition is true • else {...} //Condition is false • // Variables can be NaN (Not a Number) typical conversion problem between text and number, • It happens a lot!!!! • if(!isNaN(x)){...} • for(var i=0; i<10; i++){ • myArray[i] // remember in AssociativeArrays, keys are strings. • ... • }

  8. Javascript Associative Arrays have a different for implementation This saved my life a lot of times… • for(varkeyinmyArray){ • if(myArray.hasOwnProperty(key)){ • // do somethingwithmyArray[key] • } • }

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

  10. Javascript • Callbacks • Callback are functions associated to specific states of others functions (i.e. errors, success, etc) • functionplotdata(data){ /* code to plot */ } • functionshowerror(msg){ /*code to show error*/ } • functioncheckdata(data, callback, error){ • if(...) { //verifying data is OK • callback(data); • }else{ • error("Please fix your data"); • } • } • vardataset = [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!

  11. Example 1 basicinteractivity Getting the element of the document • <script> • functionkk(){ • n = document.getElementById('name').value; • document.getElementById('hola').innerHTML= "Hello "+n; • } • </script> • <body> • <h2> Type in yourname and thenpressthebutton <br> • <input type="text" value="" id="name"/> • <input type="button" value="click" OnClick="kk()"/><br> • </h2> • <h1 id="hola"> hola</h1> • </body> • Shows what is written in the text field when button is pressed Changing its value Specifying what to call when a click event occurs on element

  12. Example 2: recognizingwhichbuttonwaspressed • <script> • functionkk(i){ • n = document.getElementById('name').value; • document.getElementById('hola').innerHTML= "Hello "+n+", youpressedbutton "+i; • i++; • } • </script> • <body> • <h2> Type in yourname and thenpressanybutton <br> • <input type="text" value="" id="name"/><br> • <input type="button1" value="Button 1" OnClick="kk(1)"/> • <input type="button2" value="Button 2" OnClick="kk(2)"/><br></h2> • <h1 id="hola"> hola</h1> • </body> • Shows what is written in the text field when button is pressed Specifying a parameter Giving value to parameter

  13. Example 3: using a canvas and interacting • <canvasstyle="top:0;left:0; background-color:#580" id="can" width="500" height="250" > </canvas> • <h1 id="hola"> hola</h1> • <script> • varcanvas = document.getElementById('can'); • varcontext = canvas.getContext('2d'); • functiondraw(event) { • var h = document.getElementById('hola').innerHTML= '('+event.pageX+','+event.pageY+')'; • context.beginPath(); • context.arc(event.pageX,event.pageY,40,0,2*Math.PI); • context.stroke(); • } • // click, mousedown, mouseup, click, dblclick, select, keydown, beforeinput, input, keyup • canvas.addEventListener('click',draw,false); • </script> • Shows what is written in the text field when button is pressed Specifying a canvas Getting the element and its graphic 2D context Drawing a circle Adding a listener

  14. Example 4: paintingwiththe mouse (1) • <canvasstyle="top:0;left:0; background-color:#580" id="can" width="500" height="250" > </canvas> • <h1 id="hola"> hola</h1> • <button id="clean" type="button" onclick="callbackClean()">clean</button> • <script> • varcanvas = document.getElementById('can'); • varcontext = canvas.getContext('2d'); • var que = 'no painting'; • varmyx = 0; • varmyy = 0; • functioncallbackClean() { • context.clearRect(0, 0, context.canvas.width, context.canvas.height); • } • function iniciar(event) { • myx = event.pageX; • myy = event.pageY; • que = 'painting'; • } • Shows what is written in the text field when button is pressed Where I am now Cleaning the canvas Mousedown detected: Preparing data to paint

  15. Example 4: paintingwiththe mouse (2) • function pintar(event) { • if (que == 'painting') { • context.beginPath(); • context.moveTo(myx,myy); • x = event.pageX; y = event.pageY; • a = 'line from ('+myx+','+myy+') to ('+x+','+y+')'; • var h = document.getElementById('hola').innerHTML= a • context.lineTo(x,y); context.moveTo(x,y); context.stroke(); • myx = x; myy = y; • } • } • function finalizar(event) { • que = 'no painting'; • } • canvas.addEventListener('mousedown', iniciar, false) • canvas.addEventListener('mouseup', finalizar, false) • canvas.addEventListener('mousemove', pintar, false) • </script> Mouse moving • Shows what is written in the text field when button is pressed Standing where I was Asking where I am now Drawing a line Adding listeners

  16. Javascript • AJAX • 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: 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.

  17. Javascript • Ajax • Jquery library simplify considerably Ajax calls • <scriptsrc="//ajax.googleapis.com/ajax/libs/jquery/1.11.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>

  18. Javascript Javascript … GO!

  19. Geographical Data Types • Only based on latitudeand 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 →

  20. Geographical Data Types

  21. 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!.

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

  23. Geographical Data Types • Geographical Data Types GO!.

  24. Web VisualizationComponents

  25. Web VisualizationComponents • Example Google: Just a map • <html> • <scriptsrc="https://maps.googleapis.com/maps/api/js?v=3.exp"></script> • <divid="map-canvas"></div> • <!-- Define propertiesformap-div in CSS likewidth, height--> • </html> • <script> • varmap; • functioninit(){ • //Initialoptions of theMap • varmapOptions={ • zoom: 8, //Zoom level: 1 to 20 • center: newgoogle.maps.LatLng(-34.397, 150.644) // MERCATOR!!!! • }; • map=newgoogle.maps.Map(document.getElementById('map-canvas'), mapOptions); • } • //ConstructstheMaponwindowload • google.maps.event.addDomListener(window, 'load', init); • </script>

  26. Web VisualizationComponents OpenLayers • <html> • <bodyonload="init()"> • <divid="map"></div> • <!-- Define propertiesformap-div in CSS likewidth, height --> • </body> • </html> • <script> • var map, layer; • functioninit(){ • map =newOpenLayers.Map('map'); // Map Object • layer =newOpenLayers.Layer.OSM("Simple OSM Map"); // Map Layer • map.addLayer(layer); // Add Layer to map • map.setCenter(newOpenLayers.LonLat(-71.147, 42.472).transform( • newOpenLayers.Projection("EPSG:4326"), // Yes you must specify! • map.getProjectionObject() // yes you can have multiple projections engines • ), 12 ); // Zoom Level • } • </script>

  27. Web VisualizationComponents • Google Example: Adding a marker • varmarker=newgoogle.maps.Marker({ • position:, newgoogle.maps.LatLng(-25.363882,131.044922) • map: map, //Instance of MapObject • title: 'HelloWorld!'// Tooltip, notinfo-label • });

  28. Web VisualizationComponents • OpenLayersExample: Adding a marker • //Define a new layer for markers • var markers =newOpenLayers.Layer.Markers("Markers"); • map.addLayer(markers); //Add the layer to the map • //Define markers options • var size =newOpenLayers.Size(21,25); • var offset =newOpenLayers.Pixel(-(size.w/2), -size.h); • //Setting the marker icon • var icon =newOpenLayers.Icon('http://www.openlayers.org/dev/img/marker.png',size,offset); • //Add the marker to the layer • markers.addMarker(newOpenLayers.Marker(newOpenLayers.LonLat(0,0),icon)); • // USING DEFAULT PROJECTION OBJECT, MUST CHECK IF MERCATOR!!!

  29. END • Web VisualizationComponentsGO!. • Geographical Web AplicationLaunch in T-minus3!

  30. Displaying Web Maps T-minus 3!

  31. GO no goforlaunch! • 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 OpenLayers, all objects projections must be adapted.

  32. Geographical web application • Displaying a Point as a Marker • //Create a marker object var marker =newgoogle.maps.Marker({ • //Position of the marker position: newgoogle.maps.LatLng(-25.36388,131.04492), • map: map, //Map Object • title: "marker of a point" //tooltip });

  33. Geographical web application • Displaying a line • //Array of LatLng indicate the extreme points of the line • var corners = [newgoogle.maps.LatLng(-29.925626, -71.281886), • newgoogle.maps.LatLng(-29.932767, -71.259956)]; • //Create a Polyline(Line) Object • var line =newgoogle.maps.Polyline({ • path:corners, //Array of LatLng • map:map, //Map Object • strokeColor: "#CC0000", //Line color • strokeOpacity: 0.8, //Line Opacity • strokeWeight: 2//Line width • });

  34. Geographical web application • Displaying polylines • //Array of LatLng indicate the extrem points of the line • varcorners=[newgoogle.maps.LatLng(-29.925626, -71.281886), • newgoogle.maps.LatLng(-29.932767, -71.259956), • newgoogle.maps.LatLng(-29.926891, -71.258153), • newgoogle.maps.LatLng(-29.915025, -71.252317), • newgoogle.maps.LatLng(-29.913835, -71.256694)]; • //Create a Polyline Object • varline =newgoogle.maps.Polyline({ • path:corners, //Array of LatLng • map:map, //Map Object • strokeColor: "#CC0000", //Line color • strokeOpacity: 0.8, //Line Opacity • strokeWeight: 2//Line width • });

  35. Geographical web application • Displaying areas as polygons • // Array of vertex: Firstpoint and lastpointmust be equal! • vartriangleCoords= [newgoogle.maps.LatLng(25.774252, -80.190262), newgoogle.maps.LatLng(18.466465, -66.118292), • newgoogle.maps.LatLng(32.321384, -64.75737), • newgoogle.maps.LatLng(25.774252, -80.190262)]; • //Create a Polygon Object • varpolygon=newgoogle.maps.Polygon({ • path:triangleCoords, //Array of LatLng • map:map, //Map Object • strokeColor: "#FFCC00", //Line color • strokeOpacity: 0.8, //Line Opacity • strokeWeight: 2//Line width • fillColor: "#FFCC00", //Fill color • fillOpacity: 0.3//Fill Opacity • });

  36. Geographical web application • Displaying areas as circles • //Creating a Circle Object • varcircle=newgoogle.maps.Circle({ • //Position of the center • center: newgoogle.maps.LatLng(-25.36388,131.04492), • radius: 1000, //radius in meters • map:map, //Map Object • strokeColor: "#0000FF", //Line color • strokeOpacity: 0.8, //Line Opacity • strokeWeight: 2//Line width • fillColor: "#0000FF", //Fill color • fillOpacity: 0.3 //Fill Opacity • });

  37. Geographical web application • Interactive Maps: Adding events to maps.

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

  39. Geographical web application • Example: Showing info when mouse over a marker • //Info Window Object • varinfo=newgoogle.maps.InfoWindow({ • content:"HelloWorld!"//Content of InfoWindow • }); //InitiatllyInfoWindow is closed • google.maps.event.addListener(marker,'mouseover',function(){ • info.open(map,marker); //Open when mouse over • }); • google.maps.event.addListener(marker,'mouseout',function(){ • info.close(map,marker); //Closewhenmouse out • });

  40. Geographical web application • //Function to manage multiple markers • functionaddMarker(marker, txt){ • //Set id according to markerArray's length • marker.id=markerArray.length(); • markerArray.push(marker); //Add to Array • //Event Handler • google.maps.event.addListener(marker,'click',function(){ • alert("You click the marker id "+marker.id); • //You can get the index • }); • } • //Usage • varmymarker=newgoogle.maps.Marker({ • position: location, //Some location • map: map • }); • addMarker(mymarker); //Add marker • TIPS to manage multiple markers: • Store all your markers in a markerArray 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

  41. 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 v3 • Main Google web services: • Geocoding: Obtaining coordinates -latitude and longitude- from an address • DistanceMatrix: 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

  42. Geographical web application • JSON • 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 • { • "key1": value1, • "key2": value2, • "key3": value3, • ... • } Values could be of any type: numbers, strings, booleans, arrays or even other objects with the same notation

  43. 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)

  44. 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: • 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 In Javascript use JSON because it’s easy to use and valid Javascript object • Coordinates results are in JsonResponse.geometry.location.lat (or lng)

  45. Geographical web application • GeocodingExample: Obtaining coordinates of King ST 92, Sidney, Australia • JSON Result: (a lot of other information also is received) • http://maps.googleapis.com/maps/api/geocode/json?address=King+ST+92+Sidney+Australia&sensor=false { "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" }

  46. Geographical web application • Geocoding Google Maps API Example: • vargeocoder=newgoogle.maps.Geocoder(); //Instance a geocoding service • //Request, indicate the address • varrequest= {'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.GeocoderStatus.OK){ • //results is an array, index 0 is the most accurate result. • map.setCenter(results[0].geometry.location); • var marker =newgoogle.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); • } });

  47. Geographical web application • Distance Matrix: obtaining distance and time in a travel UsingURL query: • http://maps.googleapis.com/maps/api/distancematrix/output?parameters • output: json or xml • Parameters: • origins: address or LatLng of the start point • destinations: address or LatLngof 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 JsonResponse.rows.elements.distance (or duration)

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

  49. Geographical web application • Directions: obtaining a route (N coordinates) of a travel UsingURL query: • http://maps.googleapis.com/maps/api/directions/output?parameters • output: json or xml • Parameters: • origin: address or LatLng of the start point • destination: address or LatLngof 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 JsonResponse.routes.legs.steps

  50. Geographical web application • Directions Example: Obtaining directions of 2 Sidney places • JSON Result: (Direction results have much more information than others) • http://maps.googleapis.com/maps/api/directions/json?origin=William+ST+155+Sidney+Australia • &destination=King+ST+80+Sidney+Australia&sensor=false { "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"}, …

More Related