Sei sulla pagina 1di 15

W EB E NGINEERING

L ABORATORY 6

JAVA S CRIPT - A GOOGLE M APS A PPLICATION AND S IMPLE AJAX

A IMS

There are two main aims for this Laboratory

1. To further assist you to in getting more practice with the JavaScript development by implementing a Google maps example.

2. T o give an example of using simple AJAX inside web2py using the jQuery library $.load() function

R EQUIRED SOFTWARE FOR THIS LABORATORY

Firefox Browser v17 or later

Firebug Debugger v1.11.4 or later

WebStorm IDE v6.0 or an alternative text editor

jQuery 1.10 or later

“Starter pack week 8 .zip ” containing a WebStorm project for Google Maps.

P ART 1: G OOGLE M APS F UNDAMENTALS

By the end of this part of the practical you should be able use Google Maps to display a map of Adelaide. You should also be able to move the map centre to the location of your hometown and display some simple information about your hometown below the map.

USING A JAVA S CRIPT API – GOOGLE M APS

Google distributes a JavaScript library to make it easy for JavaScript programmers to access their maps cloud service.

<script src="http://maps.google.com/maps/api/js?sensor=false" type="text/javascript"></script>

First you need to select a part of your page where the map will be displayed:

<div id="map_canvas" style="width: 700px; height:500px;"></div>

The google maps library uses objects to set preferences for the map. These options include the location of the centre of the map, the type of map and the zoom level:

var myLatlng = new google.maps.LatLng(-34.85, 138.6);

var myOptions = {

zoom: 11,

center: myLatlng,

mapTypeId: google.maps.MapTypeId.ROADMAP

}

To display the map you create a new instance of the map object defined in the library with the maps location on the page and the options provided to the constructor as parameter s:

map = new google.maps.Map($("#map_canvas").get(0), myOptions);

Note that with jQuery we must extract from the jQuery object $( " # map_canvas") just the native DOM element. The method get(0) extracts the first part of the jQuery object which is the native DOM element representing in this case the div with id of map_canvas.

The invocation of the constructor actually initiates an AJAX call to the Google Map server. You don’t need to understand how this (AJAX) call is made as the library does all the hard work .

DOWNLOAD AND TRY OUT THE S TARTER PACK WEEK 8. ZIP

Unizp the start into a folder on your USB drive. Open WebStorm or an alternative text editor to edit files in the folder. Run Labgmapajaxstarter.html to display the map.

M OVING THE MAP TO YOU R HOMETOWN . Add a button under the map

M OVING THE MAP TO YOU R HOMETOWN .

Add a button under the map that is marked with the name “Move to my home town”, using the HTML <input type="button" value="Move to my home town" />

Use the onclick property of the button to execute a new function called moveCentre() on the map object. Add a definition for the function at the bottom of the body inside the script tag. The function should look like this pseudocode:

function moveCentre() {

alert('About to move the map to Insert your home town here');

// Find the latitude and longitude of your hometown and create a new

// Google maps entity for this and assign it to a variable myhometown

// Insert your code here

// Use the correct method on the map object to change the centre

// Insert your code here

}

To do this you will need to find your latitude and longitude on Google Maps so that you can create the myhometown object as a type of google.maps.LatLng – there is an example you can use in the slides.

A DDING HTML ABOUT YOU R HOME TOWN .

Add a div under the button to hold information about your hometown.

Inside the function moveCentre() add jQuery code that inserts a few html sentences about your home town below the button. The result should look like this:

town below the button. The result should look like this: You will need to a) identify

You will need to a) identify the div to change, and b) rewrite the html it contains using the .html() function.

P ART 2 S IMPLE AJAX F UNDAMENTALS

By the end of this part of the practical you should be able use the jQuery.load() function to fetch some html from the web2py server using AJAX and place it on a web page.

Java S cri pt can be used to access webservers without loading a new page. There are several uses for this. The first is for companies to provide services that you can incorporate into your own web pages using a JavaScript library. This is how G oogle M aps works. We h ave actually been using AJAX like this already but G oogle M aps has taken care of it all behind the scenes.

You can design your own AJAX service inside a framework like web2py to be used by your own web pages. This is what we will do in this part. The sim plest form of Ajax with jQuery is to reload part of an HTML page without refreshing the whole page. This will be explained using this part of the lab.

CREATING A NEW WEB 2PY APPLICATION .

Open web2py and go the site admin page:

2 PY APPLICATION . Open web2py and go the site admin page: Create a new simple

Create a new simple application called Labgmapajax

Open WebStorm or an alternative text browse. If using WebStorm, create a new project pointing to this application: web2py/applications/Labgmapajax

CREATING A NEW WEB 2PY FUNCTION GMAP .

Edit the default controller and create a new function called gmap() which returns a dict() in the same way that the index() function does so that it invokes a view with a message “Google maps example”.

Inside the views/default folder create a new html file called default/gmap.html. Copy the html from

Inside the views/default folder create a new html file called default/gmap.html. Copy the html from view index.html to gmap.html. Remove all the html from after “how did you get here”

Test out gmap - it should look like this:

you get here” Test out gmap - it should look like this: A DDING HTML TO

A DDING HTML TO THE WE B 2PY STATIC FOLDER SO IT CAN BE LOADED VIA AJAX.

Using AJAX we will load some html from the web2py file system. First we need to store this html in the filesystem. The place where will store it is the web2py static folder.

Create a directory in the Labgmapajax/static folder called myajax. Create a new html file in this folder called ajaxload.html. Delete the default contents of this file and replace it with this contents only. Note because this is not a complete html file we don’t need any headers or body HTML tags.

<p>This is a fragment of html for use with simple ajax</p>

