If this is your first visit, check our documentation. To post, register or login.
Forums / Addon Shipping Modules / Mileage based shipping module?

Mileage based shipping module?

Started by fjolsvith on 22 Mar 2016, 7:37 PM · Views: 19,555

Results 1 to 20 of 33
22 Mar 2016, 7:37 PM
#1
fjolsvith avatar

fjolsvith

New Zenner

Join Date:
Mar 2016
Location:
Norcatur, Kansas, USA
Posts:
88
Plugin Contributions:
2

Mileage based shipping module?

Hi,

I have a portable building manufacturing business and need a shipping module that calculates the mileage from our factory to the customer's delivery address, and then adds a shipping charge cost per mile.

Does anyone know of a shipping module that can do this?

Thanks!

23 Mar 2016, 4:03 AM
#3
rodg avatar

rodg

Deceased

Join Date:
Jan 2007
Location:
Australia
Posts:
6,263
Plugin Contributions:
4

Re: Mileage based shipping module?

Fjolsvith:

Hi,

I have a portable building manufacturing business and need a shipping module that calculates the mileage from our factory to the customer's delivery address, and then adds a shipping charge cost per mile.

Does anyone know of a shipping module that can do this?

None that I'm aware of, but it is quite possible that you could use the 'zones' shipping module for this. I'm not sure how easy/hard it would be to configure for your needs though. The way I envisage it is zone#1 = within a 1mile radius, Zone#2 = within a 2mile radius ........ Zone#50 = within a 50mile radius.

Just a thought.

Cheers
RodG

NOTE: We are sorry that Rod is no longer with us.
We are grateful for all his contributions to the Zen Cart community.

Ozpost - The Ultimate Shipping module for Australian Merchants. Click these links for its Homepage, or Download from Zen-Cart.com.

23 Mar 2016, 6:49 PM
#5
fjolsvith avatar

fjolsvith

New Zenner

Join Date:
Mar 2016
Location:
Norcatur, Kansas, USA
Posts:
88
Plugin Contributions:
2

Re: Mileage based shipping module?

Okay, so I tried my hand at writing a shipping module but it doesn't seem to work. Here is the code:

In includes/modules/shipping/mileageship.php:

<?php
/**
 * @package shippingMethod
 * @copyright Copyright 2003-2006 Zen Cart Development Team
 * @copyright Portions Copyright 2016 James Plotts
 * @license http://www.zen-cart.com/license/2_0.txt GNU Public License V2.0
 * @version $Id: mileage.php 
 * 1/25/2007 - for Zen-Cart 1.5.4
 */
