Building the Polylines Demo

Một phần của tài liệu Beginning Google Maps Applications with PHP and Ajax From Novice to Professional PHẦN 8 potx (Trang 26 - 30)

Our starting setup will be pretty familiar from prior chapters. For markup and styles, establish a basic screen involving a header and flanking sidebar, as shown in Listing 10-7.

Listing 10-7. index.php for Polylines Example

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"

"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml">

<head>

<script src="http://maps.google.com/maps?file=api&v=2&key=<?= $api_key ?>"➥ type="text/javascript"></script>

<script src="map_functions.js" type="text/javascript"></script>

<link href="style.css" rel="stylesheet" type="text/css" />

C H A P T E R 1 0■ L I N E S, L E N G T H S, A N D A R E A S 274

<!--[if IE]>

<style type="text/css"> v\:* { behavior:url(#default#VML); } </style>

<![endif]-->

</head>

<body class="sidebar-right">

<div id="toolbar">

<h1>Lengths and Areas</h1>

<ul id="sidebar-controls">

<li><a href="#" id="button-sidebar-hide">hide</a></li>

<li><a href="#" id="button-sidebar-show">show</a></li>

</ul>

</div>

<div id="content">

<div id="map-wrapper">

<div id="map"></div>

</div>

<div id="sidebar">

<div id="line-info">

<p><span id="length-title">Length</span>

<span id="length-data">0</span> km</p>

<p>Area: <span id="area-data">0</span> km<sup>2</sup></p>

</div>

<ul id="sidebar-list">

</ul>

</div>

</div>

</body>

</html>

You can see we’ve dropped the link element that included the map_points.phpdata. To

“prove” that the calculations in this chapter are working properly, it will be more fun to feed them new data on each run. Additionally, we’ve added an extra XML namespace, plus a bizarre proprietary style rule contained inside a conditional comment. This is a special Microsoft HTML comment that reliably hides the rule from all non-Internet Explorer browsers (see http://msdn.

microsoft.com/workshop/author/dhtml/overview/ccomment_ovw.asp). Including this rule is a prerequisite to using the GPolylineclass, if we want our polylines to work in Internet Explorer.

Why such requirements? To render polylines on Internet Explorer, Google Maps uses Vector Markup Language (VML), an XML vector language that was ahead of its time, and sadly never got included in browsers other than Internet Explorer. For nonsupporting user agents, the API simply has Google’s servers render a PNG image, which gets draped over the map. In some cases, it will try to render the polyline using Scalable Vector Graphics (SVG), a contem- porary standard that occupies the same space VML once did.

We could always stick the VML rule in with all the other rules in our main style.cssfile, but because it’s not standard, we should keep it separate and away from browsers that might choke on it. (Generally, it’s considered good CSS practice to keep any filters or “hack” style rules separated from the main flow of the style sheet.)

The styles used in this demo are lifted verbatim from the demos in prior chapters.

C H A P T E R 1 0■ L I N E S, L E N G T H S, A N D A R E A S 275

And, as for the JavaScript, well, a lot of it is similar to what you’ve seen before, but we’ve made some changes, too, which are highlighted in the next few listings, starting with Listing 10-8.

Listing 10-8. Initialization Function in map_functions.js, Containing a GEvent Call var map;

var centerLatitude = 40.6897;

var centerLongitude = -95.0446;

var startZoom = 5;

var deselectCurrent = function() {};

var removePolyline = function() {};

var earthRadius = 6378137; // in metres var latlngs = [];

function init() { document.getElementById('button-sidebar-hide').onclick =➥ function() { return changeBodyClass('sidebar-right', 'nosidebar'); };

document.getElementById('button-sidebar-show').onclick =➥

function() { return changeBodyClass('nosidebar', 'sidebar-right'); };

handleResize();

map = new GMap2(document.getElementById("map"));

map.setCenter(new GLatLng(centerLatitude, centerLongitude), startZoom);

map.addControl(new GSmallMapControl());

GEvent.addListener(map, 'click', handleMapClick);

}

Most of this should be familiar to you from earlier chapters, including the one line that attaches a click handler to the map object. But, of course, we can’t just reference a map click handler function and not show it to you.

The handleMapClick()function is designed to build up a list of a GLatLngobjects in an array, and on each new one added, redraw a polyline that connects the lot. Check it out in Listing 10-9.

Listing 10-9. Handler for Map Clicks, in map_functions.js function handleMapClick(marker, latlng) {

if (!marker) {

latlngs.push(latlng);

initializePoint(latlngs.length - 1);

redrawPolyline();

} }

This function is not a tricky one. It just adds the new GLatLngto the accumulating array, initializes the new point, and then has a second function redraw the polyline that connects all the points. So what are the functions initializePoint()and redrawPolyline()?

C H A P T E R 1 0■ L I N E S, L E N G T H S, A N D A R E A S 276

The venerable initializePoint()function has undergone some slight renovations from previous versions, but large chunks of it will remain familiar in Listing 10-10. The biggest change is that a new draggableparameter has been enabled, so that we can move our markers around once they’re down on the map.

Listing 10-10. Function for Initializing Individual Points from a Global Array function initializePoint(id) {

var marker = new GMarker(latlngs[id], { draggable:true });

var listItem = document.createElement('li');

var listItemLink = listItem.appendChild(document.createElement('a'));

listItemLink.href = "#";

listItemLink.innerHTML = '<strong>' + latlngs[id].lat() +➥ '<br />' + latlngs[id].lng() + '</strong>';

var focusPoint = function() { deselectCurrent();

listItem.className = 'current';

deselectCurrent = function() { listItem.className = ''; } map.panTo(latlngs[id]);

return false;

}

GEvent.addListener(marker, 'click', focusPoint);

listItemLink.onclick = focusPoint;

document.getElementById('sidebar-list').appendChild(listItem);

map.addOverlay(marker);

marker.enableDragging();

GEvent.addListener(marker, 'dragend', function() {

listItemLink.innerHTML = '<strong>' + latlngs[id].lat() +'<br />' + latlngs[id].lng() + '</strong>';

latlngs[id] = marker.getPoint();

redrawPolyline();

});

}

You can see now why it was important to keep initializePoint()and redrawPolyline() as separate entities—so that a dragged marker could also trigger a redrawing of the polyline.

Speaking of redrawn polylines, let’s take a peek at the redrawPolyline()function in Listing 10-11.

Listing 10-11. Function to Redraw a Polyline from a Global Array function redrawPolyline() {

var pointCount = latlngs.length;

var id;

C H A P T E R 1 0■ L I N E S, L E N G T H S, A N D A R E A S 277

map.removeOverlay(polyline)

// Plot polyline, adding the first element to the end, to close the loop.

latlngs.push(latlngs[0]);

var polyline = new GPolyline(latlngs, 'FF6633', 4, 0.8);

map.addOverlay(polyline);

// Check total length of polyline (length for 2 points, perimeter > 2 points) if (pointCount >= 2) {

var length = 0;

for(id = 0; id < pointCount; id += 1) {

length += latlngs[id].distanceFrom(latlngs[id + 1]);

}

if (pointCount > 2) {

document.getElementById('length-title').innerHTML = 'Perimeter';

document.getElementById('length-data').innerHTML =➥

Math.round(length) / 1000;

} else {

document.getElementById('length-title').innerHTML = 'Length';

document.getElementById('length-data').innerHTML =➥

Math.round(length) / 2000;

} }

latlngs.pop(); // restore the array to how it was // Show value of area in square km.

if (pointCount >= 3) {

document.getElementById('area-data').innerHTML =➥

polylineArea(latlngs) / 1000000;

} }

This function may be long, but it’s mostly just a sequence of mundane tasks: pad the list of points, remove the old polyline, draw the new polyline, iterate through to check length, and call our previous function to check area.

Một phần của tài liệu Beginning Google Maps Applications with PHP and Ajax From Novice to Professional PHẦN 8 potx (Trang 26 - 30)

Tải bản đầy đủ (PDF)

(39 trang)