function classify($trainingData, $unknownPixels)
{
    $neighbors = [];
    foreach ($trainingData as $i => $knownDigit) {
        $neighbors[$i] = calculateDistance($unknownPixels, $knownDigit->Pixels);
    }
    asort($neighbors);
    return $trainingData[key($neighbors)]->Label;
}
function calculateMetrics($rawData)
{
    $data = array();
    $currentTruckId = $workingTruckId = NULL;
    $startTime = $stopTime = $runningTime = $mileage = $idleTime = $stopTimerStart = $stopTimerStop = NULL;
    $stopTimerArray = array();
    $prevTime = $prevLat = $prevLng = $prevMileage = NULL;
    foreach ($rawData as $entry) {
        $currentTruckId = $entry['Truck'];
        $time = $entry['TimeStamp'];
        $lat = $entry['Latitude'];
        $lng = $entry['Longitude'];
        if ($workingTruckId == NULL) {
            $workingTruckId = $currentTruckId;
        } elseif ($workingTruckId != $currentTruckId) {
            $data[] = compileDataForCalculateMetrics($workingTruckId, $startTime, $stopTime, $mileage, $idleTime, $runningTime, $stopTimerArray);
            unset($startTime, $stopTime, $runningTime, $idleTime, $mileage, $stopTimerStart, $stopTimerStop);
            unset($prevTime, $prevLat, $prevLng, $prevMileage);
            $stopTimerArray = array();
            $workingTruckId = $currentTruckId;
        }
        //Mileage
        $mileage += calculateDistance($lat, $lng, $prevLat, $prevLng);
        //StartTime
        if ($mileage > 0 && $startTime === NULL) {
            $startTime = $prevTime;
            $stopTime = $prevTime;
        }
        //StopTime
        if ($prevMileage !== $mileage) {
            $stopTime = $time;
        }
        //IdleTime
        if ($prevMileage === $mileage) {
            $idleTime += strtotime($time) - strtotime($prevTime);
        }
        //RunningTime
        if ($prevMileage < $mileage) {
            $runningTime += strtotime($time) - strtotime($prevTime);
        }
        //How long was each stop
        if (stopTimerCalculator($startTime, $prevMileage, $mileage, $time, &$stopTimerStart, &$stopTimerStop)) {
            $stopTimerArray[] = array('start' => $stopTimerStart, 'stop' => $stopTimerStop, 'lat' => $lat, 'lng' => $lng);
            unset($stopTimerStart, $stopTimerStop);
        }
        $prevTime = $time;
        $prevLat = $lat;
        $prevLng = $lng;
        $prevMileage = $mileage;
    }
    $data[] = compileDataForCalculateMetrics($workingTruckId, $startTime, $stopTime, $mileage, $idleTime, $runningTime, $stopTimerArray);
    return $data;
}
Exemplo n.º 3
0
<?php

include_once 'dbconfig.php';
include_once 'formula.php';
$phone_mac = "bc:d1:d3:cc:b5:df";
$ssid0 = "c0:a0:bb:01:5b:69";
$ssid1 = "00:1e:a6:28:18:50";
$ssid2 = "c0:a0:bb:01:5e:71";
$ssid3 = "";
$query0 = "SELECT `rssi0` FROM rssi_data WHERE `phone_mac` = '{$phone_mac}' AND `ssid0` = '{$ssid0}' ORDER BY id DESC LIMIT 1";
$query1 = "SELECT `rssi0` FROM rssi_data WHERE `phone_mac` = '{$phone_mac}' AND `ssid0` = '{$ssid1}' ORDER BY id DESC LIMIT 1";
$query2 = "SELECT `rssi0` FROM rssi_data WHERE `phone_mac` = '{$phone_mac}' AND `ssid0` = '{$ssid2}' ORDER BY id DESC LIMIT 1";
$query3 = "SELECT `rssi0` FROM rssi_data WHERE `phone_mac` = '{$phone_mac}' AND `ssid0` = '{$ssid3}' ORDER BY id DESC LIMIT 1";
$retval = mysql_query($query0, $conn);
$row = mysql_fetch_array($retval);
$rssi0 = $row['rssi0'];
$retval = mysql_query($query1, $conn);
$row = mysql_fetch_array($retval);
$rssi1 = $row['rssi0'];
$retval = mysql_query($query2, $conn);
$row = mysql_fetch_array($retval);
$rssi2 = $row['rssi0'];
$retval = mysql_query($query3, $conn);
$row = mysql_fetch_array($retval);
$rssi3 = $row['rssi0'];
echo calculateDistance($conn, $ssid0, $rssi0);
echo "<br>";
echo calculateDistance($conn, $ssid1, $rssi1);
echo "<br>";
echo calculateDistance($conn, $ssid2, $rssi2);
echo "<br>";
     die("Database connection failed:" . mysqli_connect_error() . "(" . mysqli_connect_errno() . ")");
 }
 //$menu_name = mysqli_real_escape_string($connection, $menu_name);
 $query = "INSERT INTO details (Timestamp, Category, Mobile, Vehicle, Sex, Height, Race, Latitude, Longitude, Address, Description)\n\t\t\t\t\tVALUES (NOW(),'{$category}', '{$phone_number}', '{$vehicle_no}', '{$sex}', '{$height}', '{$race}', '{$latitude}', \n\t\t\t\t\t\t\t'{$longitude}','{$address}','{$description}')";
 //echo $query;
 $result = mysqli_query($connection, $query);
 testForQuery($result);
 //calculate distance
 $query = "SELECT Latitude, Longitude FROM gcm_users WHERE 1";
 $result = mysqli_query($connection, $query);
 testForQuery($result);
 $count = 0;
 while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
     $latTo = $row["Latitude"];
     $longTo = $row["Longitude"];
     $distances[$count] = calculateDistance($latitude, $longitude, $latTo, $longTo);
     $count++;
 }
 sort($distances);
 $distanceArray = array("First" => $distances[0]);
 echo json_encode($distanceArray);
 /*here we send the information to registered police mobiles*/
 include_once './GCM.php';
 $gcm = new GCM();
 $query = "SELECT * FROM gcm_users WHERE 1";
 $result = mysqli_query($connection, $query);
 testForQuery($result);
 $message = "A " . $race . " " . $sex . " " . "with " . $height . " build has been reported to be involved in a " . $category . " at " . $address . "\n\n" . "Reported Description: " . $description . "\n\n" . "Reported Vehicle#: " . $vehicle_no;
 while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
     $registatoin_ids = array($row["gcm_regid"]);
     $message1 = array("alert" => $message, "addr" => $address);