/*

  USAGE
  





*/

  class mileageship {
    var $code, $title, $description, $enabled, $num_zones;

// class constructor
    function mileageship() {
      $this->code = 'mileageship';
      $this->title = MODULE_SHIPPING_MILEAGESHIP_TEXT_TITLE;
      $this->description = MODULE_SHIPPING_MILEAGESHIP_TEXT_DESCRIPTION;
      $this->sort_order = MODULE_SHIPPING_MILEAGESHIP_SORT_ORDER;
      $this->icon = '';
      $this->tax_class = MODULE_SHIPPING_MILEAGESHIP_TAX_CLASS;
      $this->tax_basis = MODULE_SHIPPING_MILEAGESHIP_TAX_BASIS;
      $this->enabled = ((MODULE_SHIPPING_MILEAGESHIP_STATUS == 'True') ? true : false);

      /*// disable only when entire cart is free shipping
      if (zen_get_shipping_enabled($this->code)) {
        $this->enabled = ((MODULE_SHIPPING_MILEAGESHIP_STATUS == 'True') ? true : false);
      }*/

     
    }

// class methods
    function quote($method = '') {
      global $order, $shipping_weight, $shipping_num_boxes, $total_count;
      $dest_mileagecode = $order->delivery['postcode'];
      $dest_zone = 0;
      $error = false;
      try
      {
          $info = get_driving_information('67653', $dest_mileagecode, false);
          echo $info['distance'];
          $shipping_cost = $info['distance'];
          $shipping_method = MODULE_SHIPPING_MILEAGESHIP_TEXT_WAY . ' ' . $dest_mileagecode;
          $done = true;
          break;
      }
      catch(Exception $e)
      {
          echo 'Caught exception: '.$e->getMessage()."\n";
          $error = true;
      }


        
      $this->quotes = array('id' => $this->code,
                            'module' => MODULE_SHIPPING_MILEAGESHIP_TEXT_TITLE,
                            'methods' => array(array('id' => $this->code,
                                                     'title' => $shipping_method,
                                                     'cost' => $shipping_cost)));

      if ($this->tax_class > 0) {
        	$this->quotes['tax'] = zen_get_tax_rate($this->tax_class, $order->delivery['country']['id'], $order->delivery['zone_id']);
      }

      if (zen_not_null($this->icon)) $this->quotes['icon'] = zen_image($this->icon, $this->title);

      if ($error == true) $this->quotes['error'] = MODULE_SHIPPING_MILEAGESHIP_INVALID_CODE;

      return $this->quotes;
    }

    function check() {
      global $db;
      if (!isset($this->_check)) {
        $check_query = $db->Execute("select configuration_value from " . TABLE_CONFIGURATION . " where configuration_key = 'MODULE_SHIPPING_MILEAGESHIP_STATUS'");
        $this->_check = $check_query->RecordCount();
      }
      return $this->_check;
    }

    function install() {
      global $db;
      $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, date_added) VALUES ('Enable Zip Code Method', 'MODULE_SHIPPING_MILEAGESHIP_STATUS', 'True', 'Do you want to offer mileage code base shipping?', '6', '0', 'zen_cfg_select_option(array(\'True\', \'False\'), ', now())");
      //$db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, date_added) VALUES ('Calculation Method', 'MODULE_SHIPPING_MILEAGESHIP_METHOD', 'Weight', 'Calculate cost based on Weight, Price or Item?', '6', '0', 'zen_cfg_select_option(array(\'Weight\', \'Price\', \'Item\'), ', now())");
      $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, use_function, set_function, date_added) values ('Tax Class', 'MODULE_SHIPPING_MILEAGESHIP_TAX_CLASS', '0', 'Use the following tax class on the shipping fee.', '6', '0', 'zen_get_tax_class_title', 'zen_cfg_pull_down_tax_classes(', now())");
      $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, date_added) values ('Tax Basis', 'MODULE_SHIPPING_MILEAGESHIP_TAX_BASIS', 'Shipping', 'On what basis is Shipping Tax calculated. Options are<br />Shipping - Based on customers Shipping Address<br />Billing Based on customers Billing address<br />Store - Based on Store address if Billing/Shipping Zone equals Store zone', '6', '0', 'zen_cfg_select_option(array(\'Shipping\', \'Billing\', \'Store\'), ', now())");
      $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('Sort Order', 'MODULE_SHIPPING_MILEAGESHIP_SORT_ORDER', '0', 'Sort order of display.', '6', '0', now())");
      $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, date_added) values ('Skip Zipcodes, use a comma separated list of the five character Zip codes', 'MODULE_SHIPPING_MILEAGESHIP_SKIPPED', '', 'Disable for the following Zip Codes:', '6', '0', 'zen_cfg_textarea(', now())");

      /*for ($i = 1; $i <= $this->num_zones; $i++) {
        $default_mileagecodes = '';
        if ($i == 1) {
          $default_mileagecodes = '33801,33803,33809';
        }
        $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, date_added) values ('Zone " . $i ." Zip Codes', 'MODULE_SHIPPING_MILEAGESHIP_CODES_" . $i ."', '" . $default_mileagecodes . "', 'Comma separated list of five character mileage codes that are part of Zone " . $i . ".<br />Set as 00000 to indicate all five character mileage codes that are not specifically defined.', '6', '0', 'zen_cfg_textarea(', now())");
        $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, date_added) values ('Zone " . $i ." Shipping Table', 'MODULE_SHIPPING_MILEAGESHIP_COST_" . $i ."', '50:5.50,51:0', 'Shipping rates to Zone " . $i . " destinations based on a group of maximum order weights/prices. Example: 3:8.50,7:10.50,... Weight/Price less than or equal to 3 would cost 8.50 for Zone " . $i . " destinations.', '6', '0', 'zen_cfg_textarea(', now())");
        $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('Zone " . $i ." Handling Fee', 'MODULE_SHIPPING_MILEAGESHIP_HANDLING_" . $i."', '0', 'Handling Fee for this shipping zone', '6', '0', now())");
      }*/
    }

    function remove() {
      global $db;
      $db->Execute("delete from " . TABLE_CONFIGURATION . " where configuration_key in ('" . implode("', '", $this->keys()) . "')");
    }

    function keys() {
      $keys = array('MODULE_SHIPPING_MILEAGESHIP_STATUS', 'MODULE_SHIPPING_MILEAGESHIP_METHOD', 'MODULE_SHIPPING_MILEAGESHIP_TAX_CLASS', 'MODULE_SHIPPING_MILEAGESHIP_TAX_BASIS', 'MODULE_SHIPPING_MILEAGESHIP_SORT_ORDER', 'MODULE_SHIPPING_MILEAGESHIP_SKIPPED');

      for ($i=1; $i<=$this->num_zones; $i++) {
        $keys[] = 'MODULE_SHIPPING_MILEAGESHIP_CODES_' . $i;
        $keys[] = 'MODULE_SHIPPING_MILEAGESHIP_COST_' . $i;
        $keys[] = 'MODULE_SHIPPING_MILEAGESHIP_HANDLING_' . $i;
      }

      return $keys;
    }


  function get_driving_information($start, $finish, $raw = false)
  {
      if(strcmp($start, $finish) == 0)
      {
          $time = 0;
          if($raw)
          {
              $time .= ' seconds';
          }
   
          return array('distance' => 0, 'time' => $time);
      }
   
      $start  = urlencode($start);
      $finish = urlencode($finish);
   
      $distance   = 'unknown';
      $time		= 'unknown';
   
      $url = 'http://maps.googleapis.com/maps/api/directions/xml?origin='.$start.'&destination='.$finish.'&sensor=false';
      if($data = file_get_contents($url))
      {
          $xml = new SimpleXMLElement($data);
   
          if(isset($xml->route->leg->duration->value) AND (int)$xml->route->leg->duration->value > 0)
          {
              if($raw)
              {
                  $distance = (string)$xml->route->leg->distance->text;
                  $time	  = (string)$xml->route->leg->duration->text;
              }
              else
              {
                  $distance = (int)$xml->route->leg->distance->value / 1000 / 1.609344; 
                  $time	  = (int)$xml->route->leg->duration->value;
              }
          }
          else
          {
              throw new Exception('Could not find that route');
          }
   
          return array('distance' => $distance, 'time' => $time);
      }
      else
      {
          throw new Exception('Could not resolve URL');
      }
  }

  }


