overlayMaps and markers in Leaflet - leaflet

I am using Leaflet to show two sets of markers on a map. Let's call them "trip 1" and "trip 2".
The markers information (lat, lon, description, etc.) is stored in two separate geojson files.
I would like to show each trip separately, using two L.layerGroup, one for each trip.
The code below is the page I have written: so far this is what I have.
The problem is that all markers are already shown on the map before selecting each trip (top right corner - see attached image).
I would like the markers to be shown after selection.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<center>
<div id="map" class="embed-container"></div>
</center>
<script>
var viaggio1 = L.layerGroup([
<?php
$url = 'docs/guardini.geojson'; // path to your JSON file
$dati = file_get_contents($url); // put the contents of the file into a variable
$result = json_decode($dati, true); // decode the JSON feed
$data = $result['features'];
foreach($data as $key => $row) {
$numero = $row['id'];
$nome = $row['name'];
$lat = $row['lat'];
$lon = $row['lon'];
$text = $row['text'];
$pic = $row['pic'];
$link = $row['link'];
?>
L.marker(['<?=$lat;?>', '<?=$lon;?>']),
<?php
}
?>
]);
</script>
<script>
var viaggio2 = L.layerGroup([
<?php
$url2 = 'docs/guardini2.geojson'; // path to your JSON file
$dati2 = file_get_contents($url2); // put the contents of the file into a variable
$result2 = json_decode($dati2, true); // decode the JSON feed
$data2 = $result2['features'];
foreach($data2 as $key2 => $row2) {
$numero2 = $row2['id'];
$nome2 = $row2['name'];
$lat2 = $row2['lat'];
$lon2 = $row2['lon'];
$text2 = $row2['text'];
$pic2 = $row2['pic'];
$link2 = $row2['link'];
?>
L.marker(['<?=$lat2;?>', '<?=$lon2;?>']),
<?php
}
?>
]);
</script>
<script>
var overlayMaps = {
"viaggio 1": viaggio1,
"viaggio 2": viaggio2
};
var map = L.map('map').setView([48.3585, 10.86135], 6);
L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
{
attribution: '© OpenStreetMap',
maxZoom: 19,
minZoom: 4
}).addTo(map);
L.control.scale({imperial: false}).addTo(map);
var pol = L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
{
attribution: '© OpenStreetMap',
minZoom: 4,
maxZoom: 19
}).addTo(map);
var sat = L.tileLayer('http://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}',
{
attribution: 'Tiles © Esri — Source: Esri, IGN, IGP, UPR-EGP, and the GIS User Community',
minZoom: 4,
maxZoom: 19
});
var arte = L.tileLayer('http://stamen-tiles-{s}.a.ssl.fastly.net/watercolor/{z}/{x}/{y}.{ext}',
{
attribution: 'Map tiles by Stamen Design, CC BY 3.0 — Map data © OpenStreetMap',
subdomains: 'abcd',
minZoom: 4,
maxZoom: 19,
ext: 'png'
});
var baseMaps = {
"politica": pol,
"satellitare": sat,
"artistica": arte
};
//L.control.layers(baseMaps).addTo(map);
L.control.layers(baseMaps, overlayMaps).addTo(map);
var stile = {
"color": "#ff3385",
"weight": 4,
"opacity": 0.65
};
</script>
<?php
$url = 'docs/guardini.geojson'; // path to your JSON file
$dati = file_get_contents($url); // put the contents of the file into a variable
$result = json_decode($dati, true); // decode the JSON feed
$data = $result['features'];
foreach($data as $key => $row) {
$numero = $row['id'];
$nome = $row['name'];
$lat = $row['lat'];
$lon = $row['lon'];
$text = $row['text'];
$pic = $row['pic'];
$link = $row['link'];
?>
<div id="sidebar<?=$numero;?>" align="left"></div>
<script>
var sidebar<?=$numero;?> = L.control.sidebar('sidebar<?=$numero;?>', {
closeButton: true,
position: 'left'
});
sidebar<?=$numero;?>.setContent('<br>luogo nr. <?=$numero;?><br><br><b><?=$nome;?></b><br><br><?=$text;?><br><br><img src="<?=$pic;?>"><br><br><?=$link;?><br>');
map.addControl(sidebar<?=$numero;?>);
setTimeout(function () {
sidebar<?=$numero;?>.hide();
}, 700);
var marker<?=$numero;?> = L.marker(['<?=$lat;?>', '<?=$lon;?>']).addTo(map).on('click', function () {
sidebar<?=$numero;?>.toggle();
});
</script>
<?php
}
?>
<?php
$url2 = 'docs/guardini2.geojson'; // path to your JSON file
$dati2 = file_get_contents($url2); // put the contents of the file into a variable
$result2 = json_decode($dati2, true); // decode the JSON feed
$data2 = $result2['features'];
foreach($data2 as $key2 => $row2) {
$numero2 = $row2['id'];
$nome2 = $row2['name'];
$lat2 = $row2['lat'];
$lon2 = $row2['lon'];
$text2 = $row2['text'];
$pic2 = $row2['pic'];
$link2 = $row2['link'];
?>
<div id="sidebar<?=$numero2;?>" align="left"></div>
<script>
var sidebar<?=$numero2;?> = L.control.sidebar('sidebar<?=$numero2;?>', {
closeButton: true,
position: 'left'
});
sidebar<?=$numero2;?>.setContent('<br>luogo nr. <?=$numero2;?><br><br><b><?=$nome2;?></b><br><br><?=$text2;?><br><br><img src="<?=$pic2;?>"><br><br><?=$link2;?><br>');
map.addControl(sidebar<?=$numero2;?>);
setTimeout(function () {
sidebar<?=$numero2;?>.hide();
}, 700);
var markerr<?=$numero2;?> = L.marker(['<?=$lat2;?>', '<?=$lon2;?>']).addTo(map).on('click', function () {
sidebar<?=$numero2;?>.toggle();
});
</script>
<?php
}
?>
</div>
</div>
</body>
</html>

