1. Home
  2. Computing & Technology
  3. JavaScript

Distance Calculator

3. Modify the Code

clr gif
Join the Discussion

Questions? Comments?

More of this Feature

Introduction Get the Code

The final step in getting your own custom distance calculator on your web page is to modify the dist array that is at the top of the dist.js file so that it contains your list of cities (or other locations) and the distances between them. To be able to make the required modifications you will need to understand how that complex array structure needs to be arranged in order to work with the script.

There are actually three levels of arrays that are nested inside of one another in building up the structure that we need. The outermost array contains one entry for each city or location.

var dist = [
entry,
entry,
entry
];

Each of these entries consists of an array that itself has two entries.

['cityname',array_of_distances]

The array of distances (the third level of the array structure) contains one entry for each location entry that precedes it in the top level array. These entries are the distances in kilometres between this location and each of the preceding locations (starting from the top of the array). As the first location has no entries preceding it this location has no entries in this array. The second location has one location preceding it and so the array has one entry. In the supplied example code the 1268 is the distance in kilometres between Paris and Madrid (in either direction).

['Paris',[]],
['Madrid',[1268]],
['Lisbon',[1786,638]],

Similarly when we look at the third entry in the main array, 1786 is the distance between Paris and Lisbon in kilometres and 638 is the distance between Madrid and Lisbon in kilometres. The entries that follow are constructed the same way with each entry having one more value in the distances array than did the line before (since there is now one additional preceding line to give distances to).

The entries will be displayed in alphabetical order in the two drop down lists regardless of which order they are entered in the array so you can add the entries in to the array in whichever order is easiest. There is no limit as to how many locations that you can have in your drop down lists (apart from those imposed by browsers when your page starts to get rediculously large). An extra entry can always be added to the array simply by supplying the distances to all of the locations from the new location to those locations already in the array.

Explore JavaScript
About.com Special Features

The Best Web Trends of the Decade

A look back at the best innovations, ideas and technologies over the last 10 years, More >

Family Tech Center

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

  1. Home
  2. Computing & Technology
  3. JavaScript

©2009 About.com, a part of The New York Times Company.

All rights reserved.