?>

And in the includes/languages/modules/shipping/mileageship.php:

<?php
//
// +----------------------------------------------------------------------+
// |zen-cart Open Source E-commerce                                       |
// +----------------------------------------------------------------------+
// | Copyright (c) 2003 The zen-cart developers                           |
// |                                                                      |
// | http://www.zen-cart.com/index.php                                    |
// |                                                                      |

/*
//  $Id: mileageship.php,v 1.0 2016
//  ecw, Eternal Codeworks
//  modified for Zen-Cart v 1.5.4 - by James Plotts
//
//  Copyright (c) 2016 James Plotts
//
//  Released under the GNU General Public License
*/

define('MODULE_SHIPPING_MILEAGESHIP_TEXT_TITLE', 'Mileage Rate');
define('MODULE_SHIPPING_MILEAGESHIP_TEXT_DESCRIPTION', 'Mileage-Based Rate');
define('MODULE_SHIPPING_MILEAGESHIP_TEXT_WAY', 'Deliver To Zipcode: ');
define('MODULE_SHIPPING_MILEAGESHIP_TEXT_UNITS', 'lb(s)');
define('MODULE_SHIPPING_MILEAGESHIP_INVALID_ZONE', 'No delivery/shipping available to the selected zipcode.');
define('MODULE_SHIPPING_MILEAGESHIP_UNDEFINED_RATE', 'The delivery/shipping fee cannot be determined at this time');
define('MODULE_SHIPPING_MILEAGESHIP_INVALID_CODE', 'Sorry. Free Shipping not available in your area.');

?>

Can anyone tell me what is not working?

23 Mar 2016, 7:08 PM
#6
ajeh avatar

ajeh

Oba-san

Join Date:
Sep 2003
Location:
Ohio
Posts:
62,757
Plugin Contributions:
1

Re: Mileage based shipping module?

Your function:
get_driving_information

Should be outside of the class, at the bottom of the file ...

Next,, you cannot use the break on line 50 ...

See if that gets you headed in the right direction ...

Would love to see this when it is complete ... :smile:

Linda McGrath
If you have to think ... you haven't been zenned ...

**Did YOU buy the Zen Cart Team a cup of coffee and a donut today? Just click here to support the Zen Cart Team!!**

Are you using the latest? Perhaps you've a problem that's fixed in the latest version: [Upgrade today!]
Officially PayPal-Certified! Just click here

Try our Zen Cart Recommended Services - Hosting, Payment and more ...
Signup for our Announcements Forums to stay up to date on important changes and updates!

23 Mar 2016, 7:27 PM
#7
fjolsvith avatar

fjolsvith

New Zenner

Join Date:
Mar 2016
Location:
Norcatur, Kansas, USA
Posts:
88
Plugin Contributions:
2

Re: Mileage based shipping module?

Okay, its still broke. When I pull up the Modules -> Shipping Modules page, it doesn't have the right side panel showing.

Also, when I click on the shipping estimator button, the popup is blank.

I also have Paypal Express configured, and when trying to checkout with paypal, when paypal redirects back to the shopping cart, it fails saying my site is not configured properly.

23 Mar 2016, 7:38 PM
#8
ajeh avatar

ajeh

Oba-san

Join Date:
Sep 2003
Location:
Ohio
Posts:
62,757
Plugin Contributions:
1

Re: Mileage based shipping module?

This is what I have so far on the file:
/includes/modules/shipping/mileageship.php

<?php
/**
 * @package shippingMethod
 * @copyright Copyright 2003-2006 Zen Cart Development Team
 * @copyright Portions Copyright 2016 James Plotts
 * @license http://www.zen-cart.com/license/2_0.txt GNU Public License V2.0
 * @version $Id: mileage.php
 * 1/25/2007 - for Zen-Cart 1.5.4
 */