It looks like you are adding the markers to the map:
L.marker(['<?=$lat2;?>', '<?=$lon2;?>']).addTo(map)
And I think what you want to do is add the markers to the layerGroups:
L.marker(['<?=$lat2;?>', '<?=$lon2;?>']).addTo(viaggio2)

Related

Upload getUserMedia blob with Perl

I have problem with upload video file - blob, to our server. I tried solve this by javascript, but I have response 403.
So I tried do it with perl, but nothing happend. I know, that when I try create and save empty txt file with perl, it works (it is upload on server). So I hoped, that it will be similar. But it doesn´t work :(
I´m very basic programmer, please apologize me.
Please, how can I save the file to the server?
Thank you very much.
<html>
<div class="left">
<div id="startButton" class="button">
Start
</div>
<h2>Preview</h2>
<video id="preview" width="160" height="120" autoplay muted></video>
</div>
<div class="right">
<div id="stopButton" class="button">
Stop
</div>
<h2>Recording</h2>
<video id="recording" width="160" height="120" controls></video>
<a id="downloadButton" class="button">
Download
</a>
<a id="uploadButton" class="button" action="upload_ML_v01.pl" method="post" enctype="multipart/form-data">
Upload
</a>
</div>
<script>
let preview = document.getElementById("preview");
let recording = document.getElementById("recording");
let startButton = document.getElementById("startButton");
let stopButton = document.getElementById("stopButton");
let downloadButton = document.getElementById("downloadButton");
let logElement = document.getElementById("log");
let uploadButton = document.getElementById("uploadButton");
let recordingTimeMS = 5000;
function log(msg) {
//logElement.innerHTML += msg + "\n";
}
function wait(delayInMS) {
return new Promise(resolve => setTimeout(resolve, delayInMS));
}
function startRecording(stream, lengthInMS) {
let recorder = new MediaRecorder(stream);
let data = [];
recorder.ondataavailable = event => data.push(event.data);
recorder.start();
log(recorder.state + " for " + (lengthInMS/1000) + " seconds...");
let stopped = new Promise((resolve, reject) => {
recorder.onstop = resolve;
recorder.onerror = event => reject(event.name);
});
let recorded = wait(lengthInMS).then(
() => recorder.state == "recording" && recorder.stop()
);
return Promise.all([
stopped,
recorded
])
.then(() => data);
}
function stop(stream) {
stream.getTracks().forEach(track => track.stop());
}
startButton.addEventListener("click", function() {
navigator.mediaDevices.getUserMedia({
video: true,
audio: false
}).then(stream => {
preview.srcObject = stream;
downloadButton.href = stream;
preview.captureStream = preview.captureStream || preview.mozCaptureStream;
return new Promise(resolve => preview.onplaying = resolve);
}).then(() => startRecording(preview.captureStream(), recordingTimeMS))
.then (recordedChunks => {
let recordedBlob = new Blob(recordedChunks, { type: "video/webm" });
//upload it to server part start............................
var xhr = new XMLHttpRequest();
var fd = new FormData();
fd.append("video",recordedBlob);
xhr.open('POST', 'video', recordedBlob)
xhr.send(fd);
recording.src = URL.createObjectURL(recordedBlob);
downloadButton.href = recording.src;
downloadButton.download = "RecordedVideo.webm";
log("Successfully recorded " + recordedBlob.size + " bytes of " +
recordedBlob.type + " media.");
})
.catch(log);
}, false);
stopButton.addEventListener("click", function() {
stop(preview.srcObject);
}, false);
</script>
</html>
and perl file:
use strict;
use warnings;
use CGI;
use CGI::Carp qw/fatalsToBrowser/;
use File::Basename;
$|=1; # auto flush
$CGI::DISABLE_UPLOADS = 0;
my $query = CGI->new; # ..global query
my $src_filehandle = $query->upload('recording.src');
my $upld_pathfilename = "video.webm";
open (UPLOADFILE, ">",$upld_pathfilename);
my $totalbytes = 0;
while ( <$src_filehandle> ) {
print UPLOADFILE;
$totalbytes += length;
};
close UPLOADFILE
Your JavaScript code does not look right:
xhr.open('POST', 'video', recordedBlob)
The open method expects a boolean as the third argument, see documentation. You are sending it a blob instead.
Here is an example of how you can send binaray data.

Severity: Notice Message: Undefined variable: data Filename: frontend/v_grafik.php Line Number: 17

CodeIgniter, Message: Undefined variable, Passing data
Controller
function v_grafik() {
// error_reporting(0);
$iklan = $this->Tb_iklan_model->get_all();
$berita = $this->Tb_berita_model->get_all();
$x['data'] = $this->M_grafik->get_data_stok();
if ($x) {
$data = array(
'x' => $x,
'berita' => $berita,
'iklan' => $iklan,
'content' => "frontend/v_grafik",
);
// $content = $this->load->view('frontend/v_grafik',$x);
$this->load->view('layout/frontend', $data);
} else {
$this->session->set_flashdata('message', 'Record Not Found');
redirect(site_url('frontend'));
}
}
View
<?php
foreach($data as $data){
$merk[] = $data->merk;
$stok[] = (float) $data->stok;
}
?>
<canvas id="canvas" width="1000" height="280"></canvas>
<!--Load chart js-->
<script type="text/javascript" src="<?=base_url()?>assets/vendor/chartjs/Chart.js"></script>
<script type="text/javascript" src="<?=base_url()?>assets/vendor/chartjs/Chart.min.js"></script>
<script>
var lineChartData = {
labels : <?php echo json_encode($merk);?>,
datasets : [
{
fillColor: "rgba(60,141,188,0.9)",
strokeColor: "rgba(60,141,188,0.8)",
pointColor: "#3b8bba",
pointStrokeColor: "#fff",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(152,235,239,1)",
data : <?php echo json_encode($stok);?>
}
]
}
var myLine = new Chart(document.getElementById("canvas").getContext("2d")).Line(lineChartData);
</script>
This eror : A PHP Error was encountered
Severity: Notice
Message: Undefined variable: data
Filename: frontend/v_grafik.php
Line Number: 17
Backtrace:
File: C:\xampp\htdocs\project\application\views\frontend\v_grafik.php
Line: 17
This Severity: Warning
Message: Invalid argument supplied for foreach()
Filename: frontend/v_grafik.php
Line Number: 17
Can help me?
Why would you do... In your view
foreach($data as $data)
You are changing what $data is and bad things will happen. So you need to change one of them. In this "example" I have changed the 2nd occurrence of $data to $info.
foreach($data as $info){
$merk[] = $info->merk;
$stok[] = (float) $info->stok;
}

How to save multiple image path to database while image is saved to server

I have this code on how to save multiple images to server using codeigniter and ajax
I have gone through this code, though i'm still learning Ajax, Json and Javascript. But i want to be able to save the image paths (for all images uploaded to the database so i can be able to retrieve them for each user. Just the was facebook image upload is). The code below is in my view file.
$(document).ready(function(){
$('#profiles').change(function(){
var files = $('#profiles')[0].files;
var error = '';
var form_data = new FormData();
for(var count = 0; count<files.length; count++){
var name = files[count].name;
var extension = name.split('.').pop().toLowerCase();
if(jQuery.inArray(extension, ['gif','png','jpg','jpeg']) == -1){
error += " " + count + "Invalid Image File(s)"
}
else {
form_data.append("profiles[]", files[count]);
}
}
if(error == ''){
$.ajax({
url:"<?php echo base_url(); ?>pastors/upload_image",
method:"POST",
data:form_data,
contentType:false,
cache:false,
processData:false,
beforeSend:function() {
$('#upl_images').html("<label class='text-success'>Uploading...</label>");
},
success:function(data){
$('#upl_images').html(data);
$('#profiles').val('');
document.getElementById("success_msg").style.transition="all 0.9s ease";
document.getElementById("success_msg").style.opacity=0.5;
document.getElementById("success_msg").innerHTML="Images Successfully Uploaded";
//alert(pastor +" "+ "You saved a new report");
setTimeout(remove_prodiv, 1500);
}
})
}
else{
alert(error);
}
});
});
And this is my controller
public function upload_image(){
if($_FILES["profiles"]["name"] != ''){
$output = '';
$config["upload_path"] = './programphoto/';
$config["allowed_types"] = 'gif|jpg|png|jpeg';
$this->load->library('upload', $config);
$this->upload->initialize($config);
for($count = 0; $count<count($_FILES["profiles"]["name"]); $count++){
$_FILES["file"]["name"] = $_FILES["profiles"]["name"][$count];
$_FILES["file"]["type"] = $_FILES["profiles"]["type"][$count];
$_FILES["file"]["tmp_name"] = $_FILES["profiles"]["tmp_name"][$count];
$_FILES["file"]["error"] = $_FILES["profiles"]["error"][$count];
$_FILES["file"]["size"] = $_FILES["profiles"]["size"][$count];
if($this->upload->do_upload('file')){
$data = $this->upload->data();
//$image=$data["file_name"];
//$this->pastors_model->SaveReport($image);
$output .= '
<div class="col-md-2">
<img src="'.base_url().'programphoto/'.$data["file_name"].'" class="img-responsive img-thumbnail" />
</div>
';
}
}
echo $output;
}
}
This code uploads images perfectly to the server. but i just want a way out to saving the paths to database
I got this working.
All I did was to send the file names to the model each time it uploads,
like this:
if($this->upload->do_upload('file')){
$data = $this->upload->data();
$output .= '
<div class="col-md-2">
<img src="'.base_url().'folder/'.$data["file_name"].'" class="img-responsive img-thumbnail" />
</div>
';
$filename = $data['file_name'];
$this->Model->save_file($filename);
}

Google Charts -- Axis Values overlapping and how to avoid

How do I avoid this axis overlap in google charts? I am working with a large data set and not sure what to do to solve this issue. I am using a large number of dates for the x axis. The options I use for my chart are
var options = {
tooltip: {
trigger: 'both',
},
width: 1900,
height: 400,
vAxis: { 'title': 'Volume' },
crosshair: { trigger: 'both'}
};
EDIT::
PHP creation of the containers
if( isset($db_graph_query)){
while($row = mysqli_fetch_array($db_graph_query)) {
$rowcount2++;
// removed the hard coded column set and made it driven off of the array below
// could have pulled it from the $cols array above, but there might be columns that we don't wish to show
echo " <tr>";
$colindex = 0;
foreach( $cols as $column_name ) {
$style = "";
$val = $row[$column_name];
if ( isset($column_callback)) {
$style=$column_callback($colindex, $val);
}
if ($colindex == 0) {
echo "<td style='text-align: left; width: 1pt;'><a href='#' class='toggle' onClick='drawChart(\"$val\");'>$val</a></td>";
$tempval = $val;
} else {
echo "<td $style>$val</td>";
}
$colindex++;
}
echo "</tr>";
echo "<tr class='tablesorter-childRow'>";
echo "<td colspan='12'>";
echo "<div id='$tempval' style='height: 400px;'></div>";
echo "</td>";
echo "</tr>";
}
}
EDIT::
Draw Chart Script, creates the chart options, grabs data from SQL DB and adds into the data:
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages':['corechart']});
function drawChart(inputname) {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Name');
data.addColumn('string', 'RunDate');
data.addColumn('number', 'Runs');
data.addColumn('number', 'Fails');
data.addRows([
<?php
$dbName = "mydb";
$config = parse_ini_file("configfile.ini",true);
$dbUser = $config["DB"]["db_user"];
$dbServer = $config["DB"]["db_ip"];
$dbPassword = $config["DB"]["db_pass"];
$con = mysql_connect($dbServer, $dbUser, $dbPassword);
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db($dbName, $con);
$sql = mysql_query("SELECT * From MyTestTable");
$output = array();
while($row = mysql_fetch_array($sql)) {
// create a temp array to hold the data
$temp = array();
// add the data
$temp[] = '"' . $row['Name'] . '"';
$temp[] = '"' . $row['RunDate'] . '"';
$temp[] = (int) $row['Runs'];
$temp[] = (int) $row['FailCount'];
// implode the temp array into a comma-separated list and add to the output array
$output[] = '[' . implode(', ', $temp) . ']';
}
// implode the output into a comma-newline separated list and echo
echo implode(",\n", $output);
mysql_close($con);
?>
]);
var view = new google.visualization.DataView(data);
view.setRows(data.getFilteredRows([
{column: 0, value: inputname}
]));
view.setColumns([1,2,3]);
var options = {
tooltip: {
trigger: 'both',
},
vAxis: { 'title': 'Volume' },
crosshair: { trigger: 'both'},
width: 1900,
height: 400
};
var chart = new google.visualization.LineChart(document.getElementById(inputname));
chart.draw(view, options);
}
</script>
try using option for slanted text...
hAxis: {slantedText: true}
The horizontal axis ticks should not be overlapping at all, and I believe the only way this could be happening is if your chart is not visible at the time you draw it, in which case the chart thinks the ticks don't take up any space and can be packed in as dense as possible. Slanting or alternating would not necessarily help until you get down to the minimum spacing constraint.
So the only real solution, at this time, is to make sure your chart is visible when you draw it.

How put dates on flot

I've a little problem, I need to do a curve with on y axis numbers and x axis dates.. but I can't display some dates...
My code :
<script type="text/javascript">
$(function () {
<?php
echo " var data = [";
$cpt="0";
include ('../connect.php');
// Requete SQL
$req = 'select "SPP_NB_IND" from "STAT_PERPHY" where "SPP_SAGES" = \''.$sages.'\' AND "SPP_DATE" between \''.$jourtableau.' 00:00:00\' and \''.$jourfinw.' 23:59:59\'';
$res = pg_query($req);
$reqd = 'select "SPP_DATE" from "STAT_PERPHY" where "SPP_SAGES" = \''.$sages.'\' AND "SPP_DATE" between \''.$jourtableau.' 00:00:00\' and \''.$jourfinw.' 23:59:59\' AND "SPP_NB_IND" IS NOT NULL ';
$resd = pg_query($reqd);
// On met les valeurs obtenues dans un tableau
while ( $row = pg_fetch_assoc ($res) )
{
//echo $row['SPP_NB_IND']."<br>";
$var=$row['SPP_NB_IND'];
while ( $roww = pg_fetch_assoc ($resd) )
{
$abscisse=date('d-m', strtotime($roww['SPP_DATE']));
}
echo "[$abscisse, $var],";
$cpt++;
}
echo "];";
?>
var options = {
lines: {
show: true
},
points: { show: true
},
xaxis: {
mode: "time",
timeformat : "%d/%m"
}
};
<?php
echo "$.plot($(\"#graph1\"), [ data ], options);";
?>
});
</script>
[/CODE]
When I put $abscisse, my curve is vertical and if I put $cpt, I have a "normal" curve... but I want to see dates corresponding with numbers..
Freindly,
Tanaes.
See the documentation:
You have to give flot timestamps, not already formated dates. For PHP use something like
$abscisse = strtotime($roww['SPP_DATE']) * 1000;