Exemplo n.º 5
0
function parseXml($filePath, $gpxOffset, $distancetype)
{
    $points = null;
    $points->dt = array();
    $points->lat = array();
    $points->lon = array();
    $points->ele = array();
    $points->dist = array();
    $points->speed = array();
    $points->hr = array();
    $points->atemp = array();
    $points->cad = array();
    $points->grade = array();
    $points->maxTime = 0;
    $points->minTime = 0;
    $points->maxEle = 0;
    $points->minEle = 0;
    $points->totalEleUp = 0;
    $points->totalEleDown = 0;
    $points->avgSpeed = 0;
    $points->totalLength = 0;
    $gpx = simplexml_load_file($filePath);
    if ($gpx === FALSE) {
        return;
    }
    $gpx->registerXPathNamespace('10', 'http://www.topografix.com/GPX/1/0');
    $gpx->registerXPathNamespace('11', 'http://www.topografix.com/GPX/1/1');
    $gpx->registerXPathNamespace('gpxtpx', 'http://www.garmin.com/xmlschemas/TrackPointExtension/v1');
    $nodes = $gpx->xpath('//trk | //10:trk | //11:trk');
    //normal gpx
    if (count($nodes) > 0) {
        foreach ($nodes as $_trk) {
            $trk = simplexml_load_string($_trk->asXML());
            $trk->registerXPathNamespace('10', 'http://www.topografix.com/GPX/1/0');
            $trk->registerXPathNamespace('11', 'http://www.topografix.com/GPX/1/1');
            $trk->registerXPathNamespace('gpxtpx', 'http://www.garmin.com/xmlschemas/TrackPointExtension/v1');
            $trkpts = $trk->xpath('//trkpt | //10:trkpt | //11:trkpt');
            $lastLat = 0;
            $lastLon = 0;
            $lastEle = 0;
            $lastTime = 0;
            //$dist = 0;
            $lastOffset = 0;
            $speedBuffer = array();
            foreach ($trkpts as $trkpt) {
                $lat = $trkpt['lat'];
                $lon = $trkpt['lon'];
                $ele = $trkpt->ele;
                $time = $trkpt->time;
                $speed = (double) $trkpt->speed;
                $hr = 0;
                $atemp = 0;
                $cad = 0;
                $grade = 0;
                if (isset($trkpt->extensions)) {
                    $arr = json_decode(json_encode($trkpt->extensions), 1);
                    if (isset($arr['gpxtpx:TrackPointExtension'])) {
                        $tpe = $arr['gpxtpx:TrackPointExtension'];
                        $hr = @$tpe["gpxtpx:hr"];
                        $atemp = @$tpe["gpxtpx:atemp"];
                        $cad = @$tpe["gpxtpx:cad"];
                    } else {
                        if (isset($arr['TrackPointExtension'])) {
                            $tpe = $arr['TrackPointExtension'];
                            $hr = @$tpe["hr"];
                            $atemp = @$tpe["atemp"];
                            $cad = @$tpe["cad"];
                        }
                    }
                }
                if ($lastLat == 0 && $lastLon == 0) {
                    //Base Case
                    array_push($points->dt, strtotime($time));
                    array_push($points->lat, (double) $lat);
                    array_push($points->lon, (double) $lon);
                    array_push($points->ele, (double) round($ele, 2));
                    array_push($points->dist, (double) round($dist, 2));
                    array_push($points->speed, 0);
                    array_push($points->hr, (double) $hr);
                    array_push($points->atemp, (double) $atemp);
                    array_push($points->cad, (double) $cad);
                    array_push($points->grade, $grade);
                    $lastLat = $lat;
                    $lastLon = $lon;
                    $lastEle = $ele;
                    $lastTime = $time;
                } else {
                    //Normal Case
                    $offset = calculateDistance((double) $lat, (double) $lon, (double) $ele, (double) $lastLat, (double) $lastLon, (double) $lastEle, $distancetype);
                    $dist = $dist + $offset;
                    $points->totalLength = $dist;
                    if ($speed == 0) {
                        $datediff = (double) my_date_diff($lastTime, $time);
                        if ($datediff > 0) {
                            $speed = $offset / $datediff;
                        }
                    }
                    if ($ele != 0 && $lastEle != 0) {
                        $deltaEle = (double) ($ele - $lastEle);
                        if ((double) $ele > (double) $lastEle) {
                            $points->totalEleUp += $deltaEle;
                        } else {
                            $points->totalEleDown += $deltaEle;
                        }
                        $grade = $deltaEle / $offset * 100;
                    }
                    array_push($speedBuffer, $speed);
                    if ((double) $offset + (double) $lastOffset > $gpxOffset) {
                        //Bigger Offset -> write coordinate
                        $avgSpeed = 0;
                        foreach ($speedBuffer as $s) {
                            $avgSpeed += $s;
                        }
                        $avgSpeed = $avgSpeed / count($speedBuffer);
                        $speedBuffer = array();
                        $lastOffset = 0;
                        array_push($points->dt, strtotime($time));
                        array_push($points->lat, (double) $lat);
                        array_push($points->lon, (double) $lon);
                        array_push($points->ele, (double) round($ele, 2));
                        array_push($points->dist, (double) round($dist, 2));
                        array_push($points->speed, (double) round($avgSpeed, 1));
                        array_push($points->hr, $hr);
                        array_push($points->atemp, $atemp);
                        array_push($points->cad, $cad);
                        array_push($points->grade, (double) round($grade, 2));
                    } else {
                        //Smoller Offset -> continue..
                        $lastOffset = (double) $lastOffset + (double) $offset;
                    }
                }
                $lastLat = $lat;
                $lastLon = $lon;
                $lastEle = $ele;
                $lastTime = $time;
            }
            array_push($points->dt, null);
            array_push($points->lat, null);
            array_push($points->lon, null);
            array_push($points->ele, null);
            array_push($points->dist, null);
            array_push($points->speed, null);
            array_push($points->hr, null);
            array_push($points->atemp, null);
            array_push($points->cad, null);
            array_push($points->grade, null);
            unset($trkpts);
        }
        unset($nodes);
        try {
            array_pop($points->dt, null);
            array_pop($points->lat, null);
            array_pop($points->lon, null);
            array_pop($points->ele, null);
            array_pop($points->dist, null);
            array_pop($points->speed, null);
            array_pop($points->hr, null);
            array_pop($points->atemp, null);
            array_pop($points->cad, null);
            array_pop($points->grade, null);
            $_time = array_filter($points->dt);
            $_ele = array_filter($points->ele);
            $_dist = array_filter($points->dist);
            $_speed = array_filter($points->speed);
            $points->maxEle = max($_ele);
            $points->minEle = min($_ele);
            $points->totalLength = max($_dist);
            $points->maxTime = max($_time);
            $points->minTime = min($_time);
            $points->avgSpeed = array_sum($_speed) / count($_speed);
        } catch (Exception $e) {
        }
    } else {
        // gpx garmin case
        $gpx->registerXPathNamespace('gpxx', 'http://www.garmin.com/xmlschemas/GpxExtensions/v3');
        $nodes = $gpx->xpath('//gpxx:rpt');
        if (count($nodes) > 0) {
            $lastLat = 0;
            $lastLon = 0;
            $lastEle = 0;
            $dist = 0;
            $lastOffset = 0;
            // Garmin case
            foreach ($nodes as $rpt) {
                $lat = $rpt['lat'];
                $lon = $rpt['lon'];
                if ($lastLat == 0 && $lastLon == 0) {
                    //Base Case
                    array_push($points->lat, (double) $lat);
                    array_push($points->lon, (double) $lon);
                    array_push($points->ele, 0);
                    array_push($points->dist, 0);
                    array_push($points->speed, 0);
                    array_push($points->hr, 0);
                    array_push($points->atemp, 0);
                    array_push($points->cad, 0);
                    array_push($points->grade, 0);
                    $lastLat = $lat;
                    $lastLon = $lon;
                } else {
                    //Normal Case
                    $offset = calculateDistance($lat, $lon, 0, $lastLat, $lastLon, 0, $distancetype);
                    $dist = $dist + $offset;
                    if ((double) $offset + (double) $lastOffset > $gpxOffset) {
                        //Bigger Offset -> write coordinate
                        $lastOffset = 0;
                        array_push($points->lat, (double) $lat);
                        array_push($points->lon, (double) $lon);
                        array_push($points->ele, 0);
                        array_push($points->dist, 0);
                        array_push($points->speed, 0);
                        array_push($points->hr, 0);
                        array_push($points->atemp, 0);
                        array_push($points->cad, 0);
                        array_push($points->grade, 0);
                    } else {
                        //Smoller Offset -> continue..
                        $lastOffset = (double) $lastOffset + (double) $offset;
                    }
                }
                $lastLat = $lat;
                $lastLon = $lon;
            }
            unset($nodes);
        } else {
            //gpx strange case
            $nodes = $gpx->xpath('//rtept | //10:rtept | //11:rtept');
            if (count($nodes) > 0) {
                $lastLat = 0;
                $lastLon = 0;
                $lastEle = 0;
                $dist = 0;
                $lastOffset = 0;
                // Garmin case
                foreach ($nodes as $rtept) {
                    $lat = $rtept['lat'];
                    $lon = $rtept['lon'];
                    if ($lastLat == 0 && $lastLon == 0) {
                        //Base Case
                        array_push($points->lat, (double) $lat);
                        array_push($points->lon, (double) $lon);
                        array_push($points->ele, 0);
                        array_push($points->dist, 0);
                        array_push($points->speed, 0);
                        array_push($points->hr, 0);
                        array_push($points->atemp, 0);
                        array_push($points->cad, 0);
                        array_push($points->grade, 0);
                        $lastLat = $lat;
                        $lastLon = $lon;
                    } else {
                        //Normal Case
                        $offset = calculateDistance($lat, $lon, 0, $lastLat, $lastLon, 0, $distancetype);
                        $dist = $dist + $offset;
                        if ((double) $offset + (double) $lastOffset > $gpxOffset) {
                            //Bigger Offset -> write coordinate
                            $lastOffset = 0;
                            array_push($points->lat, (double) $lat);
                            array_push($points->lon, (double) $lon);
                            array_push($points->ele, 0);
                            array_push($points->dist, 0);
                            array_push($points->speed, 0);
                            array_push($points->hr, 0);
                            array_push($points->atemp, 0);
                            array_push($points->cad, 0);
                            array_push($points->grade, 0);
                        } else {
                            //Smoller Offset -> continue..
                            $lastOffset = (double) $lastOffset + (double) $offset;
                        }
                    }
                    $lastLat = $lat;
                    $lastLon = $lon;
                }
                unset($nodes);
            }
        }
    }
    unset($gpx);
    return $points;
}
Exemplo n.º 6
0
<?php