/*

  USAGE
  */

  class mileageship {
    var $code, $title, $description, $enabled, $num_zones;

// class constructor
    function mileageship() {
      $this->code = 'mileageship';
      $this->title = MODULE_SHIPPING_MILEAGESHIP_TEXT_TITLE;
      $this->description = MODULE_SHIPPING_MILEAGESHIP_TEXT_DESCRIPTION;
      $this->sort_order = MODULE_SHIPPING_MILEAGESHIP_SORT_ORDER;
      $this->icon = '';
      $this->tax_class = MODULE_SHIPPING_MILEAGESHIP_TAX_CLASS;
      $this->tax_basis = MODULE_SHIPPING_MILEAGESHIP_TAX_BASIS;
      $this->enabled = ((MODULE_SHIPPING_MILEAGESHIP_STATUS == 'True') ? true : false);

      /*// disable only when entire cart is free shipping
      if (zen_get_shipping_enabled($this->code)) {
        $this->enabled = ((MODULE_SHIPPING_MILEAGESHIP_STATUS == 'True') ? true : false);
      }*/


    }

// class methods
    function quote($method = '') {
      global $order, $shipping_weight, $shipping_num_boxes, $total_count;
      $dest_mileagecode = $order->delivery['postcode'];
      $dest_zone = 0;
      $error = false;
      try
      {
          $info = get_driving_information('67653', $dest_mileagecode, false);
          echo $info['distance'];
          $shipping_cost = $info['distance'];
          $shipping_method = MODULE_SHIPPING_MILEAGESHIP_TEXT_WAY . ' ' . $dest_mileagecode;
          $done = true;
//          break;
      }
      catch(Exception $e)
      {
          echo 'Caught exception: '.$e->getMessage()."\n";
          $error = true;
      }



      $this->quotes = array('id' => $this->code,
                            'module' => MODULE_SHIPPING_MILEAGESHIP_TEXT_TITLE,
                            'methods' => array(array('id' => $this->code,
                                                     'title' => $shipping_method,
                                                     'cost' => $shipping_cost)));

      if ($this->tax_class > 0) {
          $this->quotes['tax'] = zen_get_tax_rate($this->tax_class, $order->delivery['country']['id'], $order->delivery['zone_id']);
      }

      if (zen_not_null($this->icon)) $this->quotes['icon'] = zen_image($this->icon, $this->title);

      if ($error == true) $this->quotes['error'] = MODULE_SHIPPING_MILEAGESHIP_INVALID_CODE;

      return $this->quotes;
    }

    function check() {
      global $db;
      if (!isset($this->_check)) {
        $check_query = $db->Execute("select configuration_value from " . TABLE_CONFIGURATION . " where configuration_key = 'MODULE_SHIPPING_MILEAGESHIP_STATUS'");
        $this->_check = $check_query->RecordCount();
      }
      return $this->_check;
    }

    function install() {
      global $db;
      $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, date_added) VALUES ('Enable Zip Code Method', 'MODULE_SHIPPING_MILEAGESHIP_STATUS', 'True', 'Do you want to offer mileage code base shipping?', '6', '0', 'zen_cfg_select_option(array(\'True\', \'False\'), ', now())");
      //$db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, date_added) VALUES ('Calculation Method', 'MODULE_SHIPPING_MILEAGESHIP_METHOD', 'Weight', 'Calculate cost based on Weight, Price or Item?', '6', '0', 'zen_cfg_select_option(array(\'Weight\', \'Price\', \'Item\'), ', now())");
      $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, use_function, set_function, date_added) values ('Tax Class', 'MODULE_SHIPPING_MILEAGESHIP_TAX_CLASS', '0', 'Use the following tax class on the shipping fee.', '6', '0', 'zen_get_tax_class_title', 'zen_cfg_pull_down_tax_classes(', now())");
      $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, date_added) values ('Tax Basis', 'MODULE_SHIPPING_MILEAGESHIP_TAX_BASIS', 'Shipping', 'On what basis is Shipping Tax calculated. Options are<br />Shipping - Based on customers Shipping Address<br />Billing Based on customers Billing address<br />Store - Based on Store address if Billing/Shipping Zone equals Store zone', '6', '0', 'zen_cfg_select_option(array(\'Shipping\', \'Billing\', \'Store\'), ', now())");
      $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('Sort Order', 'MODULE_SHIPPING_MILEAGESHIP_SORT_ORDER', '0', 'Sort order of display.', '6', '0', now())");
      $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, date_added) values ('Skip Zipcodes, use a comma separated list of the five character Zip codes', 'MODULE_SHIPPING_MILEAGESHIP_SKIPPED', '', 'Disable for the following Zip Codes:', '6', '0', 'zen_cfg_textarea(', now())");

      /*for ($i = 1; $i <= $this->num_zones; $i++) {
        $default_mileagecodes = '';
        if ($i == 1) {
          $default_mileagecodes = '33801,33803,33809';
        }
        $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, date_added) values ('Zone " . $i ." Zip Codes', 'MODULE_SHIPPING_MILEAGESHIP_CODES_" . $i ."', '" . $default_mileagecodes . "', 'Comma separated list of five character mileage codes that are part of Zone " . $i . ".<br />Set as 00000 to indicate all five character mileage codes that are not specifically defined.', '6', '0', 'zen_cfg_textarea(', now())");
        $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, date_added) values ('Zone " . $i ." Shipping Table', 'MODULE_SHIPPING_MILEAGESHIP_COST_" . $i ."', '50:5.50,51:0', 'Shipping rates to Zone " . $i . " destinations based on a group of maximum order weights/prices. Example: 3:8.50,7:10.50,... Weight/Price less than or equal to 3 would cost 8.50 for Zone " . $i . " destinations.', '6', '0', 'zen_cfg_textarea(', now())");
        $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('Zone " . $i ." Handling Fee', 'MODULE_SHIPPING_MILEAGESHIP_HANDLING_" . $i."', '0', 'Handling Fee for this shipping zone', '6', '0', now())");
      }*/
    }

    function remove() {
      global $db;
      $db->Execute("delete from " . TABLE_CONFIGURATION . " where configuration_key in ('" . implode("', '", $this->keys()) . "')");
    }

    function keys() {
      $keys = array('MODULE_SHIPPING_MILEAGESHIP_STATUS', 'MODULE_SHIPPING_MILEAGESHIP_METHOD', 'MODULE_SHIPPING_MILEAGESHIP_TAX_CLASS', 'MODULE_SHIPPING_MILEAGESHIP_TAX_BASIS', 'MODULE_SHIPPING_MILEAGESHIP_SORT_ORDER', 'MODULE_SHIPPING_MILEAGESHIP_SKIPPED');

      for ($i=1; $i<=$this->num_zones; $i++) {
        $keys[] = 'MODULE_SHIPPING_MILEAGESHIP_CODES_' . $i;
        $keys[] = 'MODULE_SHIPPING_MILEAGESHIP_COST_' . $i;
        $keys[] = 'MODULE_SHIPPING_MILEAGESHIP_HANDLING_' . $i;
      }

      return $keys;
    }



  }


  function get_driving_information($start, $finish, $raw = false)
  {
      if(strcmp($start, $finish) == 0)
      {
          $time = 0;
          if($raw)
          {
              $time .= ' seconds';
          }

          return array('distance' => 0, 'time' => $time);
      }

      $start  = urlencode($start);
      $finish = urlencode($finish);

      $distance   = 'unknown';
      $time    = 'unknown';

      $url = 'http://maps.googleapis.com/maps/api/directions/xml?origin='.$start.'&destination='.$finish.'&sensor=false';
      if($data = file_get_contents($url))
      {
          $xml = new SimpleXMLElement($data);

          if(isset($xml->route->leg->duration->value) AND (int)$xml->route->leg->duration->value > 0)
          {
              if($raw)
              {
                  $distance = (string)$xml->route->leg->distance->text;
                  $time    = (string)$xml->route->leg->duration->text;
              }
              else
              {
                  $distance = (int)$xml->route->leg->distance->value / 1000 / 1.609344;
                  $time    = (int)$xml->route->leg->duration->value;
              }
          }
          else
          {
              throw new Exception('Could not find that route');
          }

          return array('distance' => $distance, 'time' => $time);
      }
      else
      {
          throw new Exception('Could not resolve URL');
      }
  }

