Jump to content

Recommended Posts

ich habe eine Website. dort habe ich verschiedene Anbieter - also Umzugunternehmen, die Ihren Service anbieten. Ziel sollte nun sein, dass irgend ein potentieller Kunde auf meine Homepage kommt. dort findet er - ähnlich wie auf booking.com ein Suchfenster. Dort kann er eingeben Ort (wo zügle, sprich von wo ziehe ich um? dann an welchem datum und als drittes - will ich nur das fahrzeug mieten - oder soll ein helfer dabei sein oder zwei helfer?) Das wichtigste hier ist nun das WO! ich habe verschiedenste Firmen von verschiedensten Orten aus der Schweiz. der kunde soll mit WO die nähesten Firmen angezeigt bekommen, inkl. Distanz in km. Ausserdem soll auch gleich stehen wieviel der Anfahrtsweg kostet. Ich möchte nun ein Tool /addon für Prestashop erstellen, dass genau das kann. Folgende Datenbanken sind erstellt: ps_distance_swiss_locations. hier sind alle plz, ort und latitude und longitude von der schweiz integriert. Dann: ps_distance_products: alle Produkte / Firmen sind dort mit longitude und latitude  versehen. dann: ps_distance_price_per_km: jede firma hat preis per km. datenbank: ps_distance_price_per_km. zusätzlich habe ich mich auf openrouteservice.com registriert und den entsprechenden Api erhalten. Leider funktioniert das modul einfach nicht. ich bin am verzweifeln. kann mir jemand helfen? hier die datei "distance.php": 

<?php
/**
 * 2007-2024 PrestaShop
 * NOTICE OF LICENSE
 * This source file is subject to the Academic Free License (AFL 3.0)
 * that is bundled with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://opensource.org/licenses/afl-3.0.php
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to [email protected] so we can send you a copy immediately.
 *
 * DISCLAIMER
 * Do not edit or add to this file if you wish to upgrade PrestaShop to newer
 * versions in the future. If you wish to customize PrestaShop for your
 * needs please refer to http://www.prestashop.com for more information.
 * @author    Niklaus Hartmann
 * @copyright 2007-2024 PrestaShop SA
 * @license   http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
 */

if (!defined('_PS_VERSION_')) {
    exit;
}

class Distance extends Module
{
    public function __construct()
    {
        $this->name = 'distance';
        $this->tab = 'search_filter';  // Correct tab
        $this->version = '1.0.0';  // Ensure version matches with config.xml
        $this->author = 'Niklaus Hartmann';
        $this->bootstrap = true;  // Enable Bootstrap

        // Added ps_versions_compliancy for version checking
        $this->ps_versions_compliancy = array('min' => '1.7.0.0', 'max' => _PS_VERSION_);

        parent::__construct();
        $this->displayName = $this->l('Distance Calculator with OpenRouteService');  // Updated display name
        $this->description = $this->l('Module to calculate distance using OpenRouteService API.');  // Correct description
    }

    public function install()
    {
        return parent::install() && $this->registerHook('header');
    }

    public function hookHeader()
    {
        $this->context->controller->addJS($this->_path.'/views/js/front.js');
        $this->context->controller->addCSS($this->_path.'/views/css/front.css');

        $this->context->smarty->assign(array(
            'search_action_url' => $this->context->link->getModuleLink('distance', 'search'),
        ));

        return $this->display(__FILE__, 'views/templates/front/search.tpl');
    }

    public function getContent()
    {
        // Settings form here
    }

    public function calculateDistance($start_coords, $end_coords)
    {
        $api_key = '5b3ce3597851110001cf6248c93c453e9c1a42819c86b7f85ca1aae2';
        $url = 'https://api.openrouteservice.org/v2/directions/driving-car';

        $request_data = [
            'coordinates' => [$start_coords, $end_coords],
            'format' => 'json',
        ];

        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Authorization: ' . $api_key,
            'Content-Type: application/json',
        ]);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($request_data));
        $response = curl_exec($ch);
        curl_close($ch);

        $data = json_decode($response, true);

        if (isset($data['routes'][0]['summary']['distance'])) {
            return $data['routes'][0]['summary']['distance'];  // Distance in meters
        }

        return false;
    }
}
. hier der "SearchController.php": 

