Thư viện tri thức trực tuyến
Kho tài liệu với 50,000+ tài liệu học thuật
© 2023 Siêu thị PDF - Kho tài liệu học thuật hàng đầu Việt Nam

Beginning Ajax with PHP From Novice to Professional phần 9 pps
Nội dung xem thử
Mô tả chi tiết
All right, so here is your functions.js file; this is where all of the Google Maps functionality and Ajax-based concepts are happening. Let’s have a closer look. You first define
mapContainer and msgContainer, which will hold the divs you created to hold your map and
status message, respectively. You set these in the init() method.
Next, you set the default values for your map: the default latitude and longitude and
the zoom level. In this case, your map will automatically center on Calgary.
Next, you set the URL from which you fetch the locations. Although this is a PHP file,
it will return XML data, which you can then plot on your map.
Finally, you have two small utility functions. The first is used to trim a value, which
works the same as PHP’s trim function (removing whitespace from the beginning and
end of a string). You use this in your basic form validation. The second is used to write a
message to your status message div.
//functions.js
// div to hold the map
var mapContainer = null;
// div to hold messages
var msgContainer = null;
// coords for Calgary
var mapLng = -114.06;
var mapLat = 51.05;
var mapZoom = 7;
// locations xml file
var locationsXml = 'locations.php';
function trim(str)
{
return str.replace(/^(\s+)?(\S*)(\s+)?$/, '$2');
}
function showMessage(msg)
{
if (msg.length == 0)
msgContainer.style.display = 'none';
else {
msgContainer.innerHTML = msg;
msgContainer.style.display = 'block';
}
}
166 CHAPTER 10 ■ SPATIALLY ENABLED WEB APPLICATIONS
6676CH10.qxd 9/27/06 11:59 AM Page 166
Next you have your script initialization function. This is the function you called in
the onload event in sample10_1.php. Here you set the elements that will hold your Google
map and your status message. After this has been set, you call loadMap, which displays the
map based on your settings and loads your various points. We will look at this function
more closely shortly:
function init(mapId, msgId)
{
mapContainer = document.getElementById(mapId);
msgContainer = document.getElementById(msgId);
loadMap();
}
The next function you define is a handy little function that creates a marker for your
Google map. This doesn’t actually add the marker to the map—you create the point using
this function then add it later on.
The first parameter to this function is the map point, which you also create elsewhere based on a location’s latitude and longitude. The second parameter contains the
HTML you will display inside the pop-up window.
function createInfoMarker(point, theaddy)
{
var marker = new GMarker(point);
GEvent.addListener(marker, "click",
function() {
marker.openInfoWindowHtml(theaddy);
}
);
return marker;
}
This next function is the core function behind generating your Google map. You first
create your map using the GMap class (provided by the Google JavaScript file you included
earlier), and then you add some features to the map (the zoom control and ability to
change the map type). You then center your map on the coordinates defined previously.
Next, you use Ajax to load the locations from your database. Here you are using
Google’s code to generate your XMLHttpRequest object, just for the sake of completeness.
You then define your onreadystatechange function as in previous examples. This function
uses the returned XML from your locations.php file. You use the built-in JavaScript functions for handling XML to read each row, creating a point (using Google’s GPoint class),
and defining the marker HTML.
You then call your createInfoMarker function to generate a marker that you can then
add to the Google map.
CHAPTER 10 ■ SPATIALLY ENABLED WEB APPLICATIONS 167
6676CH10.qxd 9/27/06 11:59 AM Page 167
You will notice that this code is using the POST method to get the data, and also that a
dummy string is sent (a, in this case). The reason for doing this is that Internet Explorer
will cache the results from a GET request (as it will if you use POST and send a null string
to the send function). Doing it this way means that the locations file will be correctly
reloaded when a new location is added:
function loadMap()
{
var map = new GMap(mapContainer);
map.addControl(new GMapTypeControl());
map.addControl(new GLargeMapControl());
map.centerAndZoom(new GPoint(mapLng, mapLat), mapZoom);
var request = GXmlHttp.create();
request.open("POST", locationsXml, true);
request.onreadystatechange = function() {
if (request.readyState == 4) {
var xmlDoc = request.responseXML;
var markers = xmlDoc.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var point = new GPoint(parseFloat(markers[i].getAttribute("longitude")),
parseFloat(markers[i].getAttribute("latitude")));
var theaddy = '<div class="location"><strong>'
+ markers[i].getAttribute('locname')
+ '</strong><br />';
theaddy += markers[i].getAttribute('address') + '<br />';
theaddy += markers[i].getAttribute('city') + ', '
+ markers[i].getAttribute('province') + '<br />'
+ markers[i].getAttribute('postal') + '</div>';
var marker = createInfoMarker(point, theaddy);
map.addOverlay(marker);
}
}
}
request.send('a');
}
The final function in your functions.js file is the submitForm function, which is called
when the user submits the form. The first few lines in this function define a list of the
fields you will be submitting, along with a corresponding error message if an invalid
168 CHAPTER 10 ■ SPATIALLY ENABLED WEB APPLICATIONS
6676CH10.qxd 9/27/06 11:59 AM Page 168
value is entered. Your data validation is simple in that it just checks to make sure something has been entered.
You then loop over the values in this structure, using the keys to fetch the corresponding value from the passed-in form. If the value is empty, you add the corresponding
error message. Note that as you loop over each of these values, you are also building up
a string (called values) that you are going to pass to your XMLHttpRequest object as the
POST data.
After all the values have been checked, you check whether any error messages
have been set. If they have, you use the showMessage function to display the errors, and
then return from this function (thereby not executing the remainder of the code in
submitForm). If there are no errors, you continue on with the function.
Here you use Google’s code to create your XMLHttpRequest object, using the action of
the passed-in form to determine where to post the form data (process_form.php). This
form-processing script then returns a status message, which you display by once again
using showMessage.
The final action taken in this function is to reload the map in the user’s browser.
You want to give the form processor time to process the submitted data, so you use the
JavaScript setTimeout function to create a 1-second (1000 ms) delay before calling the
loadMap function.
function submitForm(frm)
{
var fields = {
locname : 'You must enter a location name',
address : 'You must enter an address',
city : 'You must enter the city',
province : 'You must enter the province',
postal : 'You must enter a postal code',
latitude : 'You must enter the latitude',
longitude : 'You must enter the longitude'
};
var errors = [];
var values = 'ajax=1';
for (field in fields) {
val = frm[field].value;
if (trim(val).length == 0)
errors[errors.length] = fields[field];
values += '&' + field + '=' + escape(val);
}
CHAPTER 10 ■ SPATIALLY ENABLED WEB APPLICATIONS 169
6676CH10.qxd 9/27/06 11:59 AM Page 169