-
Notifications
You must be signed in to change notification settings - Fork 52
/
batch_geocoding_using_google_maps.html
584 lines (493 loc) · 20.1 KB
/
batch_geocoding_using_google_maps.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
<html>
<head>
<title>Batch Geocoding Using Google Mapping API</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js"></script>
<style>
#status_div {
position: absolute;
left: 600px;
top: 10px;
border: 1px solid black;
background-color: white;
padding: 5px;
}
#input_div {
display: inline-block;
}
#results_div {
display: inline-block;
}
#processing_errors {
font-family: monospace;
}
h1 {
background-color: #666;
color: white;
font-family: sans-serif;
padding: 5px;
margin: 0px;
}
body {
background-color: #F8F8F8;
font-family: sans-serif;
font-size: 12pt;
padding: 0px;
margin: 0px;
}
.body_container {
padding-left: 10px;
padding-right: 10px;
}
select {
font-family: sans-serif;
font-size: 12pt;
}
.overlay {
position: absolute;
top : 65px;
left : 100px;
background-color : white;
height : 600px;
width : 800px;
border : 1px solid black;
margin: 0px;
}
</style>
<script>
var isChrome = !!window.chrome
if (isChrome){
alert('Alert Chrome User:\nIf you are running this from your local computer, Chrome will not work.\n\n Please use Firefox or IE. \n\nIf you host the page on a web server, it should work.');
}
// Two Google Maps API objects for reuse throughout
var geocoder = new google.maps.Geocoder();
var directionsService = new google.maps.DirectionsService();
// Global results arrays
var lines = new Array(); // Hold each of the initial addresses to geocode
var ordered_results = new Array(); // Hold results lines
var unprocessed_results = new Array(); // Hold any lines where no result came back from Google API
var total_count;
var j = 0;
var consecutive_over_quota = 0;
var child_windows = new Array();
var child_windows_opened = 0;
var child_windows_finished = 0;
/*
Google Geocoding API gets really slow after 200 addresses, but that seems to be reset for each page load. To get around this, the master will open the correct number of iframes in parallel and trigger them off.
*/
// Optimization settings
var file_name = "batch_geocoding_using_google_maps_wip.html"; // Necessary to open the child iframes
var max_lines_for_performance = 3000; // Limit of lines per batch
var split_count = 150; // Number of addresses to run in each child window
var mode = 'geocode'; // Processing mode switch
var mode_headers = {};
mode_headers['geocode'] = "address|google_address_match|lon|lat";
mode_headers['reverse_geocode'] = "lon,lat|google_address_match|lon|lat";
mode_headers['directions'] = "start_address|end_address|start_lon|start_lat|end_lon|end_lat|distance_miles|duration_minutes";
var master_or_child = 'master'; // Switch so iframes behave differently
// Looks for child=true flag is present
function detectChild(){
if( window.location.search.indexOf('?child=true') >= 0 ){
master_or_child = 'child';
}
if (window.location.search.indexOf('&directions=true') >= 0){
mode = 'directions';
}
if (window.location.search.indexOf('&reverse=true') >= 0){
mode = 'reverse_geocode';
}
}
function launchProcess() {
j = 0;
lines = processList();
consecutive_over_quota = 0;
child_windows_opened = 0;
child_windows_finished = 0;
// Pop up warning if over max
if(lines.length > max_lines_for_performance) {
alert("You have entered " + lines.length + " lines\nPlease reduce to 3000 or less and rerun.");
return false;
}
// Split them up and open new windows with child parameter
if(master_or_child == 'master'){
num_children = lines.length / split_count;
num_children = Math.ceil(num_children);
//alert("Need to run " + num_children + " windows for max efficiency.\n Once finished, they will close and results will be in original window.");
// Open Iframes for same effect
for(i=0;i<num_children;i++){
child_windows[i] = document.createElement('iframe');
new_window_uri = '?child=true';
if(mode == 'directions'){
new_window_uri += '&directions=true';
}
if(mode == 'reverse_geocode'){
new_window_uri += '&reverse=true';
}
child_windows[i].src = new_window_uri;
document.body.appendChild(child_windows[i]);
$( child_windows[i]).hide();
}
}
// Reset unprocessed and hide
unprocessed_results = new Array();
ordered_results = new Array();
$("#processing_errors").hide();
$("#status_div").show();
$("#processing_errors").html("<p style='font-family: serif;'>Unprocessed Addresses<p>");
if(master_or_child == 'child'){
// Fire off first address to be processed, each returned result will trigger next via event handler
processAddress(ordered_results,unprocessed_results);
}
}
// Grab initial list of all addresses, trim it down
function processList() {
var output_array = new Array();
var input_text = $("#address_entry").val() ;
var lines = new Array();
lines = input_text.split("\n");
$("#results").val("");
for(i=0;i<lines.length;i++){
// Ignore blank lines
if(lines[i].trim().length > 0){
output_array.push( lines[i].trim() );
}
}
total_count = output_array.length; // Set global total_count
// Smaller split if less than the upper bound for Google API
if (total_count < split_count){
split_count = 25;
}
return output_array;
}
// Create a custom event handler for every returned address
// On return of first address, fire off the next address
$( document ).on(
"addressReturn",
{count : j},
function (event) {
//Increment j
console.log("Address Return event on Address " + j);
// Update on screen counter
$("#status_div").html("<p>" + j + " of " + total_count + " processed");
if( j == total_count ){
displayResults();
$("#status_div").html("<p>Processing of " + total_count + " completed <br> with " + unprocessed_results.length + " errors");
//Put errors in the processing_errors div if there were any
if(unprocessed_results.length > 0){
for(i=0;i<unprocessed_results.length;i++){
$("#processing_errors").append ( unprocessed_results[i] + "<br>" );
}
$("#processing_errors").show();
}
}
else{
setTimeout( function() { processAddress(ordered_results,unprocessed_results); } , 750 + (consecutive_over_quota*50));
}
}
);
$( document ).on (
"windowOpened",
{total_opened : child_windows_opened},
function (event) {
child_windows_opened++;
num_children = child_windows.length;
/*
// This is where everything happens after all the windows are loaded
*/
if(child_windows_opened == num_children){
// Put all the results in the child windows
remaining_lines = lines.length;
for(i=0;i<num_children;i++){
child_input = $(child_windows[num_children-1-i].contentDocument).contents().find("#address_entry");
if(remaining_lines < split_count){
limit = (i*split_count)+remaining_lines;
}
else {
limit = (i+1)*split_count;
}
for(var j=0+(i*split_count);j<limit;j++){
child_input.val( child_input.val() + lines[j] + "\n");
}
remaining_lines = remaining_lines - split_count;
}
// Fire off the launch process on the children
for(i=0;i<num_children;i++){
child_windows[i].contentDocument.launch();
}
}
}
);
// Listener on the master that is pinged every time an iframe finishes. Once all are finished, it grabs them all and combines for the final result
$ ( document ).on(
"windowFinished",
{total_opened : child_windows_opened},
function (event){
child_windows_finished++;
if(child_windows_finished == child_windows_opened){
num_children = child_windows.length;
var results_text = mode_headers[mode] + "\n";
for(i=0;i<num_children;i++){
child_results = $(child_windows[i].contentDocument).contents().find("#results");
results_text = results_text + child_results.val();
}
$("#master_results").text(results_text);
$("#master_results_div").show();
}
}
);
$( document ).on (
"incrementMasterCounter",
{master_counter: j},
function (event){
j++;
$("#status_div").html("<p>" + j + " of " + total_count + " processed");
if( j == total_count ){
displayResults();
$("#status_div").html("");
$("#status_div").hide();
//$("#status_div").html("<p>Processing of " + total_count + " completed");
//$("#results_div").show();
}
}
);
function processAddress (o_results, u_results) {
// Need to wrap the whole geocoder in ANOTHER function so that the address can be assigned at the call time and brought as a value in the callback function in the geocoder callback (JS callback and scope MADNESS)
function geocodeAddress(address,order){
var newDate = new Date();
console.log("Geocode launched: " + address + " at " + newDate.toLocaleTimeString());
geocoder.geocode(
{'address' : address},
function(results, status){
if(status == google.maps.GeocoderStatus.OK){
if(consecutive_over_quota > 0) {consecutive_over_quota = consecutive_over_quota-.25; }
console.log(results);
output_line = address + "|" + results[0].formatted_address + "|" + results[0].geometry.location.lng().toFixed(4) + "|" + results[0].geometry.location.lat().toFixed(4);
//$("#results").val( $("#results").val() + output_line + "\n");
o_results[order] = output_line;
// Display result in results window
$("#results").val( $("#results").val() + output_line + "\n");
j++;
window.parent.document.childAddressReturned(); // trigger event handler for master counter on parent
$( document ).trigger( "addressReturn");
}
// Add a two-second delay and resend request
else if (status == "OVER_QUERY_LIMIT"){
consecutive_over_quota++;
delay_time = 1500 + (consecutive_over_quota*500);
console.log("Request " + j + " over query limit. Delaying " + delay_time + " milliseconds and retrying");
setTimeout( function () { $( document ).trigger( "addressReturn"); }, delay_time);
}
else{
console.log ( "Error with geocoding request: " + status);
o_results[order] = address + "|";
j++;
window.parent.document.childAddressReturned(); // trigger event handler for master counter on parent
$( document ).trigger( "addressReturn");
u_results.push(address);
}
}
);
};
function reverseGeocodeAddress(lonlat,order){
var loc = {lng: parseFloat(lonlat[0]), lat: parseFloat(lonlat[1])};
geocoder.geocode(
{'location' : loc},
function(results, status){
if(status == google.maps.GeocoderStatus.OK){
if(consecutive_over_quota > 0) {consecutive_over_quota = consecutive_over_quota-.25; }
console.log(results);
output_line = lonlat[0] + "," + lonlat[1] + "|" + results[0].formatted_address + "|" + results[0].geometry.location.lng().toFixed(4) + "|" + results[0].geometry.location.lat().toFixed(4);
//$("#results").val( $("#results").val() + output_line + "\n");
o_results[order] = output_line;
// Display result in results window
$("#results").val( $("#results").val() + output_line + "\n");
j++;
window.parent.document.childAddressReturned(); // trigger event handler for master counter on parent
$( document ).trigger( "addressReturn");
}
// Add a two-second delay and resend request
else if (status == "OVER_QUERY_LIMIT"){
consecutive_over_quota++;
delay_time = 1500 + (consecutive_over_quota*500);
console.log("Request " + j + " over query limit. Delaying " + delay_time + " milliseconds and retrying");
setTimeout( function () { $( document ).trigger( "addressReturn"); }, delay_time);
}
else{
console.log ( "Error with geocoding request: " + status);
o_results[order] = address + "|";
j++;
window.parent.document.childAddressReturned(); // trigger event handler for master counter on parent
$( document ).trigger( "addressReturn");
u_results.push(address);
}
}
);
};
function getDirectionsBtwAddresses(address_pair,order){
var dir_request = {
origin: address_pair[0],
destination : address_pair[1],
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.IMPERIAL
};
directionsService.route(
dir_request,
function(results, status){
if(status == google.maps.DirectionsStatus.OK){
if(consecutive_over_quota > 0) {consecutive_over_quota = consecutive_over_quota-.25; }
console.log(results.routes[0]);
// Only one leg with no waypoints defined, which we don't
first_leg = results.routes[0].legs[0];
distance = first_leg.distance.value; // in meters
distance_miles = distance * .000621371;
duration = first_leg.duration.value; // in seconds
duration_mins = duration / 60;
start_lon = first_leg.start_location.lng();
start_lat = first_leg.start_location.lat();
end_lon = first_leg.end_location.lng();
end_lat = first_leg.end_location.lat();
output_line = address_pair[0] + "|" + address_pair[1] + "|" + start_lon.toFixed(4) + "|" + start_lat.toFixed(4) + "|" + end_lon.toFixed(4) + "|" + end_lat.toFixed(4) + "|" + distance_miles.toFixed(4) + "|" + duration_mins.toFixed(4);
$("#results").val( $("#results").val() + output_line + "\n");
o_results[order] = output_line;
j++;
window.parent.document.childAddressReturned(); // trigger event handler for master counter on parent
$( document ).trigger( "addressReturn");
}
// Add a two-second delay and resend request
else if (status == "OVER_QUERY_LIMIT"){
consecutive_over_quota++;
delay_time = 1500 + (consecutive_over_quota*500);
console.log("Request " + j + " over query limit. Delaying " + delay_time + " milliseconds and retrying");
setTimeout( function () { $( document ).trigger( "addressReturn"); }, delay_time);
}
else {
console.log ( "Error with geocoding request: " + status);
o_results[order] = address_pair[0] + "|" + address_pair[1] + "|";
window.parent.document.childAddressReturned(); // trigger event handler for master counter on parent
$( document ).trigger( "addressReturn");
u_results.push(address_pair[0] + "|" + address_pair[1]);
j++;
}
}
);
};
// Actual meat of the processAddress, depending on the mode
switch (mode) {
// Geocoding rather than directions
case 'geocode':
console.log('Regular address geocode mode');
//console.log(lines[i]);
// j being the global counter
geocodeAddress(lines[j],j); // Scope jack function -- by running this in the external function we can pass the original address values
break;
case 'reverse_geocode':
console.log('Reverse geocode mode on Lon,Lat pairs');
lonlat = lines[j].split(",");
//console.log(lines[i]);
// j being the global counter
reverseGeocodeAddress(lonlat,j); // Scope jack function -- by running this in the external function we can pass the original address values
break;
// Get distance and drive time for the two places. Grab Lon / Lat too if possible.
case 'directions':
// Split into two from comma
console.log('Directions between two addresses mode');
console.log('j is ' + j + ' right now');
address_pair = lines[j].split("|");
// Only run if there are two listed points in the line
if(address_pair.length == 2){
getDirectionsBtwAddresses( address_pair, j );
}
break;
}
//console.log(results);
return o_results;
};
// Tells the master that the child iframe has finished, also logs everything to the console for checking
function displayResults(){
console.log(ordered_results);
console.log(unprocessed_results);
if(master_or_child == 'child'){
window.parent.document.processingFinished();
}
}
function hideOverlay(){
$("#master_results_div").hide();
//$("#overlay").html("");
}
function modeChange(){
mode = $("#mode_select").val(); // Set the global mode
console.log("MOde set to " + mode);
}
/*
All of the prep work when the master or the child loads
*/
$(document).ready(
function() {
// Sets the children iframe into child mode
detectChild();
// Add launchProcess to DOM for the children so it can be launched by parent
document.launch = launchProcess;
// Allows children to ping master when they have opened successfully
document.windowLoaded = function (){ $(document).trigger( "windowOpened"); };
// Allows children to ping master when they have completed
document.processingFinished = function () { $(document).trigger("windowFinished"); };
// Allows children to ping master when a single address returns successfully
document.childAddressReturned = function(){ $(document).trigger("incrementMasterCounter"); }
// Set default mode to geocode
$("#mode_select").val('geocode');
// Clear results
$("#results").val("");
// Onchange of the select box set the mode
$("#mode_select").change(modeChange);
// Mode headers (maybe hide this altogether until the end?
$("#headers").text("address|google_address_match|lon|lat");
// Hide divs
$("#processing_errors").hide();
$("#status_div").hide();
if( master_or_child == 'master'){ $("#results_div").hide(); }
$("#master_results_div").hide();
// Ping the parent when the child iframe load completely per jQuery
if( master_or_child == 'child'){
window.parent.document.windowLoaded();
}
}
);
</script>
</head>
<body>
<h1>Batch Geocoding Using Google Mapping API</h1>
<div class='body_container'>
<p>Use this tool to find the longitude and latitude of up to 3000 addresses at a time in approximately 5 minutes, or the driving distance and time between two addresses.
<p>Mode Description:
<p><ul>
<li>Single Addresses: takes a list of addresses, one per line</li>
<li>Shorted Driving Distance + Estimated Time: Takes a list of address pairs, two per line, separated by |</li>
</ul>
<p>Choose Mode:
<select name='mode_select' id='mode_select'>
<option value='geocode' selected>Geocode Single Addresses</option>
<option value='reverse_geocode'>Reverse Geocode Lon,Lat Pairs</option>
<option value='directions'>Shortest Driving Distance + Estimated Time</option>
</select>
<div id='wrapper_div'>
<div id='input_div'><b>Input Addresses Below</b><p> </p><textarea id='address_entry' name='address_entry' rows=20 cols=90></textarea></div>
<div id='results_div'><b>Geocoding Results</b><p id='headers'></p><textarea id='results' name='results' rows=20 cols=75></textarea></div>
</div>
<p><button onclick='launchProcess();'>Geocode My Addresses</button>
<div id='status_div'>
</div>
<div id='processing_errors'>
<p style='font-family: serif;'>Unprocessed Addresses
<p>
</div>
<div id='master_results_div' class='overlay'>
<h1>Results</h1>
<div style='padding-left:10px;padding-right:10px;'>
<p>Copy into a text file or Excel. Each item is separated by |
<textarea id='master_results' name='master_results' rows=25 cols=90></textarea>
<p align='right'><button onclick='hideOverlay();'>Close</button><br>
</div>
</div>
</div>
</body>
</html>