-
Notifications
You must be signed in to change notification settings - Fork 73
/
Copy pathindex.html
616 lines (539 loc) · 21.2 KB
/
index.html
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
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
<html>
<head>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&key=[your_api_key]"></script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
var map;
var directionsDisplay = null;
var directionsService;
var polylinePath;
var nodes = [];
var prevNodes = [];
var markers = [];
var durations = [];
// Initialize google maps
function initializeMap() {
// Map options
var opts = {
center: new google.maps.LatLng(54, -4.4),
zoom: 6,
streetViewControl: false,
mapTypeControl: false,
};
map = new google.maps.Map(document.getElementById('map-canvas'), opts);
// Create map click event
google.maps.event.addListener(map, 'click', function(event) {
// Add destination (max 9)
if (nodes.length >= 9) {
alert('Max destinations added');
return;
}
// If there are directions being shown, clear them
clearDirections();
// Add a node to map
marker = new google.maps.Marker({position: event.latLng, map: map});
markers.push(marker);
// Store node's lat and lng
nodes.push(event.latLng);
// Update destination count
$('#destinations-count').html(nodes.length);
});
// Add "my location" button
var myLocationDiv = document.createElement('div');
new getMyLocation(myLocationDiv, map);
map.controls[google.maps.ControlPosition.TOP_RIGHT].push(myLocationDiv);
function getMyLocation(myLocationDiv, map) {
var myLocationBtn = document.createElement('button');
myLocationBtn.innerHTML = 'My Location';
myLocationBtn.className = 'large-btn';
myLocationBtn.style.margin = '5px';
myLocationBtn.style.opacity = '0.95';
myLocationBtn.style.borderRadius = '3px';
myLocationDiv.appendChild(myLocationBtn);
google.maps.event.addDomListener(myLocationBtn, 'click', function() {
navigator.geolocation.getCurrentPosition(function(success) {
map.setCenter(new google.maps.LatLng(success.coords.latitude, success.coords.longitude));
map.setZoom(12);
});
});
}
}
// Get all durations depending on travel type
function getDurations(callback) {
var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix({
origins: nodes,
destinations: nodes,
travelMode: google.maps.TravelMode[$('#travel-type').val()],
avoidHighways: parseInt($('#avoid-highways').val()) > 0 ? true : false,
avoidTolls: false,
}, function(distanceData) {
// Create duration data array
var nodeDistanceData;
for (originNodeIndex in distanceData.rows) {
nodeDistanceData = distanceData.rows[originNodeIndex].elements;
durations[originNodeIndex] = [];
for (destinationNodeIndex in nodeDistanceData) {
if (durations[originNodeIndex][destinationNodeIndex] = nodeDistanceData[destinationNodeIndex].duration == undefined) {
alert('Error: couldn\'t get a trip duration from API');
return;
}
durations[originNodeIndex][destinationNodeIndex] = nodeDistanceData[destinationNodeIndex].duration.value;
}
}
if (callback != undefined) {
callback();
}
});
}
// Removes markers and temporary paths
function clearMapMarkers() {
for (index in markers) {
markers[index].setMap(null);
}
prevNodes = nodes;
nodes = [];
if (polylinePath != undefined) {
polylinePath.setMap(null);
}
markers = [];
$('#ga-buttons').show();
}
// Removes map directions
function clearDirections() {
// If there are directions being shown, clear them
if (directionsDisplay != null) {
directionsDisplay.setMap(null);
directionsDisplay = null;
}
}
// Completely clears map
function clearMap() {
clearMapMarkers();
clearDirections();
$('#destinations-count').html('0');
}
// Initial Google Maps
google.maps.event.addDomListener(window, 'load', initializeMap);
// Create listeners
$(document).ready(function() {
$('#clear-map').click(clearMap);
// Start GA
$('#find-route').click(function() {
if (nodes.length < 2) {
if (prevNodes.length >= 2) {
nodes = prevNodes;
} else {
alert('Click on the map to select destination points');
return;
}
}
if (directionsDisplay != null) {
directionsDisplay.setMap(null);
directionsDisplay = null;
}
$('#ga-buttons').hide();
// Get route durations
getDurations(function(){
$('.ga-info').show();
// Get config and create initial GA population
ga.getConfig();
var pop = new ga.population();
pop.initialize(nodes.length);
var route = pop.getFittest().chromosome;
ga.evolvePopulation(pop, function(update) {
$('#generations-passed').html(update.generation);
$('#best-time').html((update.population.getFittest().getDistance() / 60).toFixed(2) + ' Mins');
// Get route coordinates
var route = update.population.getFittest().chromosome;
var routeCoordinates = [];
for (index in route) {
routeCoordinates[index] = nodes[route[index]];
}
routeCoordinates[route.length] = nodes[route[0]];
// Display temp. route
if (polylinePath != undefined) {
polylinePath.setMap(null);
}
polylinePath = new google.maps.Polyline({
path: routeCoordinates,
strokeColor: "#0066ff",
strokeOpacity: 0.75,
strokeWeight: 2,
});
polylinePath.setMap(map);
}, function(result) {
// Get route
route = result.population.getFittest().chromosome;
// Add route to map
directionsService = new google.maps.DirectionsService();
directionsDisplay = new google.maps.DirectionsRenderer();
directionsDisplay.setMap(map);
var waypts = [];
for (var i = 1; i < route.length; i++) {
waypts.push({
location: nodes[route[i]],
stopover: true
});
}
// Add final route to map
var request = {
origin: nodes[route[0]],
destination: nodes[route[0]],
waypoints: waypts,
travelMode: google.maps.TravelMode[$('#travel-type').val()],
avoidHighways: parseInt($('#avoid-highways').val()) > 0 ? true : false,
avoidTolls: false
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
clearMapMarkers();
});
});
});
});
});
// GA code
var ga = {
// Default config
"crossoverRate": 0.5,
"mutationRate": 0.1,
"populationSize": 50,
"tournamentSize": 5,
"elitism": true,
"maxGenerations": 50,
"tickerSpeed": 60,
// Loads config from HTML inputs
"getConfig": function() {
ga.crossoverRate = parseFloat($('#crossover-rate').val());
ga.mutationRate = parseFloat($('#mutation-rate').val());
ga.populationSize = parseInt($('#population-size').val()) || 50;
ga.elitism = parseInt($('#elitism').val()) || false;
ga.maxGenerations = parseInt($('#maxGenerations').val()) || 50;
},
// Evolves given population
"evolvePopulation": function(population, generationCallBack, completeCallBack) {
// Start evolution
var generation = 1;
var evolveInterval = setInterval(function() {
if (generationCallBack != undefined) {
generationCallBack({
population: population,
generation: generation,
});
}
// Evolve population
population = population.crossover();
population.mutate();
generation++;
// If max generations passed
if (generation > ga.maxGenerations) {
// Stop looping
clearInterval(evolveInterval);
if (completeCallBack != undefined) {
completeCallBack({
population: population,
generation: generation,
});
}
}
}, ga.tickerSpeed);
},
// Population class
"population": function() {
// Holds individuals of population
this.individuals = [];
// Initial population of random individuals with given chromosome length
this.initialize = function(chromosomeLength) {
this.individuals = [];
for (var i = 0; i < ga.populationSize; i++) {
var newIndividual = new ga.individual(chromosomeLength);
newIndividual.initialize();
this.individuals.push(newIndividual);
}
};
// Mutates current population
this.mutate = function() {
var fittestIndex = this.getFittestIndex();
for (index in this.individuals) {
// Don't mutate if this is the elite individual and elitism is enabled
if (ga.elitism != true || index != fittestIndex) {
this.individuals[index].mutate();
}
}
};
// Applies crossover to current population and returns population of offspring
this.crossover = function() {
// Create offspring population
var newPopulation = new ga.population();
// Find fittest individual
var fittestIndex = this.getFittestIndex();
for (index in this.individuals) {
// Add unchanged into next generation if this is the elite individual and elitism is enabled
if (ga.elitism == true && index == fittestIndex) {
// Replicate individual
var eliteIndividual = new ga.individual(this.individuals[index].chromosomeLength);
eliteIndividual.setChromosome(this.individuals[index].chromosome.slice());
newPopulation.addIndividual(eliteIndividual);
} else {
// Select mate
var parent = this.tournamentSelection();
// Apply crossover
this.individuals[index].crossover(parent, newPopulation);
}
}
return newPopulation;
};
// Adds an individual to current population
this.addIndividual = function(individual) {
this.individuals.push(individual);
};
// Selects an individual with tournament selection
this.tournamentSelection = function() {
// Randomly order population
for (var i = 0; i < this.individuals.length; i++) {
var randomIndex = Math.floor(Math.random() * this.individuals.length);
var tempIndividual = this.individuals[randomIndex];
this.individuals[randomIndex] = this.individuals[i];
this.individuals[i] = tempIndividual;
}
// Create tournament population and add individuals
var tournamentPopulation = new ga.population();
for (var i = 0; i < ga.tournamentSize; i++) {
tournamentPopulation.addIndividual(this.individuals[i]);
}
return tournamentPopulation.getFittest();
};
// Return the fittest individual's population index
this.getFittestIndex = function() {
var fittestIndex = 0;
// Loop over population looking for fittest
for (var i = 1; i < this.individuals.length; i++) {
if (this.individuals[i].calcFitness() > this.individuals[fittestIndex].calcFitness()) {
fittestIndex = i;
}
}
return fittestIndex;
};
// Return fittest individual
this.getFittest = function() {
return this.individuals[this.getFittestIndex()];
};
},
// Individual class
"individual": function(chromosomeLength) {
this.chromosomeLength = chromosomeLength;
this.fitness = null;
this.chromosome = [];
// Initialize random individual
this.initialize = function() {
this.chromosome = [];
// Generate random chromosome
for (var i = 0; i < this.chromosomeLength; i++) {
this.chromosome.push(i);
}
for (var i = 0; i < this.chromosomeLength; i++) {
var randomIndex = Math.floor(Math.random() * this.chromosomeLength);
var tempNode = this.chromosome[randomIndex];
this.chromosome[randomIndex] = this.chromosome[i];
this.chromosome[i] = tempNode;
}
};
// Set individual's chromosome
this.setChromosome = function(chromosome) {
this.chromosome = chromosome;
};
// Mutate individual
this.mutate = function() {
this.fitness = null;
// Loop over chromosome making random changes
for (index in this.chromosome) {
if (ga.mutationRate > Math.random()) {
var randomIndex = Math.floor(Math.random() * this.chromosomeLength);
var tempNode = this.chromosome[randomIndex];
this.chromosome[randomIndex] = this.chromosome[index];
this.chromosome[index] = tempNode;
}
}
};
// Returns individuals route distance
this.getDistance = function() {
var totalDistance = 0;
for (index in this.chromosome) {
var startNode = this.chromosome[index];
var endNode = this.chromosome[0];
if ((parseInt(index) + 1) < this.chromosome.length) {
endNode = this.chromosome[(parseInt(index) + 1)];
}
totalDistance += durations[startNode][endNode];
}
totalDistance += durations[startNode][endNode];
return totalDistance;
};
// Calculates individuals fitness value
this.calcFitness = function() {
if (this.fitness != null) {
return this.fitness;
}
var totalDistance = this.getDistance();
this.fitness = 1 / totalDistance;
return this.fitness;
};
// Applies crossover to current individual and mate, then adds it's offspring to given population
this.crossover = function(individual, offspringPopulation) {
var offspringChromosome = [];
// Add a random amount of this individual's genetic information to offspring
var startPos = Math.floor(this.chromosome.length * Math.random());
var endPos = Math.floor(this.chromosome.length * Math.random());
var i = startPos;
while (i != endPos) {
offspringChromosome[i] = individual.chromosome[i];
i++
if (i >= this.chromosome.length) {
i = 0;
}
}
// Add any remaining genetic information from individual's mate
for (parentIndex in individual.chromosome) {
var node = individual.chromosome[parentIndex];
var nodeFound = false;
for (offspringIndex in offspringChromosome) {
if (offspringChromosome[offspringIndex] == node) {
nodeFound = true;
break;
}
}
if (nodeFound == false) {
for (var offspringIndex = 0; offspringIndex < individual.chromosome.length; offspringIndex++) {
if (offspringChromosome[offspringIndex] == undefined) {
offspringChromosome[offspringIndex] = node;
break;
}
}
}
}
// Add chromosome to offspring and add offspring to population
var offspring = new ga.individual(this.chromosomeLength);
offspring.setChromosome(offspringChromosome);
offspringPopulation.addIndividual(offspring);
};
},
};
</script>
</head>
<body>
<div>
<div id="map-canvas" style="width:660px; height:560px;"></div>
<div class="hr vpad"></div>
<div>
<table>
<tr>
<td colspan="2"><b>Configuration</b></td>
</tr>
<tr>
<td>Travel Mode: </td>
<td>
<select id="travel-type">
<option value="DRIVING">Car</option>
<option value="BICYCLING">Bicycle</option>
<option value="WALKING">Walking</option>
</select>
</td>
</tr>
<tr>
<td>Avoid Highways: </td>
<td>
<select id="avoid-highways">
<option value="1">Enabled</option>
<option value="0" selected="selected">Disabled</option>
</select>
</td>
</tr>
<tr>
<td>Population Size: </td>
<td>
<select id="population-size">
<option value="5">5</option>
<option value="10">10</option>
<option value="20">20</option>
<option value="50" selected="selected">50</option>
<option value="100">100</option>
<option value="200">200</option>
</select>
</td>
</tr>
<tr>
<td>Mutation Rate: </td>
<td>
<select id="mutation-rate">
<option value="0.00">0.00</option>
<option value="0.05">0.01</option>
<option value="0.05">0.05</option>
<option value="0.1" selected="selected">0.1</option>
<option value="0.2">0.2</option>
<option value="0.4">0.4</option>
<option value="0.7">0.7</option>
<option value="1">1.0</option>
</select>
</td>
</tr>
<tr>
<td>Crossover Rate: </td>
<td>
<select id="crossover-rate">
<option value="0.0">0.0</option>
<option value="0.1">0.1</option>
<option value="0.2">0.2</option>
<option value="0.3">0.3</option>
<option value="0.4">0.4</option>
<option value="0.5" selected="selected">0.5</option>
<option value="0.6">0.6</option>
<option value="0.7">0.7</option>
<option value="0.8">0.8</option>
<option value="0.9">0.9</option>
<option value="1">1.0</option>
</select>
</td>
</tr>
<tr>
<td>Elitism: </td>
<td>
<select id="elitism">
<option value="1" selected="selected">Enabled</option>
<option value="0">Disabled</option>
</select>
</td>
</tr>
<tr>
<td>Max Generations: </td>
<td>
<select id="generations">
<option value="20">20</option>
<option value="50" selected="selected">50</option>
<option value="100">100</option>
</select>
</td>
</tr>
<tr>
<td colspan="2"><b>Debug Info</b></td>
</tr>
<tr>
<td>Destinations Count: </td>
<td id="destinations-count">0</td>
</tr>
<tr class="ga-info" style="display:none;">
<td>Generations: </td><td id="generations-passed">0</td>
</tr>
<tr class="ga-info" style="display:none;">
<td>Best Time: </td><td id="best-time">?</td>
</tr>
<tr id="ga-buttons">
<td colspan="2"><button id="find-route">Start</button> <button id="clear-map">Clear</button></td>
</tr>
</table>
</div>
</div>
</body>
</html>