Feeling lucky initial version

master
Goncalo Bras 2017-09-02 19:09:19 +01:00
parent 7a16b5220d
commit 2be9b28ca4
8 changed files with 378 additions and 70 deletions

View File

@ -6,6 +6,7 @@ use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Cache;
use App\Vehicle;
use App\Vehicles;
@ -14,16 +15,22 @@ use App\Station;
use App\Fuel;
use App\Fuels;
use Illuminate\Support\Facades\Input;
use Redirect;
use Validator;
use Hash;
use Illuminate\Support\Facades\Response;
use Illuminate\Support\Facades\Session;
class UserPageController extends Controller
{
private $apiKey = 'AIzaSyDsZDCiU1k6mSuywRRL88xxXY-81RMEU7s';
private $address;
private $coordinates;
private $distanceY = 5;
private $distanceX = 5;
public function index(Request $request)
{
@ -38,14 +45,15 @@ class UserPageController extends Controller
$vehicleData = Vehicle::where('id', $request->upSelectVehicle)
->first();
if ($request->points) {
var_dump($request->points);
}
return view('planRoute', ['name'=>$user->name, 'vehicles' => $vehicles, 'vehicleData' => $vehicleData]);
}
public function add(Request $request)
{
//$fuels =$request->upFuelType;
$data = ['brand' => $request->brand, 'model' => $request->model, 'consumption' => $request->consumption];
Vehicle::insert($data);
@ -56,7 +64,7 @@ class UserPageController extends Controller
foreach($request->upFuelType as $fuel){
$currentFuel = Fuel::where('name', 'like', "%$fuel%")->select('id')->first();
$currentFuel = Fuel::where('name', 'like', "$fuel")->select('id')->first();
Fuels::insert(['vehicle_id'=>$vehicleId, 'fuel_id'=>$currentFuel->id]);
}
@ -118,7 +126,7 @@ class UserPageController extends Controller
Vehicle::where('id', $id)->update($data);
Fuels::where('vehicle_id', $id)->delete();
foreach($request->upFuelType as $fuel){
$currentFuel = Fuel::where('name', 'like', "%$fuel%")->select('id')->first();
$currentFuel = Fuel::where('name', 'like', "$fuel")->select('id')->first();
Fuels::insert(['vehicle_id'=>$id, 'fuel_id'=>$currentFuel->id]);
}
return redirect(route('manageVehicles'));
@ -268,11 +276,7 @@ class UserPageController extends Controller
"latitude" => $value->latitude,
"longitude" => $value->longitude
];
array_push($response["stations"], $array /*[
'id' => $district->id,*/
//'name' =>
//]
);
array_push($response["stations"], $array );
}
@ -336,7 +340,160 @@ class UserPageController extends Controller
return Redirect::back()->withSuccess('Message sent!');
}
public function feelingLucky(Request $request){
//echo "$request->upOrigin\n$request->upDestination\n$request->"
public function receiveCoordinates(Request $request){
Session::forget('coordinates');
Session::forget('vehicleId');
Session::forget('autonomyKm');
// Cache::forget('latitudeOrigin');
// Cache::forget('longitudeOrigin');
Session::put("coordinates", $request->points);
Session::put("vehicleId", $request->vehicleId);
Session::put("autonomyKm", $request->distance);
Session::put("latitudeOrigin",$request->latitudeOrigin);
Session::put("longitudeOrigin", $request->longitudeOrigin);
Cache::put('latitudeOrigin', $request->latitudeOrigin, 4);//2 minutes
Cache::put('longitudeOrigin', $request->longitudeOrigin, 4);
/*$request->latitude = null;
$request->longitude = null;*/
return Response::json(["data"=> $data, "vehicleId"=> vehicleId, $request->vehicleId=> distance, "latitudeOrigin"=> $request->latitudeOrigin, "longitudeOrigin"=> $request->longitudeOrigin]);
}
public function receivedCoordinates(Request $request){
$data = Session::get("coordinates");
$vehicleData = Session::get("vehicleId");
$autonomyKmData = Session::get("autonomyKm");
$latitudeOrigin = Cache::get('latitudeOrigin');//Session::get("latitudeOrigin");
$longitudeOrigin = Cache::get('longitudeOrigin');//Session::get("longitudeOrigin");
$data = json_encode($data);
$data = json_decode($data, true);
$stationsArray = array();
// echo "latitude origin $latitudeOrigin";
// echo "longitude origin $longitudeOrigin";
$index=0;
$station = null;
$outOfRange = false;
//echo Auth::user()->id;
//user's vehicle fuel types
$vehicleFuels = Vehicles::join('vehicle', 'vehicles.vehicle_id', 'vehicle.id')
->join('fuels', 'fuels.vehicle_id', 'vehicle.id')
->join('fuel', 'fuels.fuel_id', 'fuel.id')
->where('vehicles.user_id', '=', Auth::user()->id)
->where('vehicle.id', '=', $vehicleData)
->select('fuel.name as fuelName')
->get();
//echo $vehicleFuels;
$stations = null;
if(empty($stationsArray)){
//iterate all stations
//var_dump( $data);
foreach ($data as $key => $value) {
$latitude = $data[$key]["latitude"];
$longitude = $data[$key]["longitude"];
/*echo "latitude: ".$latitude."<br>";
echo $longitude."<br><br>";*/
//formula to calculate near points
$newLatitudePlus = $latitude + ($this->distanceY / 6371) * (180 / pi());
$newLongitudePlus = $longitude + ($this->distanceX / 6371) * (180 / pi()) / cos($latitude * pi()/180);
$newLatitudeMinus = $latitude + ((-$this->distanceY) / 6371) * (180 / pi());
$newLongitudeMinus = $longitude + ((-$this->distanceX) / 6371) * (180 / pi()) / cos($latitude * pi()/180);
//stations near
$stations = Station::join('location', 'station.location', 'location.id')
->join('fuel_price', 'station.fuel_price', 'fuel_price.id')
->join('district', 'station.district', 'district.id')
->where('location.latitude', '<', $newLatitudePlus)
->where('location.latitude', '>', $newLatitudeMinus)
->where('location.longitude', '<', $newLongitudePlus)
->where('location.longitude', '>', $newLongitudeMinus);
//filter the stations that have the vehicle's fuel
foreach ($vehicleFuels as $key => $value) {
$stations->whereNotNull("fuel_price.$value->fuelName");
}
foreach ($vehicleFuels as $key => $value) {
$stations->orderBy("fuel_price.$value->fuelName");
}
$stations->select('station.name as stationName', 'station.brand as stationBrand', 'district.name as district', 'latitude', 'longitude', 'petrol_95_simple', 'petrol_95', 'petrol_98_simple', 'petrol_98', 'diesel_simple', 'diesel', 'gpl');
$stationsResult = $stations->get();
//echo $stationsResult;
//Create a stations array
foreach($stationsResult as $stationResult){
// echo $station;
array_push($stationsArray, $stationResult);
}
}
}
//order array by price
usort($stationsArray, array($this, "sortByPriceLower"));
do{
$station = $stationsArray[$index];
if ($station!=null) {
$latitudeStation = $station->latitude;
$longitudeStation = $station->longitude;
/* echo "latitude destination: ".$latitudeDestination;
echo "longitude destination: ".$longitudeDestination;*/
$distance = $this->checkStationDistance($latitudeOrigin, $longitudeOrigin, $latitudeStation, $longitudeStation);
/* echo "distance: $distance<br>";
echo "autonomy data: $autonomyKmData";*/
if ($distance<$autonomyKmData) {
$outOfRange = false;
try{
$statusCode = 200;
$response['station'] = $station ;
}catch (Exception $e){
$statusCode = 400;
}finally{
return Response::json($response, $statusCode);
}
}else{
$outOfRange = true;
$index++;
}
}
// }
}while($outOfRange==true && $index<count($stationsArray));
//}
// }
}
private function checkStationDistance( $latitudeOrigin, $longitudeOrigin, $latitudeDestination, $longitudeDestination){
$origin = "$latitudeOrigin,$longitudeOrigin";
$destination = "$latitudeDestination,$longitudeDestination";
$link = "https://maps.googleapis.com/maps/api/distancematrix/json?origins=$origin&destinations=$destination&key=$this->apiKey";
$array = json_decode(file_get_contents($link, true), true);
$distance = $array['rows'][0]['elements'][0]['distance']['value'];
$distance = $distance/1000;//m to km
return $distance;
}
public function sortByPriceLower($station1, $station2){
//echo round($station2[0]->petrol_95_simple, 3) - round($station1[0]->petrol_95_simple, 3);
//if (round($station2[0]->petrol_95_simple, 3) < round($station1[0]->petrol_95_simple, 3)) {
$result = round($station2->petrol_95_simple, 3) - round($station1->petrol_95_simple, 3);
$result<0?-1:1;
return $result;
}
}