<?php
/**
 * 2007-2024 PrestaShop
 * NOTICE OF LICENSE
 * This source file is subject to the Academic Free License (AFL 3.0)
 * that is bundled with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://opensource.org/licenses/afl-3.0.php
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to [email protected] so we can send you a copy immediately.
 *
 * DISCLAIMER
 * Do not edit or add to this file if you wish to upgrade PrestaShop to newer
 * versions in the future. If you wish to customize PrestaShop for your
 * needs please refer to http://www.prestashop.com for more information.
 * @author    Niklaus Hartmann
 * @copyright 2007-2024 PrestaShop SA
 * @license   http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
 */

if (!defined('_PS_VERSION_')) {
    exit;
}

class Distance extends Module
{
    public function __construct()
    {
        $this->name = 'distance';
        $this->tab = 'search_filter'; 
        $this->version = '1.0.0'; 
        $this->author = 'Niklaus Hartmann';
        $this->bootstrap = true; 
        parent::__construct();
        $this->displayName = $this->l('Distance Calculator with OpenRouteService'); 
        $this->description = $this->l('Module to calculate distance using OpenRouteService API.'); 
    }

    public function install()
    {
        return parent::install() && $this->registerHook('header');
    }

    public function hookHeader()
    {
        $this->context->controller->addJS($this->_path.'/views/js/front.js');
        $this->context->controller->addCSS($this->_path.'/views/css/front.css');

        $this->context->smarty->assign(array(
            'search_action_url' => $this->context->link->getModuleLink('distance', 'search'),
        ));

        return $this->display(__FILE__, 'views/templates/front/search.tpl');
    }

    public function getContent()
    {
        $output = null;

        if (Tools::isSubmit('submit'.$this->name)) {
            $apiKey = strval(Tools::getValue('DISTANCE_API_KEY'));
            if (!$apiKey || empty($apiKey) || !Validate::isGenericName($apiKey)) {
                $output .= $this->displayError($this->l('Invalid API Key'));
            } else {
                Configuration::updateValue('DISTANCE_API_KEY', $apiKey);
                $output .= $this->displayConfirmation($this->l('Settings updated'));
            }
        }

        return $output.$this->displayForm();
    }

    public function displayForm()
    {
        $defaultLang = (int)Configuration::get('PS_LANG_DEFAULT');

        $fieldsForm[0]['form'] = array(
            'legend' => array(
                'title' => $this->l('Settings'),
            ),
            'input' => array(
                array(
                    'type' => 'text',
                    'label' => $this->l('API Key'),
                    'name' => 'DISTANCE_API_KEY',
                    'size' => 20,
                    'required' => true
                )
            ),
            'submit' => array(
                'title' => $this->l('Save'),
                'class' => 'btn btn-default pull-right'
            )
        );

        $helper = new HelperForm();

        $helper->module = $this;
        $helper->name_controller = $this->name;
        $helper->token = Tools::getAdminTokenLite('AdminModules');
        $helper->currentIndex = AdminController::$currentIndex.'&configure='.$this->name;

        $helper->default_form_language = $defaultLang;
        $helper->allow_employee_form_lang = Configuration::get('PS_BO_ALLOW_EMPLOYEE_FORM_LANG') ? Configuration::get('PS_BO_ALLOW_EMPLOYEE_FORM_LANG') : 0;

        $helper->title = $this->displayName;
        $helper->show_toolbar = true;
        $helper->toolbar_scroll = true;
        $helper->submit_action = 'submit'.$this->name;
        $helper->toolbar_btn = array(
            'save' => array(
                'desc' => $this->l('Save'),
                'href' => AdminController::$currentIndex.'&configure='.$this->name.'&save'.$this->name.'&token='.Tools::getAdminTokenLite('AdminModules'),
            ),
            'back' => array(
                'href' => AdminController::$currentIndex.'&token='.Tools::getAdminTokenLite('AdminModules'),
                'desc' => $this->l('Back to list')
            )
        );

        $helper->fields_value['DISTANCE_API_KEY'] = Configuration::get('DISTANCE_API_KEY');

        return $helper->generateForm($fieldsForm);
    }