If using WebStorm, the environment should now look like this:

using WebStorm, the environment should now look like this: You should be able to load this

You should be able to load this fragment in the browser via the web2py server using the URL:

D OWNLOADING AND INSER TING THE HTML FRAGME NT USING SIMPLE AJAX. Create a button

DOWNLOADING AND INSER TING THE HTML FRAGME NT USING SIMPLE AJAX.

Create a button in the gmap.html view called “download with ajax”. Give the button an onclick property so that it executes the function myajax when it is pressed. Create the function myajax and insert an alert in it. Check the button works.

Now add the AJAX code to the functions myajax as follows:

Now add the AJAX code to the functions myajax as follows: Note that the .load() method

Note that the .load() method takes the URL of the html fragment. However with web2py you can use the (Python) URL helper in the view to generate the correct URL making the implementation more portable. This has been left commented out in the code above.

Test this out. Before you press the button you should have this:

above. Test this out. Before you press the button you should have this: After pressing the

After pressing the button you should see this:

8

P ART 3 R EPORTING AJAX PROGRESS TO THE USER

By the end of this part of the practical you should be able to report the progress of AJAX calls to the user and report AJAX errors.

Because AJAX does not reload the whole page it may be hard for the user to understand what’s happening if an error occurs. Ajax errors can cause the page to freeze. Therefore it’s important to inform the user about the progress of Ajax calls. JQuery provides callbacks which indicate the progress of Ajax calls or if an error has occurred. Inside these callbacks you can print the progress messages to the webpage or the console or both. For example the Ajax start callback is activated when the Aj ax call commences. This should trigger a Message to the user that the Ajax content is being loaded:

$(document).ajaxStart(function() {

$('.ajaxStart').text('Triggered ajaxStart handler: AJAX Loading

console.log('Triggered ajaxStart handler: AJAX Loading

});

');

');

To insert progress messages on your simple AJAX page you need to first allocate a place in the HTML where they will be displayed. Add this HTML to your view to do this:

will be displayed. Add this HTML to your view to do this: Now we need to

Now we need to add callback functions that will outp ut to these divs.

Paste the code below just after the code for the myajax function. Make sure you paste between the script tags

just after the code for the myajax function. Make sure you paste between the script tags

Here is the code to paste:

// callbacks for jQuery AJAX progress messages

//jQuery only fires those events (ajaxStart and ajaxStop) if it internally uses the XMLHttpRequest object.

// However if you request data from a different domain using a callback parameter (JSONP),

// jQuery does not use XMLHttpRequest, instead it accomplishes that by inserting a <script> tag.

//Then these events will not fire.

// This callback is activated when an AJAX call is first made

// It is typically used to provided a loading

message to the user

// for jQuery 1.9 these must be attached to the document

$(document).ajaxStart(function() {

$('.ajaxStart').text('Triggered ajaxStart handler: AJAX Loading

console.log('Triggered ajaxStart handler: AJAX Loading

});

');

');

// This callback is activated when a successful return comes back from the server

// This will be printed when the HTTP 200 status code comes back

// There may be situations where this callback is activated

// But the response is actually empty

$(document).ajaxSuccess(function() {

$('.ajaxSuccess').text('Triggered ajaxSuccess handler: AJAX succeeded');

console.log("Triggered ajaxSuccess handler: AJAX succeeded");

});

// This callback is activated when the AJAX process is complete

$(document).ajaxComplete(function() {

$('.ajaxComplete').text('Triggered ajaxComplete handler: AJAX complete');

console.log("Triggered ajaxComplete handler: AJAX complete");

});

// This callback is activated on and error during the AJAX call

// Typical errors include timeouts , HTTP 404 and 500 errors

// A 404 will happen if the URL is wrong

// A 500 error will occur if your server Python code crashes

// A 500 error will usually be associated with web2py issuing a ticket

$(document).ajaxError(function(event, xhr, ajaxOptions, thrownError) {

$('.ajaxHTTPerror').text('Triggered ajaxError handler. HTTP error number is '+xhr.status);

console.log('Triggered ajaxError handler. HTTP error number is '+xhr.status);

});

Test out your code. If you press the Load via ajax button you should get messages like this:

the Load via ajax button you should get messages like this: If you deliberately make a

If you deliberately make a mistake in the URL for the AJAX call by replacing static with xxxstatic in the URL path

in the URL for the AJAX call by replacing static with xxxstatic in the URL path

you should get messages like this:

Notice that if you use Firebug the error messages on the AJAX call will also

Notice that if you use Firebug the error messages on the AJAX call will also be reported in the console.

T HIS IS THE END OF TH E COMPULSORY PART OF THE LAB

P ART 4 I NSERTING GOOGLE MAPS INTO A WEB 2 PY APPLICATION

By the end of this part of the practical you will be able to construct a web2py application that includes Google Maps.

Past the html from the Google Maps part of this lab into the view gmap above the ajax html.

part of this lab into the view gmap above the ajax html. Now paste the script

Now paste the script functions from the Google Map solution inside the script tags and before the myajax function:

Test it out. The map will not appear because the Google Maps library reference is

Test it out. The map will not appear because the Google Maps library reference is not present in the web2py web pages.

You can fix this by adding the script tag to the view:

You can fix this by adding the script tag to the view: You can also add

You can also add this to layout.html if you wish.

You should now get the map visible.

You can add ajax to load the information about your home town by changing the code that loads the html to an ajax call and adding the information about your hometown to the static/myajax folder of the application. If we assume that the application for the Google Maps option for this lab is Labgmapajaxoption then this sort of code will add ajax

E ND OF L AB 15

E ND OF L AB