Linda McGrath
If you have to think ... you haven't been zenned ...

**Did YOU buy the Zen Cart Team a cup of coffee and a donut today? Just click here to support the Zen Cart Team!!**

Are you using the latest? Perhaps you've a problem that's fixed in the latest version: [Upgrade today!]
Officially PayPal-Certified! Just click here

Try our Zen Cart Recommended Services - Hosting, Payment and more ...
Signup for our Announcements Forums to stay up to date on important changes and updates!

23 Mar 2016, 7:48 PM
#9
fjolsvith avatar

fjolsvith

New Zenner

Join Date:
Mar 2016
Location:
Norcatur, Kansas, USA
Posts:
88
Plugin Contributions:
2

Re: Mileage based shipping module?

Yes, except missing the final "?>".

When I rename the two *.php files to *.ph_, the shipping modules list comes back up properly in Modules -> Shipping Modules. So, something is not right with the install function or in my db.

23 Mar 2016, 8:13 PM
#10
ajeh avatar

ajeh

Oba-san

Join Date:
Sep 2003
Location:
Ohio
Posts:
62,757
Plugin Contributions:
1

Re: Mileage based shipping module?

You do not need the closing php tag ?> ... so I deleted it ...

Try a rename on the old file:
mileage.php_somethinghere

as these are self loading directories and you want to avoid errors etc.

The file I posted seems to work fine. I would suggest on code change, there are many that I would add to this file, but for starters, I commented out the original line and change the Zip Code to be the one set in Configuration ... Shipping ...

[B]//[/B]          $info = get_driving_information('67653', $dest_mileagecode, false);
          $info = get_driving_information([B]SHIPPING_ORIGIN_ZIP[/B], $dest_mileagecode, false);

This just avoids needing to edit the file for a Zip code change ... (thinking about the future of this one plus many other things to jazz it up) :cool:

Linda McGrath
If you have to think ... you haven't been zenned ...

**Did YOU buy the Zen Cart Team a cup of coffee and a donut today? Just click here to support the Zen Cart Team!!**

Are you using the latest? Perhaps you've a problem that's fixed in the latest version: [Upgrade today!]
Officially PayPal-Certified! Just click here

Try our Zen Cart Recommended Services - Hosting, Payment and more ...
Signup for our Announcements Forums to stay up to date on important changes and updates!

23 Mar 2016, 8:32 PM
#11
fjolsvith avatar

fjolsvith

New Zenner

Join Date:
Mar 2016
Location:
Norcatur, Kansas, USA
Posts:
88
Plugin Contributions:
2

Re: Mileage based shipping module?

OMG it is working!!!

23 Mar 2016, 8:36 PM
#12
ajeh avatar

ajeh

Oba-san

Join Date:
Sep 2003
Location:
Ohio
Posts:
62,757
Plugin Contributions:
1

Re: Mileage based shipping module?