function calculateDistance($line)
{
    $line = preg_replace('/(\\s+)/i', '', $line);
    $line = preg_replace('/\\)\\(/i', ',', $line);
    $line = preg_replace('/(\\(|\\))/i', '', $line);
    $xy = explode(',', $line);
    $xa = intval($xy[0], 10);
    $ya = intval($xy[1], 10);
    $xb = intval($xy[2], 10);
    $yb = intval($xy[3], 10);
    $ab = sqrt(pow($xb - $xa, 2) + pow($yb - $ya, 2));
    return $ab;
}
//On parcours le fichiers en ignorant les lignes vides
$lines = file($argv[1], FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
foreach ($lines as $line) {
    $line = trim($line);
    print_r(calculateDistance($line));
    print_r("\n");
}
Exemplo n.º 7
0
        $bLat = $result->getLat();
        $bLon = $result->getLon();
    } elseif ($result->getType() == 'way' && $result->isClosed()) {
        $nodes = $result->getNodes();
        array_pop($nodes);
        $bLat = 0;
        $bLon = 0;
        foreach ($nodes as $node) {
            $n = $osm->getNode($node);
            $bLat += $n->getLat();
            $bLon += $n->getLon();
        }
        $bLat = $bLat / sizeof($nodes);
        $bLon = $bLon / sizeof($nodes);
    }
    $distance = calculateDistance($lat, $lon, $bLat, $bLon);
    // $distance = $distance * 1000; // convert to metres
    $result->distance = $distance;
    $result->lat = $bLat;
    $result->lon = $bLon;
}
usort($results, sortByDistance());
foreach ($results as $result) {
    $tags = $result->getTags();
    $name = $tags['name'];
    $addrStreet = $tags['addr:street'];
    $addrCity = $tags['addr:city'];
    $addrCountry = $tags['addr:country'];
    $addrHouseName = $tags['addr:housename'];
    $addrHouseNumber = $tags['addr:housenumber'];
    $openingHours = $tags['opening_hours'];
function scriptSecondPart($userDate)
{
    $segmentArray = array();
    $numberOfOrders = $GLOBALS["numberOfOrders"];
    $numberOfWarehouses = 0;
    // NUmber of warehouses
    $orderArray = $GLOBALS["orderArray"];
    $courierArray = $GLOBALS["courierArray"];
    $warehouseArray = $GLOBALS["warehouseArray"];
    // Adding warehouses to orderArray for distance calculation
    foreach ($warehouseArray as $warehouseUuid => $warehouse) {
        $orderArray[$warehouseUuid] = $warehouse;
        $numberOfOrders++;
        $numberOfWarehouses++;
    }
    // Если массив подходящих курьеров или заказов пуст, то заканчиваем
    if (count($courierArray) == 0 || $numberOfOrders - $numberOfWarehouses == 0) {
        if (count($courierArray) != 0) {
            echo "Нет подходящих заказов! Заказ должен иметь заполненным поля 'Склад', 'План. дата отгрузки'. Контрагент должен иметь заполненными поле 'Фактический адрес'.";
        } else {
            if ($numberOfOrders - $numberOfWarehouses != 0) {
                echo "Нет подходящих курьеров! Курьер должен иметь отметку в полях 'Курьер', 'Активен', все кастомные поля должны быть заполненными.";
            } else {
                echo "Нет подходящих заказов и курьеров! Курьер должен иметь отметку в полях 'Курьер', 'Активен', все кастомные поля должны быть заполненными.\n        Заказ должен иметь заполненным поля 'Склад', 'План. дата отгрузки'. Контрагент должен иметь заполненными поле 'Фактический адрес'.";
            }
        }
        printFirstFooter();
        return;
    }
    // Считаем попарные расстояния между заказами и складами
    foreach ($orderArray as $uuidFrom => $orderFrom) {
        foreach ($orderArray as $uuidTo => $orderTo) {
            if ($uuidFrom != $uuidTo) {
                if ($orderFrom->getAddressCoordinates() != $orderTo->getAddressCoordinates()) {
                    $segmentArray[$uuidFrom][$uuidTo] = calculateDistance($orderFrom->getAddressLatitude(), $orderFrom->getAddressLongitude(), $orderTo->getAddressLatitude(), $orderTo->getAddressLongitude());
                } else {
                    $segmentArray[$uuidFrom][$uuidTo] = 0;
                }
            }
        }
    }
    $amountOfAllOrders = 0;
    // Удаляем склады из массива заказов
    foreach ($warehouseArray as $warehouseUuid => $warehouse) {
        unset($orderArray[$warehouseUuid]);
    }
    if (count($orderArray) == 0) {
        echo "Не оказалось заказов с подходящими Яндексу адресами для распределения";
        printFirstFooter();
        return;
    }
    // Проверяем массив заказов на расположение относительно ТТК
    foreach ($orderArray as $orderUuid => $order) {
        $newOrderArray[$orderUuid] = new Order($order);
        $amountOfAllOrders++;
        $latitude = $newOrderArray[$orderUuid]->getLatitude();
        $longitude = $newOrderArray[$orderUuid]->getLongitude();
        $orderPoint = new Point($latitude, $longitude);
        $isInsideTTR = isInsideTTR($orderPoint);
        $newOrderArray[$orderUuid]->setIsInsideTTR($isInsideTTR);
    }
    // Сортируем заказы по времени доставки
    uasort($newOrderArray, "cmp");
    // Сортируем курьеров по времени прибытия
    uasort($courierArray, "cmp1");
    foreach ($warehouseArray as $warehouseUuid => $warehouse) {
        $currentWarehouseOrderArray = $newOrderArray;
        $currentCourierArray = $courierArray;
        // Удаляем товары не с текущего склада
        foreach ($currentWarehouseOrderArray as $orderUuid => $order) {
            if ($warehouseUuid != $order->getSourceStoreUuid()) {
                unset($currentWarehouseOrderArray[$orderUuid]);
            }
        }
        // Удаляем курьеров не с текущего склада
        foreach ($currentCourierArray as $courierUuid => $courier) {
            if ($warehouseUuid != $courier->getSourceStoreUuid()) {
                unset($currentCourierArray[$courierUuid]);
            }
        }
        // По очереди берем курьеров, которые работают и могут развозить/развозят заказы с этого склада
        foreach ($currentCourierArray as $courierUuid => $courier) {
            //Временные промежутки: каждый час, с 4 до 4(28)
            $isDayNotOver = true;
            $timeFrom = 4;
            $timeTo = 5;
            while ($isDayNotOver) {
                // Выделяем заказы, заканчивающиеся в этот час
                $currentTimePeriodOrderArray = array();
                foreach ($currentWarehouseOrderArray as $orderUuid => $order) {
                    if ($order->getDeliveryToHour() >= $timeTo && $order->getDeliveryFromHour() <= $timeFrom) {
                        //if ($order->getDeliveryFromHour() <= $timeFrom) {
                        $currentTimePeriodOrderArray[$orderUuid] = $order;
                    }
                }
                // Считаем число заказов, кончающихся в этот час и проверяем, есть ли они вообще
                $amountOfOrdersToBeAssigned = count($currentTimePeriodOrderArray);
                if ($amountOfOrdersToBeAssigned > 0) {
                    while ($courier->getCurrentAmountOfOrders() < $courier->getAmountOfOrders() && $courier->getCurrentTime() < $timeTo && $amountOfOrdersToBeAssigned > 0) {
                        // Сортируем массив расстояний от точки нахождения по возрастанию
                        $currentPosition = $courier->getCurrentPosition();
                        $currentTimeFromCourierPositionArray = $segmentArray[$currentPosition];
                        asort($currentTimeFromCourierPositionArray);
                        // Проверка на то, что кто-то из курьеров может взять этот товар
                        $courierCannotTake = true;
                        // Берем первый подходящий ( по длине, макс длине, весу, макс весу, общему времени доставки) заказ
                        foreach ($currentTimeFromCourierPositionArray as $orderUuid => $time) {
                            // Проверяем, существует ли такой заказ в списке заказов на данный временной промежуток
                            if (array_key_exists($orderUuid, $currentTimePeriodOrderArray)) {
                                $order = $currentTimePeriodOrderArray[$orderUuid];
                                $hours = (double) round($time / 50000, 1) . PHP_EOL;
                                //echo $time." ".$hours;
                                if (!$order->getIsTaken() && $courier->getMaxWeight() >= $order->getMaxWeight() && $courier->getMaxLength() >= $order->getMaxLength() && $courier->getCurrentLength() + $order->getWholeOrderLength() <= $courier->getLimitLength() && $courier->getCurrentWeight() + $order->getWholeOrderWeight() <= $courier->getLimitWeight() && ($courier->getCanWorkInsideTTR() || (!$order->getIsInsideTTR() || ($timeFrom <= 6 || $timeFrom >= 22)))) {
                                    $courier->increaseCurrentAmountOfOrders();
                                    $courier->increaseCurrentLengthBy($order->getWholeOrderLength());
                                    $courier->increaseCurrentWeightBy($order->getWholeOrderWeight());
                                    $courier->setCurrentPosition($order->getUuid());
                                    $courier->increaseCurrentTimeBy(1);
                                    $order->setIsTaken();
                                    $currentWarehouseOrderArray[$orderUuid]->setIsTaken();
                                    $newOrderArray[$orderUuid]->setIsTaken();
                                    $newOrderArray[$orderUuid]->setItineraryListNumber($courier->getCurrentAmountOfOrders());
                                    $newOrderArray[$orderUuid]->setCourier($courierUuid);
                                    $amountOfOrdersToBeAssigned--;
                                    $courierCannotTake = false;
                                    break;
                                }
                            }
                        }
                        if ($courierCannotTake) {
                            break;
                        }
                    }
                }
                if ($timeTo == 28) {
                    $isDayNotOver = false;
                } else {
                    $timeFrom = $timeTo;
                    $timeTo += 1;
                }
            }
        }
    }
    $counterOfNotTakenOrders = 0;
    foreach ($newOrderArray as $orderUuid => $order) {
        if (!$order->getIsTaken()) {
            $counterOfNotTakenOrders++;
        } else {
            //uploadChanges($orderUuid, $order->getCourier(), $order->getItineraryListNumber());
        }
    }
    $ordersForThisDateCounter = $GLOBALS['ordersForThisDateCounter'];
    $ordersValidForThisDateCounter = $GLOBALS['ordersValidForThisDateCounter'];
    $ordersWithValidContragentForThisDateCounter = $GLOBALS['ordersWithValidContragentForThisDateCounter'];
    $ordersYandexFailedCounter = $GLOBALS['ordersYandexFailedCounter'];
    $ordersNotValidForThisDateCounter = $ordersForThisDateCounter - $ordersValidForThisDateCounter;
    $ordersWithNotValidContragentForThisDateCounter = $ordersValidForThisDateCounter - $ordersWithValidContragentForThisDateCounter;
    $ordersCounter = count($newOrderArray) - $counterOfNotTakenOrders;
    $date = new DateTime($userDate, new DateTimeZone("Europe/Moscow"));
    $timeTomorrow = (string) $date->format("d.m.Y");
    $date = new DateTime($userDate . "+1 day", new DateTimeZone("Europe/Moscow"));
    $timeAfterTomorrow = (string) $date->format("d.m.Y");
    $summaryString = "<br><br><br><p align='center'>\n    Скрипт завершил работу!<br>\n    Из МойСклад было загружено {$ordersForThisDateCounter} заказов на период с {$timeTomorrow} 04:00 до {$timeAfterTomorrow} 04:00.<br>\n    У {$ordersNotValidForThisDateCounter} заказов были не заполнены поля \"Склад\" и/или \"План. дата отгрузки\".<br>\n    У {$ordersWithNotValidContragentForThisDateCounter} контрагентов было не заполнено поле \"Фактический адрес\".<br>\n    Для {$ordersYandexFailedCounter} заказов Яндекс не смог сопоставить адреса.<br>";
    if ($counterOfNotTakenOrders != 0) {
        $summaryString .= "{$counterOfNotTakenOrders} заказов не удалось распределить между существующими курьерами.<br>";
    }
    $summaryString .= "{$ordersCounter} заказов были распределены между курьерами и информация о них была обновлена в МойСклад.<br><br></p>";
    echo $summaryString;
    echo "<table border='1' align='center'>\n   <caption>Общая таблица распределенных заказов</caption>\n   <tr>\n    <th>Номер заказа</th>\n    <th>Адрес заказа</th>\n    <th>Время доставки</th>\n    <th>ФИО курьера</th>\n    <th>Номер заказа в листе курьера</th>\n    <th>Статус обработки</th>\n   </tr>";
    foreach ($newOrderArray as $orderUuid => $order) {
        $orderName = $order->getName();
        $orderAddress = $order->getAddress();
        $orderDeliveryToTime = $order->getDeliveryToTime();
        $orderCourierName = "";
        $orderItineraryListNumber = "";
        if ($order->getIsTaken()) {
            $courierArray[$order->getCourier()]->setOrdersIdArray($order->getUuid());
            $orderCourierName = $courierArray[$order->getCourier()]->getName();
            $orderItineraryListNumber = $order->getItineraryListNumber();
            $isOrderTaken = "Распределен";
        } else {
            $isOrderTaken = "Не распределен";
        }
        echo "<tr><td align='center'>" . $orderName . "</td><td align='center'>" . $orderAddress . "</td><td align='center'>" . $orderDeliveryToTime . "</td><td align='center'>" . $orderCourierName . "</td><td align='center'>" . $orderItineraryListNumber . "</td><td align='center'>" . $isOrderTaken . "</td></tr>";
    }
    echo "</table><br><br>";
    $GLOBALS["newOrderArray"] = $newOrderArray;
    foreach ($courierArray as $courierUuid => $courier) {
        $ordersIdArray = $courier->getOrdersIdArray();
        if (count($ordersIdArray) > 0) {
            uasort($ordersIdArray, "cmp2");
            $addressArray = array();
            $tableRowArray = array();
            $firstAddress = $warehouseArray[$courier->getSourceStoreUuid()]->getAddressCoordinates();
            array_push($addressArray, $firstAddress);
            echo "<table border='1' align='center'>\n                   <caption>Таблица распределенных заказов для " . $courier->getName() . "</caption>\n                   <tr>\n                    <th>Номер заказа в листе курьера</th>\n                    <th>Номер заказа</th>\n                    <th>Адрес заказа</th>\n                    <th>Время доставки</th>\n                    <th>Товары</th>\n                   </tr>";
            foreach ($ordersIdArray as $orderId) {
                $orderById = $newOrderArray[$orderId];
                array_push($addressArray, $orderById->getAddressCoordinates());
                $goodsArray = $orderById->getGoodOrderArray();
                $goodsString = "";
                foreach ($goodsArray as $goodId => $goodOrder) {
                    if ($goodOrder->getName() != "") {
                        $goodsString .= $goodOrder->getAmount() . " " . $goodOrder->getName() . "<br>";
                    }
                }
                $itineraryListNumber = $orderById->getItineraryListNumber();
                $name = $orderById->getName();
                $address = $orderById->getAddress();
                $toTime = $orderById->getDeliveryToTime();
                echo "<tr><td align='center'>" . $itineraryListNumber . "</td><td align='center'>" . $name . "</td><td align='center'>" . $address . "</td><td align='center'>" . $toTime . "</td><td align='center'>" . $goodsString . "</td></tr>";
                $newTableRow = array();
                $newTableRow["i"] = $itineraryListNumber;
                $newTableRow["n"] = $name;
                $newTableRow["a"] = $address;
                $newTableRow["t"] = $toTime;
                $newTableRow["g"] = $goodsString;
                $jsonNewTableRow = json_encode($newTableRow);
                array_push($tableRowArray, $jsonNewTableRow);
            }
            echo "</table>";
            $jsonAddressArray = json_encode($addressArray);
            $jsonTableRowArray = json_encode($tableRowArray);
            $jsonCourierName = json_encode($courier->getName());
            echo "\n            <form name='tableForm' method='post' action='table_script.php' target='_blank'>\n                <input type='hidden' name='jsonCourierName' value='" . $jsonCourierName . "'>\n                <input type='hidden' name='jsonTableRowArray' value='" . $jsonTableRowArray . "'>\n                <p align='center'><input type='submit' name='table_button' value='Вывести для печати'/></p>\n            </form>\n            <form name='yandexForm' method='post' action='yandex_map_script.php' target='_blank'>\n                <input type='hidden' name='jsonAddressArray' value='" . $jsonAddressArray . "'>\n                <p align='center'><input type='submit' name='yandex_button' value='Показать на карте'/></p>\n            </form><br><br>";
        } else {
            echo "\n            <table border='1' align='center'>\n                <caption>Таблица распределенных заказов для " . $courier->getName() . "</caption>\n                <tr>\n                 <th>Номер заказа в листе курьера</th>\n                 <th>Номер заказа</th>\n                 <th>Адрес заказа</th>\n                 <th>Время доставки</th>\n                 <th>Товары</th>\n                </tr>\n            </table><br><br>";
        }
    }
    printSecondFooter($userDate);
}
Exemplo n.º 9
0
        fwrite($outputFile, $disambiguatorRVal["DisambiguationTime"] . "\t");
        if ($disambiguatorRVal["TermArray"]) {
            // the TermArray is false if the disambiguator timed out
            $results = $disambiguatorRVal["SortedResults"];
            $scores = $disambiguatorRVal["Scores"];
            $phraseCount = count($results);
            fwrite($outputFile, $phraseCount . "\t");
            if ($results) {
                $calcLat = $results[0]["lat"];
                $calcLon = $results[0]["lon"];
                fwrite($outputFile, $calcLat . "\t" . $calcLon);
            } else {
                fwrite($outputFile, "N/A\tN/A");
            }
            for ($i = 0; $i < min($phraseCount, 5); $i++) {
                fwrite($outputFile, "\t" . calculateDistance($realLat, $realLon, $results[$i]["lat"], $results[$i]["lon"]));
            }
            for ($i = $phraseCount; $i < 5; $i++) {
                fwrite($outputFile, "\t");
            }
            for ($i = 0; $i < min($phraseCount, 5); $i++) {
                fwrite($outputFile, "\t" . $scores[$i]);
            }
            for ($i = $phraseCount; $i < 5; $i++) {
                fwrite($outputFile, "\t");
            }
        }
        fwrite($outputFile, "\n");
    }
}
fclose($inputFile);
     $coordinateArray = array("26.701864,-80.051957");
     //the route array will contain the shortest calculated route.
     $route = array();
     //Associate ClientIDs with coordinates
     for ($i = 0; $i < count($scheduledClients); $i++) {
         array_push($coordinateArray, getCoordinates($scheduledClients[$i]));
     }
     //$coordinateArray now contains a list of coordinates fit to submit to the calculateDistance() function
     //we can now generate a waypoint list
     $numWaypoints = count($coordinateArray + 1);
     //we add +1 because we have to include meal pick-up point.
     for ($i = 0; $i < $numWaypoints; $i++) {
         $closestLocation = $coordinateArray[$i];
         for ($j = $i + 1; $j < $numWaypoints; $j++) {
             $shortestDistance = 0;
             $distance = calculateDistance($coordinateArray[$i], $coordinateArray[$j]);
             if ($distance < $shortestDistance) {
                 $shortestDistance = $distance;
                 $closestLocation = $coordinateArray[$j];
             }
             //shortest distance conditional
         }
         //inner loop
         array_push($route, $closestLocation);
     }
     //outer loop
     //we now have an array, $route, which contains the shortest calculated route.
     //all we need to do here is get that information to the map page, where
     //we can call the google API to generate the directions for us.
     //unfortunately I don't know how to do this just yet.
 }
