Sei sulla pagina 1di 15

1

WEB ENuINEERINu
LAB0RAT0RY 6
}AvASCRIPT - A u00uLE NAPS APPLICATI0N ANB SINPLE A}AX
AINS
Theie aie two main aims foi this Laboiatoiy
1. To fuithei assist you to in getting moie piactice with the }avaSciipt uevelopment by
implementing a uoogle maps example.
2. To give an example of using simple A}AX insiue web2py using the jQueiy libiaiy
$.loau() function

REQ0IREB S0FTWARE F0R TBIS LAB0RAT0RY
! Fiiefox Biowsei v17 oi latei
! Fiiebug Bebuggei v1.11.4 oi latei
! WebStoim IBE v6.u oi an alteinative text euitoi
! jQueiy 1.1u oi latei
! "Staitei pack week 8.zip" containing a WebStoim pioject foi uoogle Naps.




2

PART 1: u00uLE NAPS F0NBANENTALS
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.
0SINu A }AvASCRIPT API - u00uLE NAPS
uoogle uistiibutes a }avaSciipt libiaiy to make it easy foi }avaSciipt piogiammeis to access
theii maps clouu seivice.
<script src="http://maps.google.com/maps/api/js?sensor=false"
type="text/javascript"></script>
Fiist you neeu to select a pait of youi page wheie the map will be uisplayeu:
<div id="map_canvas" style="width: 700px; height:500px;"></div>
The google maps libiaiy uses objects to set piefeiences foi the map. These options incluue the
location of the centie of the map, the type of map anu 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 uisplay the map you cieate a new instance of the map object uefineu in the libiaiy with the
maps location on the page anu the options pioviueu to the constiuctoi as paiameteis:
map = new google.maps.Map($("#map_canvas").get(0), myOptions);
Note that with jQueiy we must extiact fiom the jQueiy object $("#map_canvas") just the native
B0N element. The methou get(u) extiacts the fiist pait of the jQueiy object which is the native
B0N element iepiesenting in this case the uiv with iu of map_canvas.
The invocation of the constiuctoi actually initiates an A}AX call to the uoogle Nap seivei. You
uon't neeu to unueistanu how this (A}AX) call is maue as the libiaiy uoes all the haiu woik.
B0WNL0AB ANB TRY 00T TBE STARTER 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.
S



N0vINu TBE NAP T0 Y00R B0NET0WN.
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 uo this you will neeu to finu youi latituue anu longituue on uoogle Naps so that you can
cieate the myhometown object as a type of google.maps.LatLng - theie is an example you can
use in the sliues.
ABBINu BTNL AB00T Y00R B0NET0WN.
Add a div under the button to hold information about your hometown.
4

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:

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

S

PART 2 SINPLE A}AX F0NBANENTALS
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.
}avaSciipt can be useu to access webseiveis without loauing a new page. Theie aie seveial uses
foi this. The fiist is foi companies to pioviue seivices that you can incoipoiate into youi own
web pages using a }avaSciipt libiaiy. This is how uoogle Naps woiks. We have actually been
using A}AX like this alieauy but uoogle Naps has taken caie of it all behinu the scenes.
You can uesign youi own A}AX seivice insiue a fiamewoik like web2py to be useu by youi own
web pages. This is what we will uo in this pait. The simplest foim of Ajax with jQueiy is to
ieloau pait of an BTNL page without iefieshing the whole page. This will be explaineu using
this pait of the lab.
CREATINu A NEW WEB2PY APPLICATI0N.
Open web2py and go the site admin page:

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
CREATINu A NEW WEB2PY F0NCTI0N uNAP.
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.
6



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:

ABBINu BTNL T0 TBE WEB2PY STATIC F0LBER S0 IT CAN BE L0ABEB vIA A}AX.
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 dont 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:

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

7


B0WNL0ABINu ANB INSERTINu TBE BTNL FRAuNENT 0SINu SINPLE A}AX.
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:

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:

After pressing the button you should see this:
8



9

PART S REP0RTINu A}AX PR0uRESS T0 TBE 0SER
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 A}AX uoes not ieloau the whole page it may be haiu foi the usei to unueistanu what's
happening if an eiioi occuis. Ajax eiiois can cause the page to fieeze. Theiefoie it's impoitant
to infoim the usei about the piogiess of Ajax calls. }Queiy pioviues callbacks which inuicate the
piogiess of Ajax calls oi if an eiioi has occuiieu. Insiue these callbacks you can piint the
piogiess messages to the webpage oi the console oi both. Foi example the Ajax stait callback is
activateu when the Ajax call commences. This shoulu tiiggei a Nessage to the usei that the Ajax
content is being loaueu:
$(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:

Now we neeu to auu callback functions that will output to these uivs.
Paste the coue below just aftei the coue foi the myajax function. Nake suie you paste between
the sciipt tags

Beie is the coue to paste:

1u

// 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);
});
11


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

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

you should get messages like this:
12


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

TBIS IS TBE ENB 0F TBE C0NP0LS0RY PART 0F TBE LAB

1S

PART 4 INSERTINu u00uLE NAPS INT0 A WEB2PY APPLICATI0N
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.

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


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 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
1S



ENB 0F LAB

Potrebbero piacerti anche