'tis but a little elfin' magic ... :cool:

Linda McGrath
If you have to think ... you haven't been zenned ...

**Did YOU buy the Zen Cart Team a cup of coffee and a donut today? Just click here to support the Zen Cart Team!!**

Are you using the latest? Perhaps you've a problem that's fixed in the latest version: [Upgrade today!]
Officially PayPal-Certified! Just click here

Try our Zen Cart Recommended Services - Hosting, Payment and more ...
Signup for our Announcements Forums to stay up to date on important changes and updates!

23 Mar 2016, 8:45 PM
#13
fjolsvith avatar

fjolsvith

New Zenner

Join Date:
Mar 2016
Location:
Norcatur, Kansas, USA
Posts:
88
Plugin Contributions:
2

Re: Mileage based shipping module?

Okay, it is working now. I had to go in and delete the MODULE_SHIPPING_* entries in my configuration table in the database to get everything to reload and work right.

The shipping estimator is working perfectly:

Attachment 16153

Now to run a test purchase.

23 Mar 2016, 8:54 PM
#14
fjolsvith avatar

fjolsvith

New Zenner

Join Date:
Mar 2016
Location:
Norcatur, Kansas, USA
Posts:
88
Plugin Contributions:
2

Re: Mileage based shipping module?

Okay, my test purchase processed successfully. However, I need to make a feature addition to the module now.

I need to have it automatically default to a free delivery option for customers under a certain number of miles away.

24 Mar 2016, 4:45 AM
#15
fjolsvith avatar

fjolsvith

New Zenner

Join Date:
Mar 2016
Location:
Norcatur, Kansas, USA
Posts:
88
Plugin Contributions:
2

Re: Mileage based shipping module?

I have submitted this Shipping Module to the Plugins section here on this website. The module is called MileageShip, and it has a few little features.

You can specify the dollar amount that is calculated per mile. Also, you can specify a minimum range in miles where you offer free delivery. As an example, my business gives free delivery for addresses within 60 miles. If you specify 0 for this setting, it calculates the mileage charge for any distance.

I plan to make one more change where you can specify a maximum distance you are willing to deliver.

24 Mar 2016, 8:55 AM
#16
kobra avatar

kobra

Black Belt

Join Date:
Aug 2005
Location:
Arizona
Posts:
31,500
Plugin Contributions:
4

Re: Mileage based shipping module?

I have submitted this Shipping Module to the Plugins section here on this website.
Thanks for sharing as it is this community that supports each other
Glad to see that Ajeh chimed in

Zen-Venom Get Bitten

25 Jul 2016, 12:47 PM
#17
jeffwebb avatar

jeffwebb

New Zenner

Join Date:
Jul 2005
Location:
Tennessee, USA
Posts:
11
Plugin Contributions:
0

Re: Mileage based shipping module?

Fjolsvith:

I plan to make one more change where you can specify a maximum distance you are willing to deliver.

Any progress on Max Distance?

26 Jul 2016, 7:38 AM
#18
frank18 avatar

frank18

Deceased

Join Date:
Nov 2007
Location:
Sunny Coast, Australia
Posts:
3,427
Plugin Contributions:
2

Re: Mileage based shipping module?

jeffwebb:

Any progress on Max Distance?

I had a play with this mod and made some tweaks, such as restricting the module to the shipping zone 'Australia - All States'. This could be narrowed to a smaller radius and limited to a single state only.

The problem arises if you wanted to limit delivery to a radius (miles or km) around your production facility whereby this radius overlaps state borders but you are not delivering to the entire neighboring state.

From a coding perspective, the issue is that (as the mod stands now) the distance between 2 points is calculated at the end of the file but the distance needs to be known before you can apply a condition resulting in **$this->enabled = false; ** thus disabling the module.

Needs more work.....

NOTE: We are sorry that Frank is no longer with us.
We are grateful for all his contributions to the Zen Cart community.

26 Jul 2016, 9:30 AM
#19
frank18 avatar

frank18

Deceased

Join Date:
Nov 2007
Location:
Sunny Coast, Australia
Posts:
3,427
Plugin Contributions:
2

Re: Mileage based shipping module?

Ok, here is the updated file /includes/modules/shipping/mileageship.php

<?php 
/** 
 * @package shippingMethod 
 * @copyright Copyright 2003-2016 Zen Cart Development Team 
 * @copyright Portions Copyright 2016 James Plotts 
 * @license http://www.zen-cart.com/license/2_0.txt GNU Public License V2.0 
 * @version $Id: mileage.php 
 * 1/25/2007 - for Zen-Cart 1.5.4 
 * updated for Zen Cart v1.5.5 -- frank18 20160726 
 */ 
