-
Notifications
You must be signed in to change notification settings - Fork 0
/
geoxml3.js
442 lines (387 loc) · 14.6 KB
/
geoxml3.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
/*
geoXML3.js
Renders KML on the Google Maps JavaScript API Version 3
http://code.google.com/p/geoxml3/
Copyright 2009 Sterling Udell
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Extend the global String with a method to remove leading and trailing whitespace
if (!String.prototype.trim) {
String.prototype.trim = function () {
return this.replace(/^\s+|\s+$/g, '');
};
}
// Declare namespace
geoXML3 = window.geoXML3 || {};
// Constructor for the root KML parser object
geoXML3.parser = function (options) {
// Private variables
var parserOptions = geoXML3.combineOptions(options, {
singleInfoWindow: false,
processStyles: true,
zoom: true
});
var docs = []; // Individual KML documents
var lastMarker;
// Private methods
var parse = function (urls) {
// Process one or more KML documents
if (typeof urls === 'string') {
// Single KML document
urls = [urls];
}
// Internal values for the set of documents as a whole
var internals = {
docSet: [],
remaining: urls.length,
parserOnly: !parserOptions.afterParse
};
var thisDoc;
for (var i = 0; i < urls.length; i++) {
thisDoc = {
url: urls[i],
internals: internals
};
internals.docSet.push(thisDoc);
geoXML3.fetchXML(thisDoc.url, function (responseXML) {render(responseXML, thisDoc);});
}
};
var hideDocument = function (doc) {
// Hide the map objects associated with a document
var i;
for (i = 0; i < doc.markers.length; i++) {
this.markers[i].set_visible(false);
}
for (i = 0; i < doc.overlays.length; i++) {
doc.overlays[i].setOpacity(0);
}
};
var showDocument = function (doc) {
// Show the map objects associated with a document
var i;
for (i = 0; i < doc.markers.length; i++) {
doc.markers[i].set_visible(true);
}
for (i = 0; i < doc.overlays.length; i++) {
doc.overlays[i].setOpacity(doc.overlays[i].percentOpacity_);
}
};
var render = function (responseXML, doc) {
// Callback for retrieving a KML document: parse the KML and display it on the map
if (!responseXML) {
// Error retrieving the data
geoXML3.log('Unable to retrieve ' + doc.url);
if (parserOptions.failedParse) {
parserOptions.failedParse(doc);
}
} else if (!doc) {
throw 'geoXML3 internal error: render called with null document';
} else {
doc.styles = {};
doc.placemarks = [];
doc.groundOverlays = [];
if (parserOptions.zoom && !!parserOptions.map)
doc.bounds = new google.maps.LatLngBounds();
// Parse styles
var styleID, iconNodes, i;
var styleNodes = responseXML.getElementsByTagName('Style');
for (i = 0; i < styleNodes.length; i++) {
styleID = styleNodes[i].getAttribute('id');
iconNodes = styleNodes[i].getElementsByTagName('Icon');
if (!!iconNodes.length) {
doc.styles['#' + styleID] = {
href: geoXML3.nodeValue(iconNodes[0].getElementsByTagName('href')[0])
};
}
}
if (!!parserOptions.processStyles || !parserOptions.createMarker) {
// Convert parsed styles into GMaps equivalents
processStyles(doc);
}
// Parse placemarks
var placemark, node, coords, path;
var placemarkNodes = responseXML.getElementsByTagName('Placemark');
for (i = 0; i < placemarkNodes.length; i++) {
// Init the placemark object
node = placemarkNodes[i];
placemark = {
name: geoXML3.nodeValue(node.getElementsByTagName('name')[0]),
description: geoXML3.nodeValue(node.getElementsByTagName('description')[0]),
styleUrl: geoXML3.nodeValue(node.getElementsByTagName('styleUrl')[0])
};
placemark.style = doc.styles[placemark.styleUrl] || {};
if (/^https?:\/\//.test(placemark.description)) {
placemark.description = '<a href="' + placemark.description + '">' + placemark.description + '</a>';
}
// Extract the coordinates
coords = geoXML3.nodeValue(node.getElementsByTagName('coordinates')[0]).trim();
coords = coords.replace(/\s+/g, ' ').replace(/, /g, ',');
path = coords.split(' ');
// What sort of placemark?
if (path.length === 1) {
// Polygons/lines not supported in v3, so only plot markers
coords = path[0].split(',');
placemark.point = {
lat: parseFloat(coords[1]),
lng: parseFloat(coords[0]),
alt: parseFloat(coords[2])
};
if (!!doc.bounds) {
doc.bounds.extend(new google.maps.LatLng(placemark.point.lat, placemark.point.lng));
}
// Call the appropriate function to create the marker
if (!!parserOptions.createMarker) {
parserOptions.createMarker(placemark, doc);
} else {
createMarker(placemark, doc);
}
}
}
// Parse ground overlays
var groundOverlay, color, transparency;
var groundNodes = responseXML.getElementsByTagName('GroundOverlay');
for (i = 0; i < groundNodes.length; i++) {
node = groundNodes[i];
// Init the ground overlay object
groundOverlay = {
name: geoXML3.nodeValue(node.getElementsByTagName('name')[0]),
description: geoXML3.nodeValue(node.getElementsByTagName('description')[0]),
icon: {href: geoXML3.nodeValue(node.getElementsByTagName('href')[0])},
latLonBox: {
north: parseFloat(geoXML3.nodeValue(node.getElementsByTagName('north')[0])),
east: parseFloat(geoXML3.nodeValue(node.getElementsByTagName('east')[0])),
south: parseFloat(geoXML3.nodeValue(node.getElementsByTagName('south')[0])),
west: parseFloat(geoXML3.nodeValue(node.getElementsByTagName('west')[0]))
}
};
if (!!doc.bounds) {
doc.bounds.union(new google.maps.LatLngBounds(
new google.maps.LatLng(groundOverlay.latLonBox.south, groundOverlay.latLonBox.west),
new google.maps.LatLng(groundOverlay.latLonBox.north, groundOverlay.latLonBox.east)
));
}
// Opacity is encoded in the color node
color = geoXML3.nodeValue(node.getElementsByTagName('color')[0]);
if ((color !== '') && (color.length == 8)) {
transparency = parseInt(color.substring(0, 2), 16);
groundOverlay.opacity = Math.round((255 - transparency) / 2.55);
} else {
groundOverlay.opacity = 100;
}
// Call the appropriate function to create the overlay
if (!!parserOptions.createOverlay) {
parserOptions.createOverlay(groundOverlay, doc);
} else {
createOverlay(groundOverlay, doc);
}
}
if (!!doc.bounds) {
doc.internals.bounds = doc.internals.bounds || new google.maps.LatLngBounds();
doc.internals.bounds.union(doc.bounds);
}
if (!!doc.styles || !!doc.markers || !!doc.overlays) {
doc.internals.parserOnly = false;
}
doc.internals.remaining -= 1;
if (doc.internals.remaining === 0) {
// We're done processing this set of KML documents
// Options that get invoked after parsing completes
if (!!doc.internals.bounds) {
parserOptions.map.fitBounds(doc.internals.bounds);
}
if (parserOptions.afterParse) {
parserOptions.afterParse(doc.internals.docSet);
}
if (!doc.internals.parserOnly) {
// geoXML3 is not being used only as a real-time parser, so keep the parsed documents around
docs.concat(doc.internals.docSet);
}
}
}
};
var processStyles = function (doc) {
var stdRegEx = /\/(red|blue|green|yellow|lightblue|purple|pink|orange)(-dot)?\.png/;
for (var styleID in doc.styles) {
if (!!doc.styles[styleID].href) {
// Init the style object with a standard KML icon
doc.styles[styleID].icon = new google.maps.MarkerImage(
doc.styles[styleID].href,
new google.maps.Size(32, 32),
new google.maps.Point(0, 0),
new google.maps.Point(16, 12)
);
// Look for a predictable shadow
if (stdRegEx.test(doc.styles[styleID].href)) {
// A standard GMap-style marker icon
doc.styles[styleID].shadow = new google.maps.MarkerImage(
'http://maps.google.com/mapfiles/ms/micons/msmarker.shadow.png',
new google.maps.Size(59, 32),
new google.maps.Point(0, 0),
new google.maps.Point(16, 12));
} else if (doc.styles[styleID].href.indexOf('-pushpin.png') > -1) {
// Pushpin marker icon
doc.styles[styleID].shadow = new google.maps.MarkerImage(
'http://maps.google.com/mapfiles/ms/micons/pushpin_shadow.png',
new google.maps.Size(59, 32),
new google.maps.Point(0, 0),
new google.maps.Point(16, 12));
} else {
// Other MyMaps KML standard icon
doc.styles[styleID].shadow = new google.maps.MarkerImage(
doc.styles[styleID].href.replace('.png', '.shadow.png'),
new google.maps.Size(59, 32),
new google.maps.Point(0, 0),
new google.maps.Point(16, 12));
}
}
}
};
var createMarker = function (placemark, doc) {
// create a Marker to the map from a placemark KML object
// Load basic marker properties
var markerOptions = geoXML3.combineOptions(parserOptions.markerOptions, {
map: parserOptions.map,
position: new google.maps.LatLng(placemark.point.lat, placemark.point.lng),
title: placemark.name,
zIndex: Math.round(-placemark.point.lat * 100000),
icon: placemark.style.icon,
shadow: placemark.style.shadow
});
// Create the marker on the map
var marker = new google.maps.Marker(markerOptions);
// Set up and create the infowindow
var infoWindowOptions = geoXML3.combineOptions(parserOptions.infoWindowOptions, {
content: '<div class="infowindow"><h3>' + placemark.name +
'</h3><div>' + placemark.description + '</div></div>',
pixelOffset: new google.maps.Size(0, 2)
});
marker.infoWindow = new google.maps.InfoWindow(infoWindowOptions);
// Infowindow-opening event handler
google.maps.event.addListener(marker, 'click', function() {
if (!!parserOptions.singleInfoWindow) {
if (!!lastMarker && !!lastMarker.infoWindow) {
lastMarker.infoWindow.close();
}
lastMarker = this;
}
this.infoWindow.open(this.map, this);
});
if (!!doc) {
doc.markers = doc.markers || [];
doc.markers.push(marker);
}
return marker;
};
var createOverlay = function (groundOverlay, doc) {
// Add a ProjectedOverlay to the map from a groundOverlay KML object
if (!window.ProjectedOverlay) {
throw 'geoXML3 error: ProjectedOverlay not found while rendering GroundOverlay from KML';
}
var bounds = new google.maps.LatLngBounds(
new google.maps.LatLng(groundOverlay.latLonBox.south, groundOverlay.latLonBox.west),
new google.maps.LatLng(groundOverlay.latLonBox.north, groundOverlay.latLonBox.east)
);
var overlayOptions = geoXML3.combineOptions(parserOptions.overlayOptions, {percentOpacity: groundOverlay.opacity});
var overlay = new ProjectedOverlay(parserOptions.map, groundOverlay.icon.href, bounds, overlayOptions);
if (!!doc) {
doc.overlays = doc.overlays || [];
doc.overlays.push(overlay);
}
return
};
return {
// Expose some properties and methods
options: parserOptions,
docs: docs,
parse: parse,
hideDocument: hideDocument,
showDocument: showDocument,
processStyles: processStyles,
createMarker: createMarker,
createOverlay: createOverlay
};
};
// End of KML Parser
// Helper objects and functions
// Log a message to the debugging console, if one exists
geoXML3.log = function(msg) {
if (!!window.console) {
console.log(msg);
}
};
// Combine two options objects, a set of default values and a set of override values
geoXML3.combineOptions = function (overrides, defaults) {
var result = {};
if (!!overrides) {
for (var prop in overrides) {
if (overrides.hasOwnProperty(prop)) {
result[prop] = overrides[prop];
}
}
}
if (!!defaults) {
for (prop in defaults) {
if (defaults.hasOwnProperty(prop) && (result[prop] === undefined)) {
result[prop] = defaults[prop];
}
}
}
return result;
};
// Retrieve a text document from url and pass it to callback as a string
geoXML3.fetchers = [];
geoXML3.fetchXML = function (url, callback) {
function timeoutHandler() {
callback();
};
var xhrFetcher;
if (!!geoXML3.fetchers.length) {
xhrFetcher = geoXML3.fetchers.pop();
} else {
if (!!window.XMLHttpRequest) {
xhrFetcher = new window.XMLHttpRequest(); // Most browsers
} else if (!!window.ActiveXObject) {
xhrFetcher = new window.ActiveXObject('Microsoft.XMLHTTP'); // Some IE
}
}
if (!xhrFetcher) {
geoXML3.log('Unable to create XHR object');
callback(null);
} else {
xhrFetcher.open('GET', url, true);
xhrFetcher.onreadystatechange = function () {
if (xhrFetcher.readyState === 4) {
// Retrieval complete
if (!!xhrFetcher.timeout)
clearTimeout(xhrFetcher.timeout);
if (xhrFetcher.status >= 400) {
geoXML3.log('HTTP error ' + xhrFetcher.status + ' retrieving ' + url);
callback();
} else {
// Returned successfully
callback(xhrFetcher.responseXML);
}
// We're done with this fetcher object
geoXML3.fetchers.push(xhrFetcher);
}
};
xhrFetcher.timeout = setTimeout(timeoutHandler, 60000);
xhrFetcher.send(null);
}
};
//nodeValue: Extract the text value of a DOM node, with leading and trailing whitespace trimmed
geoXML3.nodeValue = function(node) {
if (!node) {
return '';
} else {
return (node.innerText || node.text || node.textContent).trim();
}
};