View File

@ -12,6 +12,6 @@ class VerifyCsrfToken extends BaseVerifier
* @var array
*/
protected $except = [
'login',
'login', 'receiveCoords'
];
}

View File

@ -16,7 +16,7 @@ class CreateFuelsTable extends Migration
Schema::create('fuels', function (Blueprint $table) {
$table->increments('id');
$table->integer('vehicle_id');
$table->integer('fuel_id');
$table->integer('fuels_id');
});
}

View File

@ -6,6 +6,7 @@ use App\Location;
use App\FuelPrice;
use App\District;
use App\User;
use App\Fuel;
class AllTableSeeder extends Seeder
{
@ -19,7 +20,7 @@ class AllTableSeeder extends Seeder
public function run()
{
$all = array();
/* $all = array();
array_push($all, file_get_contents('public/files/Postos-Alves-Bandeira.geojson'));
array_push($all, file_get_contents('public/files/Postos-BP.geojson'));
array_push($all, file_get_contents('public/files/Postos-Cepsa.geojson'));
@ -52,22 +53,15 @@ class AllTableSeeder extends Seeder
$descriptionString = html_entity_decode($description, ENT_QUOTES);
$descriptionString = preg_replace("/(<div[^>]*>)(.*?)(<\/div>)/i", '$2', $descriptionString);
// Convert HTML entities to characters
// Remove characters other than the specified list.
/*FUEL TYPES*/
//FUEL TYPES
preg_match_all('/(title=")(.*?)(")/', $descriptionString, $fuel);
//print_r($fuel[2]);
/*PRICES*/
//PRICES
$fuelPriceArray = array();//main array
$fuelKeys = array();//fuel => price array
/*foreach($fuel[2] as $key => $value){
echo $value;
}
array_push($fuelPriceArray, $fuelKeys);
*/
preg_match_all('/\d.\d\d\d+/', $descriptionString, $priceMatches);
$fuelPriceArray = $this->array_combine2($fuel[2], $priceMatches[0]);
@ -94,13 +88,7 @@ class AllTableSeeder extends Seeder
$priceId = FuelPrice::insertGetId($fuelPrices);
/*
foreach($priceMatches[0] as $key => $value){
echo $value;
}*/
/*Coordinates and Insert Coordinates*/
//Coordinates and Insert Coordinates
$latitude = $feature->geometry->coordinates[1];
$longitude = $feature->geometry->coordinates[0];
$locationId = Location::insertGetId(['latitude' => $latitude, 'longitude' => $longitude]);
@ -118,9 +106,11 @@ class AllTableSeeder extends Seeder
}
}
}*/
$data = array(["id" => 1, "name" => "Gestor", "email" => "gestor@gmail.com", "password" => Hash::make(123123123), "is_activated" => 1]);
User::insert($data);
$fuelsData = array(["id" => 1, "name" => "petrol_95_simple"], ["id" => 2, "name" => "petrol_95"], ["id" => 3, "name" => "petrol_98_simple"], ["id" => 4, "name" => "petrol_98"], ["id" => 5, "name" => "diesel_simple"], ["id" => 6, "name" => "diesel"], ["id" => 7, "name" => "gpl"]);
Fuel::insert($fuelsData);
}