/* 
 
  USAGE 
  */ 
 
  class mileageship { 
    var $code, $title, $description, $enabled, $num_zones; 
 
// class constructor 
    function __construct() { 
      $this->code = 'mileageship'; 
      $this->title = MODULE_SHIPPING_MILEAGESHIP_TEXT_TITLE; 
      $this->description = MODULE_SHIPPING_MILEAGESHIP_TEXT_DESCRIPTION; 
      $this->sort_order = MODULE_SHIPPING_MILEAGESHIP_SORT_ORDER; 
      $this->icon = ''; // add image filename here; must be uploaded to the /images/ subdirectory -- frank18 20160726 
      $this->tax_class = MODULE_SHIPPING_MILEAGESHIP_TAX_CLASS; 
      $this->tax_basis = MODULE_SHIPPING_MILEAGESHIP_TAX_BASIS; 
      $this->enabled = ((MODULE_SHIPPING_MILEAGESHIP_STATUS == 'True') ? true : false); 
    } 
     
  function update_status() { 
    global $order, $db; 
    if ( ($this->enabled == true) && ((int)MODULE_SHIPPING_MILEAGESHIP_ZONE > 0) ) { 
      $check_flag = false; 
      $check = $db->Execute("select zone_id from " . TABLE_ZONES_TO_GEO_ZONES . " 
                             where geo_zone_id = '" . MODULE_SHIPPING_MILEAGESHIP_ZONE . "' 
                             and zone_country_id = '" . $order->delivery['country']['id'] . "' 
                             order by zone_id"); 
      while (!$check->EOF) { 
        if ($check->fields['zone_id'] < 1) { 
          $check_flag = true; 
          break; 
        } elseif ($check->fields['zone_id'] == $order->delivery['zone_id']) { 
          $check_flag = true; 
          break; 
        } 
        $check->MoveNext(); 
      } 
       
      if ($check_flag == false) { 
        $this->enabled = false; 
      } 
       
    } 
     
  } 
 
// class methods 
    function quote($method = '') { 
      global $order, $shipping_weight, $shipping_num_boxes, $total_count; 
      $dest_mileagecode = $order->delivery['postcode']; 
      $dest_zone = 0; 
      $error = false; 
      try 
      { 
          $info = get_driving_information(SHIPPING_ORIGIN_ZIP, $dest_mileagecode, false); 
             $shipping_cost = $info['distance'] * MODULE_SHIPPING_MILEAGESHIP_COSTPERMILE; 
             $shipping_method = MODULE_SHIPPING_MILEAGESHIP_TEXT_WAY . ' ' . $dest_mileagecode; 
             if ($shipping_cost < MODULE_SHIPPING_MILEAGESHIP_FREEMILES) { 
                $shipping_method = 'Free Delivery to Post/Zip Code: ' . $dest_mileagecode; 
                $shipping_cost = 0; 
          } 
           
          $done = true; 
      } 
      catch(Exception $e) 
      { 
          echo 'Caught exception: '.$e->getMessage()."\n"; 
          $error = true; 
      } 
 
 
      if ($info['distance'] < MODULE_SHIPPING_MILEAGESHIP_MAXMILES) { // bof mileage exceeded -- frank18 20160726 
      $this->quotes = array('id' => $this->code, 
                            'module' => MODULE_SHIPPING_MILEAGESHIP_TEXT_TITLE, 
                            'methods' => array(array('id' => $this->code, 
                                                     'title' => $shipping_method, 
                                                     'cost' => $shipping_cost))); 
 
      if ($this->tax_class > 0) { 
          $this->quotes['tax'] = zen_get_tax_rate($this->tax_class, $order->delivery['country']['id'], $order->delivery['zone_id']); 
      } 
 
      if (zen_not_null($this->icon)) $this->quotes['icon'] = zen_image($this->icon, $this->title); 
 
      if ($error == true) $this->quotes['error'] = MODULE_SHIPPING_MILEAGESHIP_INVALID_CODE; 
 
      return $this->quotes; 
    } 
  } // eof mileage exceeded -- frank18 20160726 
 
    function check() { 
      global $db; 
      if (!isset($this->_check)) { 
        $check_query = $db->Execute("select configuration_value from " . TABLE_CONFIGURATION . " where configuration_key = 'MODULE_SHIPPING_MILEAGESHIP_STATUS'"); 
        $this->_check = $check_query->RecordCount(); 
      } 
      return $this->_check; 
    } 
 
    function install() { 
      global $db; 
      $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, date_added) VALUES ('Enable Zip Code Method', 'MODULE_SHIPPING_MILEAGESHIP_STATUS', 'True', 'Do you want to offer mileage (km) based shipping?', '6', '0', 'zen_cfg_select_option(array(\'True\', \'False\'), ', now())"); 
      $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, use_function, set_function, date_added) values ('Shipping Zone', 'MODULE_SHIPPING_MILEAGESHIP_ZONE', '0', 'If a zone is selected, only enable this shipping method for that zone.', '6', '0', 'zen_get_zone_class_title', 'zen_cfg_pull_down_zone_classes(', now())"); 
      $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, use_function, set_function, date_added) values ('Tax Class', 'MODULE_SHIPPING_MILEAGESHIP_TAX_CLASS', '0', 'Use the following tax class on the shipping fee.', '6', '0', 'zen_get_tax_class_title', 'zen_cfg_pull_down_tax_classes(', now())"); 
      $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, date_added) values ('Tax Basis', 'MODULE_SHIPPING_MILEAGESHIP_TAX_BASIS', 'Shipping', 'On what basis is Shipping Tax calculated. Options are<br />Shipping - Based on customers Shipping Address<br />Billing Based on customers Billing address<br />Store - Based on Store address if Billing/Shipping Zone equals Store zone', '6', '0', 'zen_cfg_select_option(array(\'Shipping\', \'Billing\', \'Store\'), ', now())"); 
      $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('Sort Order', 'MODULE_SHIPPING_MILEAGESHIP_SORT_ORDER', '0', 'Sort order of display.', '6', '0', now())"); 
      $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, date_added) values ('Enter the cost/km in dollars (e.g.: 1.25)', 'MODULE_SHIPPING_MILEAGESHIP_COSTPERMILE', '', 'Cost per kilometre in dollars:', '6', '0', 'zen_cfg_textarea(', now())"); 
      $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, date_added) values ('Maximum Distance in km for Free Delivery', 'MODULE_SHIPPING_MILEAGESHIP_FREEMILES', '', 'Enter the distance in kilometres for the maximum range for Free Delivery (Enter 0 for no free delivery):', '6', '0', 'zen_cfg_textarea(', now())"); 
      $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, date_added) values ('Maximum Distance in km you want to ship', 'MODULE_SHIPPING_MILEAGESHIP_MAXMILES', '', 'Enter the distance in kilometres for the maximum range you want to ship (this field is mandatory):', '6', '0', 'zen_cfg_textarea(', now())");     
    } 
 
    function remove() { 
      global $db; 
      $db->Execute("delete from " . TABLE_CONFIGURATION . " where configuration_key in ('" . implode("', '", $this->keys()) . "')"); 
    } 
 
    function keys() { 
      $keys = array('MODULE_SHIPPING_MILEAGESHIP_STATUS', 'MODULE_SHIPPING_MILEAGESHIP_ZONE', 'MODULE_SHIPPING_MILEAGESHIP_TAX_CLASS', 'MODULE_SHIPPING_MILEAGESHIP_TAX_BASIS', 'MODULE_SHIPPING_MILEAGESHIP_SORT_ORDER', 'MODULE_SHIPPING_MILEAGESHIP_COSTPERMILE', 'MODULE_SHIPPING_MILEAGESHIP_FREEMILES', 'MODULE_SHIPPING_MILEAGESHIP_MAXMILES'); 
 
      for ($i=1; $i<=$this->num_zones; $i++) { 
        $keys[] = 'MODULE_SHIPPING_MILEAGESHIP_CODES_' . $i; 
        $keys[] = 'MODULE_SHIPPING_MILEAGESHIP_COST_' . $i; 
        $keys[] = 'MODULE_SHIPPING_MILEAGESHIP_HANDLING_' . $i; 
      } 
 
      return $keys; 
    } 
 
  } 
 
 
  function get_driving_information($start, $finish, $raw = false) 
  { 
      if(strcmp($start, $finish) == 0) 
      { 
          $time = 0; 
          if($raw) 
          { 
              $time .= ' seconds'; 
          } 
 
          return array('distance' => 0, 'time' => $time); 
      } 
      
      $shipping_country = 'australia'; // change for your country -- frank18 20160726
      $start  = urlencode($start); 
      $finish = urlencode($finish); 
 
      $distance   = 'unknown'; 
      $time    = 'unknown'; 
 
      $url = 'http://maps.googleapis.com/maps/api/directions/xml?origin='.$start.','.$shipping_country.'&destination='.$finish.','.$shipping_country.'&sensor=false'; 
      // for debugging purposes only 
      // echo $url; 
      // echo $shipping_cost; 
    if($data = file_get_contents($url)) 
      { 
          $xml = new SimpleXMLElement($data); 
 
          if(isset($xml->route->leg->duration->value) AND (int)$xml->route->leg->duration->value > 0) 
          { 
              if($raw) 
              { 
                  $distance = (string)$xml->route->leg->distance->text; 
                  $time    = (string)$xml->route->leg->duration->text; 
              } 
              else 
              { 
                  //$distance = (int)$xml->route->leg->distance->value / 1000 / 1.609344; // uncomment for miles -- frank18 20160726 
                  $distance = (int)$xml->route->leg->distance->value / 1000 / 1.00; // uncomment for kms -- frank18 20160726 
                  // for debugging -- frank18 20160726 
                  // echo $distance; 
                  $time    = (int)$xml->route->leg->duration->value; 
              } 
          } 
          else 
          { 
              throw new Exception('Could not find that route'); 
          } 
 
          return array('distance' => $distance, 'time' => $time); 
           
      } 
      else 
      { 
          throw new Exception('Could not resolve URL'); 
      } 
  } 

It adds new fields into the database so you need to uninstall the module first, upload the updated file and then re-install the module.

The added fields allow a zone selector and specification of a max delivery distance. I noted that the original file would not add the country to the url, so at this point in time that is hardcoded (more work...!!!!), needs to be changed for your country.

NOTE: We are sorry that Frank is no longer with us.
We are grateful for all his contributions to the Zen Cart community.

26 Jul 2016, 12:31 PM
#20
lat9 avatar

lat9

Administrator

Join Date:
Sep 2009
Location:
Stuart, FL
Posts:
14,142
Plugin Contributions:
56

Re: Mileage based shipping module?

The shipping-method could be updated to make use of the Google Maps Distance API, using that to check the distance from the store's address to the customer's shipping address to make it more deterministic.