Exemplo n.º 11
0
// pr($userLat . ' / ' . $userLon . ' / ' . $max);
// TODO: sanitize lat / lon?
// Where we'll store any place within a X mile radius
$nearbyPlaces = array();
// Set db query
$query = "SELECT * FROM `venues`";
// $dblink is created in include/_db_connex.php
$statement = $dblink->prepare($query);
// Execute query, fetching results by associative index
$statement->execute();
$results = $statement->fetchAll(PDO::FETCH_ASSOC);
// Parse through results tagging each venue with proximity from user
foreach ($results as $row) {
    $current_venue_latlon = array("lat" => $row["lat"], "lon" => $row["lon"]);
    // user position, venue position, geofence radius
    $distance = calculateDistance(array("lat" => $userLat, "lon" => $userLon), $current_venue_latlon, GEOFENCE_RADIUS);
    // End distance = calcDist
    // Append distance column, add to nearbyPlaces list
    $row["distance"] = $distance;
    array_push($nearbyPlaces, $row);
    // If we want to limit results
    //if($distance <= $some_passed_in_distance {
    //			array_push($placeList, $thisPlace);
    //}
    // DEBUG
    // pr($row['name'] . ' - ' . $distance);
}
// End foreach parse through db results
// sort place array, distance ascending;
// ensures we get only places within our radius;
// will have to order again in front end