Category Archives: Javascript

New York City Household Furniture Moving Travel Time Calculator

My next project is to create a travel time calculator application using Dancer2. Hopefully, this would be useful to any household furniture moving company operating in New York City.
When charging for the travel time between two locations, many New York City Moving companies use the following DOT guidelines.

  1. 1/2 an hour within any borough.
  2. 3/4 an hour from one borough to another.
  3. 1 hour for the first 20 miles between locations that either start or end within New York City
  4. 1 hour for each 40 miles after the first 20 miles, which is equivalent to 15 minutes for each 10 miles.

Most of the information that I need to get the distances between locations is freely available from Google’s Distance Matrix API. I checked out CPAN to see if there was a suitable module available to access this API. There were some that partially did what I required, but not all of what I required.
I decided to write my own, which you can read about here.


Form To Input Addresses

There are two methods of User Input that I wanted to experiment with. The first is by means of a form where you would enter the exact origin and destination addresses. I describe this in detail here.
The second method, using jQuery autocomplete, I discuss here.

Dancer2 Application TravelTime

The Perl App that implements the Travel Time Calculator

I used the Perl Dancer2 framework for building this application. Dancer2 bills itself as a “Lightweight yet powerful web application framework”, which I guess is true. It works well for me and is not too complex. I did run into a few bugs which seem to have been ironed out in the very latest version. So, it does have an active group of developers who are maintaining and upgrading this software. Thank you for that.
Here is an excerpt from this module, showing one particular route handler. This particular one handles an Ajax call to provide a list of cities that match a specific search criteria. The Dancer2::Plugin::Ajax helps out with this method. The caller in this case is a JavaScript program that I use to implement a jQuery autocomplete input field. You can read about this here