View File

@ -1,9 +1,10 @@
"use strict";
var js = $(document).ready(function(){
var waypts = [];
var waypts = new Array();
getLocation();
var routePoints = [];
var mapUP;
$("#district").val(localStorage.getItem("district"));
@ -123,7 +124,7 @@ var array2;
var pt = {lat: parseFloat(coordinates.latitude), lng: parseFloat(coordinates.longitude)};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
zoom: 7,
center: pt
});
@ -136,7 +137,7 @@ var array2;
markers.forEach(function(marker){
for (var i = 0; i < marker.length; i++) {
//console.log(parseFloat(marker[i].latitude)+" lng"+ parseFloat(marker[i].longitude));
console.log(parseFloat(marker[i].latitude)+" lng"+ parseFloat(marker[i].longitude));
new google.maps.Marker({
position: {"lat": parseFloat(marker[i].latitude), "lng": parseFloat(marker[i].longitude)},
label: labels[labelIndex++ % labels.length],
@ -241,20 +242,7 @@ var array2;
}
$('#landingSearch').click(function(){
/*$.ajax({
url: "api/stations",
type: "GET",
dataType: "json",
//delay: 50,
//data: request,
success: function (data) {
response($.map(data["districts"] , function (key, value) {
//console.log(data["districts"][value]);
return data["districts"][value];
}))}
});*/
initMap();
});
@ -274,8 +262,8 @@ var array2;
var directionsService = new google.maps.DirectionsService;
var directionsDisplay = new google.maps.DirectionsRenderer;
var mapUP = new google.maps.Map(document.getElementById('mapUP'), {
zoom: 10,
mapUP = new google.maps.Map(document.getElementById('mapUP'), {
zoom: 7,
center: pt
});
directionsDisplay.setMap(mapUP);
@ -307,7 +295,7 @@ var array2;
calculateAndDisplayRoute(directionsService, directionsDisplay);
markers.push(getStationsUP());
//console.table(markers[0][1]);
var myLatLng = {"lat": 39.7495, "lng":-8.8077};
//var myLatLng = {"lat": 39.7495, "lng":-8.8077};
var labels = '12345';
var labelIndex = 0;
/*for(var j=0;j<markers[0].length;j++){
@ -370,23 +358,188 @@ var array2;
var points = [];
var key = "AIzaSyDsZDCiU1k6mSuywRRL88xxXY-81RMEU7s";
coordinates = getCoordinates();
alert("origem: "+$("#upOrigin").val() +" "+coordinates.origin.latitude+" destino: "+$("#upDestination").val()+" "+coordinates.destination.latitude);
$.ajax({
//async: false,
crossDomain: true,
dataType: "json",
var link = "https://maps.googleapis.com/maps/api/elevation/json?path="+coordinates.origin.latitude+","+coordinates.origin.longitude+"|"+coordinates.destination.latitude+","+coordinates.destination.longitude+"&samples=15&key="+key;
var i, j, k, l;
var multiplier=1;
var autonomyKm = $('#upAutonomyKm').val();
var checkForStationPoints = [];
var point = {"latitude":null, "longitude":null};
var pointsArray = [];
var vehicleId = $('select[name=upSelectVehicle]').val();
var distance = $('#upAutonomyKm').val();
console.log("distance: "+ distance);
console.log("latitude origin: "+coordinates.origin.latitude);
var directionsService = new google.maps.DirectionsService();
var directionsDisplay = new google.maps.DirectionsRenderer({
map: mapUP,
preserveViewport: true
});
directionsService.route({
origin: new google.maps.LatLng(coordinates.origin.latitude, coordinates.origin.longitude),
destination: new google.maps.LatLng(coordinates.destination.latitude, coordinates.destination.longitude),
/*waypoints: [{
stopover: true,
//location: new google.maps.LatLng(51.263439, 1.03489)
}],*/
travelMode: google.maps.TravelMode.DRIVING
}, function(response, status) {
if (status === google.maps.DirectionsStatus.OK) {
// directionsDisplay.setDirections(response);
var polyline = new google.maps.Polyline({
path: [],
strokeColor: '#0000FF',
strokeWeight: 3
});
var bounds = new google.maps.LatLngBounds();
var legs = response.routes[0].legs;
for (i = 0; i < legs.length; i++) {
var steps = legs[i].steps;
for (j = 0; j < steps.length; j++) {
var nextSegment = steps[j].path;
for (k = 0; k < nextSegment.length; k++) {
polyline.getPath().push(nextSegment[k]);
bounds.extend(nextSegment[k]);
}
}
}
var totalPoints = polyline.getPath().getArray().length;
var previousPoint = {"latitude":null, "longitude": null};
var previousPointString = polyline.getPath().getArray()[0].toString();
previousPoint.latitude = previousPointString.substring( 1, previousPointString.indexOf(','));
previousPoint.longitude = previousPointString.substring( previousPointString.indexOf(',')+1,previousPointString.length-1);
point.latitude = previousPoint.latitude;
point.longitude = previousPoint.longitude;
pointsArray.push(previousPoint);
for (l = 1; l < totalPoints; l++) {
var currentPointString = polyline.getPath().getArray()[l].toString();
var currentPoint= {"latitude":null, "longitude":null};
currentPoint.latitude = currentPointString.substring( 1, currentPointString.indexOf(','));
currentPoint.longitude = currentPointString.substring( currentPointString.indexOf(',')+1, currentPointString.length-1);
var currentDistance = calculateDistance(previousPoint.latitude, previousPoint.longitude, currentPoint.latitude, currentPoint.longitude);
if(currentDistance>4*multiplier && currentDistance<(4*multiplier+1)){
console.log("GUARDAR ESTE PONTO");
console.log("lat: "+currentPoint.latitude+" lng: "+currentPoint.longitude);
pointsArray.push(currentPoint);
multiplier++;
}
}
pointsArray.push(currentPoint);
console.table(pointsArray);
//console.log("COORDS ORIGIN"+ coordinates.origin.latitude +" "+ coordinates.origin.longitude);
$.ajax({
url: '/receiveCoords',//'http://geocomb.app/receiveCoords',
type: 'POST',
data: {"points": pointsArray, "vehicleId": vehicleId, "distance": distance, "latitudeOrigin": coordinates.origin.latitude, "longitudeOrigin": coordinates.origin.longitude},//{ "_token" : $('meta[name=_token]').attr('content'), name: "John", location: "Boston" },//JSON.stringify(pointsArray),//{_token: CSRF_TOKEN},
//contentType: "application/json; charset=utf-8",
success: function (response) {
console.log("data sent "+ response);
$("body").html(response);
},
error: function(error){
console.log("could not send data, error: ");
console.table(error);
}
});
var link= "/receivedCoords";
var stationData;
console.log(link);
$.ajax({
async: false,
url: link,
type: "GET",
url: "https://maps.googleapis.com/maps/api/elevation/json?path="+coordinates.origin.latitude+","+coordinates.origin.longitude+"|"+coordinates.destination.latitude+","+coordinates.destination.longitude+"&samples=15&key="+key,
success: function(data){
data.forEach(function(element){
console.log(element);
});
dataType: "json",
success: function (data) {
stationData = data['station'];
console.table(stationData);
},
error: function (error) {
console.log("Error getting the station data");
console.table(error);
}
});
});
console.table(stationData);
//polyline.setMap(mapUP);
//directionsDisplay.setMap(mapUP);
waypts.push({
location: new google.maps.LatLng(stationData["latitude"], stationData["longitude"]),
stopover: true
});
calculateAndDisplayRoute(directionsService, directionsDisplay);
waypts.pop();
} else {
window.alert('Directions request failed due to ' + status);
}
});
//getCoordinatePoints(route);
});
function calculateDistance(latitudeOrigin, longitudeOrigin, latitudeDestination, longitudeDestination)
{
/*var earthRadius = 6371;//km
var latitudeDifference = latitudeOrigin-latitudeDestination;
var longitudeDifference = longitudeOrigin-longitudeDestination;
var a = Math.pow(Math.sin(latitudeDifference/2),2) + Math.cos(latitudeOrigin) * Math.cos(latitudeDestination) * Math.pow(Math.sin(longitudeDifference/2), 2);
var c = 2 * a * Math.pow(Math.tan(Math.sqrt(a)*Math.sqrt(1-a)) ,2);
return earthRadius * c;*/
var lat1 = latitudeOrigin* Math.PI / 180;
var lat2 = latitudeDestination* Math.PI / 180;
var lon1 = longitudeOrigin* Math.PI / 180;
var lon2 = longitudeDestination* Math.PI / 180;
var dist = (6371 * Math.acos( Math.cos( lat1 ) * Math.cos( lat2 ) * Math.cos( lon2 - lon1 ) + Math.sin( lat1 ) * Math.sin(lat2) ) );
//dist = number_format($dist, 2, '.', '');
return dist;
}
function getCoordinatePoints(result) {
var currentRouteArray = result.routes[0]; //Returns a complex object containing the results of the current route
var currentRoute = currentRouteArray.overview_path; //Returns a simplified version of all the coordinates on the path
obj_newPolyline = new google.maps.Polyline({ map: map }); //a polyline just to verify my code is fetching the coordinates
var path = obj_newPolyline.getPath();
for (var x = 0; x < currentRoute.length; x++) {
var pos = new google.maps.LatLng(currentRoute[x].kb, currentRoute[x].lb)
latArray[x] = currentRoute[x].kb; //Returns the latitude
lngArray[x] = currentRoute[x].lb; //Returns the longitude
path.push(pos);
}
}
function calculateAndDisplayRoute(directionsService, directionsDisplay) {
directionsService.route({

View File

@ -8,9 +8,13 @@
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link href="{{ URL::asset('css/style.css') }}" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script
src="https://code.jquery.com/jquery-1.12.4.min.js"
integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ="
crossorigin="anonymous"></script>
<!--<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>-->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<!--<script src="https://code.jquery.com/jquery-1.12.4.js"></script>-->
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script src="{{asset('js/bootstrap3-typeahead.js')}}"></script>

View File

@ -1,4 +1,5 @@
@include('header')
<meta name="_token" content="{{ csrf_token() }}">
<div class="col-lg-12 text-center">
<h1 class="center">Bem-Vindo, {{$name}}</h1>
<br><br>
@ -32,7 +33,7 @@
{{csrf_field()}}
<div class="col-lg-6">
<label for="inputdefault">Veiculos:</label>
<select name="upSelectVehicle" onchange="this.form.submit()" >
<select name="upSelectVehicle" id="upSelectVehicle" onchange="this.form.submit()" >
@if(isset($vehicles))
@foreach($vehicles as $vehicle)
@ -93,8 +94,8 @@
</form>
<button id="sendRouteEmail" type="button" class="btn btn-info btn-lg" >Enviar rota para o meu Email</button>
</div>
</div>
@ -104,6 +105,6 @@
</div>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDsZDCiU1k6mSuywRRL88xxXY-81RMEU7s&callback=initMapUP" ></script>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDsZDCiU1k6mSuywRRL88xxXY-81RMEU7s&callback=initMapUP&libraries=places" ></script>
@include('footer')

View File

@ -77,3 +77,6 @@ Route::get('/api/districts', 'LandingController@apiDistricts')->name('apidistric
Route::get('/api/brands', 'LandingController@apiBrands')->name('apibrands');
Route::get('/api/stations/{district}/{brand}/{fuelType}', 'LandingController@apiStations')->name('apistations');
Route::get('/api/stationsup/{origin}/{destination}/{autonomy}', 'UserPageController@apiStations')->name('apistationsup');
Route::post('/receiveCoords','UserPageController@receiveCoordinates');
Route::get('/receivedCoords','UserPageController@receivedCoordinates');