    public function calculateDistance($start_coords, $end_coords)
    {
        $api_key = Configuration::get('DISTANCE_API_KEY');
        $url = 'https://api.openrouteservice.org/v2/directions/driving-car';

        $request_data = [
            'coordinates' => [$start_coords, $end_coords],
            'format' => 'json',
        ];

        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Authorization: ' . $api_key,
            'Content-Type: application/json',
        ]);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($request_data));
        $response = curl_exec($ch);
        curl_close($ch);

        $data = json_decode($response, true);

        if (isset($data['routes'][0]['summary']['distance'])) {
            return $data['routes'][0]['summary']['distance'];  
        }

        return false;
    }

    public function geocodeLocation($plz, $city)
    {
        return [
            'lat' => 47.3768866,
            'lng' => 8.541694,    
        ];
    }

    public function callIsochronesAPI($locations, $range)
    {
        return [
            'isochrone' => 'example data', 
        ];
    }
}

class DistanceSearchModuleFrontController extends ModuleFrontController
{
    public function initContent()
    {
        parent::initContent();

        $plz = Tools::getValue('plz');
        $city = Tools::getValue('city');
        $helpers = Tools::getValue('helpers');
        $range = Tools::getValue('range', 300);

        if ($plz && $city) {
            $location = $this->module->geocodeLocation($plz, $city);
            if ($location) {
                $locations = [[$location['lng'], $location['lat']]];
                $isochroneData = $this->module->callIsochronesAPI($locations, $range);
                $this->context->smarty->assign(array(
                    'isochroneData' => $isochroneData,
                    'plz' => $plz,
                    'city' => $city,
                    'helpers' => $helpers,
                    'range' => $range,
                ));
            } else {
                $this->context->smarty->assign('isochroneData', []);
            }
        }

        $this->setTemplate('module:distance/views/templates/front/results.tpl');
    }
}
?>
hier die datei "search.tpl": 

{/**
 * 2007-2024 PrestaShop
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Academic Free License (AFL 3.0)
 * that is bundled with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://opensource.org/licenses/AFL-3.0.php
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to [email protected] so we can send you a copy immediately.
 *
 * DISCLAIMER
 *
 * Do not edit or add to this file if you wish to upgrade PrestaShop to newer
 * versions in the future. If you wish to customize PrestaShop for your
 * needs please refer to http://www.prestashop.com for more information.
 */

<div class="distance-module">
    <h3>{l s='Find Products by Postal Code and City' mod='distance'}</h3>

    <p>{l s='Enter your postal code (PLZ) and city to find products near you.' mod='distance'}</p>

    <form method="get" action="{$search_action_url}">
        <div class="form-group">
            <label for="plz">{l s='Postal Code (PLZ)' mod='distance'}</label>
            <input type="text" name="plz" id="plz" class="form-control" placeholder="Enter Postal Code (PLZ)" required>
        </div>

        <div class="form-group">
            <label for="city">{l s='City' mod='distance'}</label>
            <input type="text" name="city" id="city" class="form-control" placeholder="Enter City" required>
        </div>

        <button type="submit" class="btn btn-primary">{l s='Search' mod='distance'}</button>
    </form>
</div>


 und hier die datei "results.tpl": 

{**
 * 2007-2024 PrestaShop
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Academic Free License (AFL 3.0)
 * that is bundled with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://opensource.org/licenses/AFL-3.0.php
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to [email protected] so we can send you a copy immediately.
 *
 * DISCLAIMER
 *
 * Do not edit or add to this file if you wish to upgrade PrestaShop to newer
 * versions in the future. If you wish to customize PrestaShop for your
 * needs please refer to http://www.prestashop.com for more information.
 *}

<div class="distance-results">
    <h3>{l s='Search Results' mod='distance'}</h3>

    {if isset($searchResults) && $searchResults|@count > 0}
        <div class="results-container">
            <ul>
                {foreach from=$searchResults item=product}
                    <li>
                        <p><strong>{$product.name}</strong></p>
                        <p>{l s='Distance' mod='distance'}: {$product.distance|floatval} km</p>
                        <p>{l s='Total Price' mod='distance'}: {$product.price|floatval} CHF</p>
                    </li>
                {/foreach}
            </ul>
        </div>
    {else}
        <p>{l s='No products found.' mod='distance'}</p>
    {/if}
</div>
DENKE das sind die wichtigsten Dateien um mir eine Rückmeldung zu geben. vielen Dank.

Link to comment
Share on other sites

Ich kann da leider nichts beitragen, möchte dich aber darauf hinweisen, dass du deinen Beitrag bestmöglich versteckt hast, hier sollen nur fertige kostenlose Module zum Download angeboten werden, dein Beitrag wäre sicher im Entwickler-Unterforum besser aufgehoben, außerdem solltest du einen "etwas" aussagekräftigeren Threadtitel wählen!

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...