#    Get a list of city, states and counties.
ajax '/city_states' => sub {
    #------ Trim  whitespace from lhs and append the '%' SQL match char.
    #       This will handle searches like 'Sunn,      New York' (Sunnyside, New York)
    #       or                             'Kew Gar,      New York' (Kew Gardens,  New York)
    #       or                             'Kew,New York'
    my @find_params =
      map { $_ =~ s/^\s+//; s/\s+\z//; $_ . '%' }
      split( ',', params->{find} );
    debug 'The find params array now contains : ' . dump @find_params;

    my $csc_arr;

    #------ Allow some short cuts for the Big Apple
    if ( $find_params[0] =~ /^(nyc|manhattan|base)%\z/i ) {
        $csc_arr->[0] = [ 'New York City', 'New York', 'New York County' ];
    else {

        #----- Search DB for City and Counties matching the search params.
        connect_to_cities() unless $DBH;
        process_error( { Error => 'Unable to connect to the City, State,
                county database! Please try later!', } ) unless $DBH;
        $csc_arr = select_city_state_cty( $DBH, \@find_params );

    #------ Returns sorted list of Cities, States and Counties to
    #       city-states.js
    { city_states => $csc_arr };

Have a look at the entire Application code on GitHub.
For a live demo, here is the Moving Truck Travel Time Calculator application running on the dotCloud hosting service.
This is how I deployed my Dancer2 Application to dotCloud.

City, State, County Selection With Bootstrap 2 Typeahead

This is a demonstration of how I implemented an Ajax call to a Perl Dancer2 Application using jQuery and the Bootstrap Typeahead function.

As part of my TravelTime App , I wanted to create and easy way to select the start and end locations using the jQuery Autocomplete component. Bootstrap 2 has its own version of this which they call Typeahead.
I just found out that the latest version of Bootstrap will not include this Typeahead functionality. Instead it will be replaced with typeahead.js I hope to check this out in the future.
Anyway, I will be using Perl, Dancer2 with Template Toolkit to render this form.
I also needed to customise the Typeahead to complete an Ajax call to my Perl Dancer2 application. The Dancer2 application will then provide the sorted list of City,States and Counties based on the search parameters passed to it.

The Template::Toolkit Form

Exerpt from

<div class="span11">
        <span class="text-info">
            <abbr title='Enter the starting location'>Start Location</abbr>
        <div class="control-group">
        <!-- Bootstrap Typeahead -->
            <label class="control-label" for="address-[% loop.count %]">[% warning_message %]</label>
            <div class="controls">
                <input type="text"
                    class="cityStatesTypeahead span9 input-append"
                    name="address-[% loop.count %]"
                    id="address-[% loop.count %]" value="[% address %]"
                    placeholder="City/Town, State" 
                    <span class="addQmark"><i class="iconic-question-mark"></i></span>
            <input type="hidden"
                name="h-address-[% loop.count %]"
                id="h-address-[% loop.count %]"
        </div> <!-- /span11 -->

The entire template can be seen here on GitHub.
The highlighted fields are the ones that are pertinent to the activation of the Bootstrap Typeahead.
In order to customise the Bootstrap Typeahead, I found this very useful website by FusionGrokker, for which I am thankful (You could also check out the jQuery docs for the original concept).

Here is my JavaScript to implement the Typeahead Ajax call.

The jQuery

Excerpt from city-states.js

var hiddenId;
// Get the hidden address field associated with the current
// address field
$('.cityStatesTypeahead').bind('focus',  function(){
   hiddenId =  $(this).attr('id'); 

  items: 10, 
  minLength : 3, 
  source:  function(query, process) {
      //Call Perl App to find the sorted list of City, States and Counties
      return searchForPlaces(query, process);
  highlighter: function(item){
    return highLightSelect(item);

matcher: function () { return true; }, 
updater: function (item) {
    return updateField(item);

// Ajax call to Perl Dancer Script, which returns an Array Ref
// of sorted City, State and County data.
var debounceWait = 100;
// Use Underscore JS function '_debounce' to ensure that the
// search waits for specific number of milliseconds before running again.
var cityStates = {};
var cityNames = [];
var searchForPlaces = _.debounce(function( query,  process ){
    $.post("/city_states",{ find : query}, function(data){
    cityStates = {};
    cityNames = [];
        var counter = 0;
        _.each( data.city_states,  function( item,  ix,  list ){
        item.label = item + '-' + (counter++);
         // console.log('Got this item from AJAX : ' + item);
        cityStates[item.label] = {
                city : item[0],   
                state : item[1],  
                county : item[2]
        //add selected items to diaplay array
        // console.log('Add this to the array ' + item.label);

    // Let Bootstrap and jQuery process the list
    // for display in the input box
    process( cityNames );
},  debounceWait);

//Highlighter Function
var highLightSelect = function(item){
    // console.log("      Item inside highlighter " + item);
   var c = cityStates[item];
   return ''
       + "<div class='typeahead_wrapper'>"
       + "<div class='typeahead_labels'>"
       + "<div class='typeahead_primary'>" + + ', ' + c.state + "</div>"
       + "<div class='typeahead_secondary'><strong>County: </strong>"  + c.county + "</div>"
       + "</div>"
       + "</div>";

// Updater Function
// Add the required data into the input field
var updateField = function(item){
   var c = cityStates[item];
   //Hidden field will contain all the valuable data
    $( "#h-" + hiddenId ).val( + ',' + c.state + ',' + c.county );
   //This is the data for display on input box
   return + ', ' + c.state + "  County: " + c.county ;


Have a look at line 34 for the actual Ajax call to the Perl module. It sends a request to’s ‘/city_state’ route. As the Typeahead attribute ‘minLength’ is set to 3, it passes at least the first three letters of the requested City to the Dancer2 application. The city_states database is then searched for a city beginning with this search string. The Dancer2 application will return a sorted list of these cities with their corresponding state and county names. The application can also accept two search strings separated by a comma. This will search the database for cities beginning with the first string and corresponding states beginning with the second string.
“city-states.js” receives this sorted list of cities, states and counties.
The Typeahead displays (items: 10) items in the dropdown list.The “highLightSelect” highlighter function formats this list into a more readable format.
When an item is selected “theupdateField” populates the hidden fields.

More details of what is happening in will be left for another post.
Have a look at the TravelTime App in action.
I hope that this blog post may useful to some developer out there.