I'm fairly new to the coding world so please have mercy regarding my obsolete SQL connection although the wpdp class does exist. I am aware of this, but for some reasons, it doesn't work and that's another topic...
I try to write my own plugin to connect to my sql database, query some stuff and then provide a google chart with a jsontable. The code works If I use it in a stand alone .php file. However, as soon as I activate do_action nothing works and my whole page is white.
<?php
/*
Plugin Name: mm_gchart
Description: -
Version: 1.0.0
Author: MM
*/
function mm_gct_data() {
$con=mysqli_connect("localhost","xx","xx","xx");
// Check connection
if (mysqli_connect_errno()) {
//echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//echo "Hello";
$sql="SELECT gewicht, wdh FROM testtable";
$query=mysqli_query($con, $sql);
$rows=array();
$table=array();
$table['cols'] = array(
array('label' => 'Gewicht', 'type' => 'number'),
array('label' => 'Wiederholungen', 'type' => 'number')
);
while ($r = mysqli_fetch_assoc($query))
{
$temp=array();
$temp[]=array('v' => (int) $r['gewicht']);
$temp[]=array('v' => (int) $r['wdh']);
$rows[]=array('c' => $temp);
}
global $jsonTable;
$table['rows'] = $rows;
$jsonTable = json_encode($table);
}
add_action('init', 'mm_gct_data');
//do_action( 'init','mm_gct_data' );
?>
I would be super happy, if somebody could work some black magic on my code and then provide a simple description.
Thanks in advance!
Edit after replies:
Thank you very much for your fast reply! If the do_action() command was not the reason for my blank page, then what is?
<html>
<head>
<!--Load the AJAX API-->
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
// Load the Visualization API and the piechart package.
google.load('visualization', '1', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
function drawChart() {
// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable(<?=$jsonTable?>);
var options = {
title: 'Testing',
width: 600,
height: 400
};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<!--Div that will hold the pie chart-->
<div id="chart_div"></div>
<p>Everything went well..</p>
</body>
</html>
You should not make a call to do_action() as you have it in your code. This action hook is built into WordPress and will be called automatically as part of its running. The WordPress site has a list of the Actions Run During a Typical Request on their site.
It is appropriate to make a call to do_action() when you want to implement a custom action hook for other developers to plug in to. Calls to add_action() can be made to add events to your hook.
Related
I’m passing an encoded json array from a MYSQL query to render a google.visualization.dashboard. I am almost certain the problem is with my array but I can't find where. The code works when I draw the chart google charts directly (eg google.visualization.PieChart) but not when I use dashboard / control wrapper / chart wrapper classes.
That leads me to believe that the problem is either with my array structure or that google.visualization.dashboard requires the data table to be populated differently than the charts.
PHP code (loadpiechart.php):
$table['cols'] = array(
array('label' => 'NZ Crime', 'type' => 'string'),
array('label' => 'Value', 'type' => 'number'),
);
$rows=array();
while($r=mysqli_fetch_assoc($res)){
$temp=array();
$temp[]=array('v'=> $r['Offence']);
$temp[]=array('v' => $r['Total']);
$rows[]=array('c' => $temp);
}
$table['rows'] = $rows;
$jsonTable = json_encode($table, JSON_NUMERIC_CHECK);
echo $jsonTable;
Which gives me the following array[]
{"cols":[{"id":"A","label":"NZ Crime","type":"string"},{"id":"B","label":"Value","type":"number"}],"rows":[{"c":[{"v":" Acts intended to cause injury"},{"v":97}]},{"c":[{"v":" Sexual assault and related offences"},{"v":44515}]},{"c":[{"v":" Dangerous or negligent acts endangering persons"},{"v":3016}]},{"c":[{"v":" Abduction, harassment and other related offences against a person"},{"v":859}]},{"c":[{"v":" Robbery, extortion and related offences"},{"v":14157}]},{"c":[{"v":" Unlawful entry with intent\/burglary, break and enter"},{"v":2641}]},{"c":[{"v":" Theft and related offences"},{"v":59323}]},{"c":[{"v":" Fraud, deception and related offences"},{"v":136932}]},{"c":[{"v":" Illicit drug offences"},{"v":9726}]},{"c":[{"v":" Prohibited and regulated weapons and explosives offences"},{"v":22994}]},{"c":[{"v":" Property damage and environmental pollution"},{"v":7074}]},{"c":[{"v":" Public order offences"},{"v":58483}]},{"c":[{"v":" Offences against justice procedures, government security and government operations"},{"v":46105}]},{"c":[{"v":" Miscellaneous offences"},{"v":19084}]}]}
And finally the HTML code.
html>
<head>
<!--Load the AJAX API-->
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
// Load the Visualization API and the piechart package.
google.charts.load('current', {packages:['corechart', 'table', 'controls']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawTable);
function drawTable() {
var jsonData = $.ajax({
url: "loadpiechart.php",
dataType:"json",
async: false
}).responseText;
// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable(jsonData);
var table = new google.visualization.ChartWrapper({
'chartType': 'Table',
'containerId': 'table_div',
});
var chart = new google.visualization.ChartWrapper({
'chartType': 'PieChart',
'containerId': 'chart_div',
'view': {'columns': [0, 1]},
});
var control = new google.visualization.ControlWrapper({
'controlType': 'CategoryFilter',
'containerId': 'control_div',
'options': {
'filterColumnIndex': 0,
}
});
var dashboard = new google.visualization.Dashboard(
document.getElementById('dashboard_div'));
dashboard.bind([control], [table,chart]);
dashboard.draw(data);
}
</script>
</head>
<body>
<div id="dashboard_div" style="border: 1px solid #ccc; margin-top: 1em">
<p style="padding-left: 1em"><strong>NZ Crime Stats</strong></p>
<table class="columns">
<tr>
<td>
<div id="control_div" style="padding-left: 15px"></div>
</td>
</tr><tr>
<td>
<div id="chart_div" style="padding-top: 15px"></div>
</td><td>
<div id="table_div" style="padding-top: 30px"></div>
</td>
</tr>
</table>
</div>
</body>
</html>
I would recommend to change the AJAX call to a non-blocking asynchronous call and call the drawing routine in the success() method:
function drawTable() {
$.ajax("https://gist.githubusercontent.com/Moonbird-IT/da4c7d76a69eb250478bb55b5d2360f5/raw/9dbf9d92981a3c9b71906dd3a680a2cdeca7c4aa/googlecharts.json", {
dataType: "json",
success: function(jsonData) {
// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable(jsonData);
...
}
});
}
I updated your code to use the changed recommendation, here is a working Fiddle of it.
My problem was that I wasn't calling jQuery. I added this line of code and it works my original code plus this addition.
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
Link here for google.visaulization documentation https://developers.google.com/chart/interactive/docs/php_example
Im new to php and mysql and we have a project where we want to display a specific users input in a google chart.
In the mysql table I have 2 different values (admin, test) under a row called user_name.
When the code is as I linked, the chart shows all the inputs, no matter if they are from the user "test" or the user "admin" and works as it should.
But when I change
$query="
select *
from temp
"
to
$query=
"select *
from temp
where user_name=test
"
the chart stops working.
Any help how to solve this is much appreciated!
<!-- The scripts for the graph -->
<script type="text/javascript"
src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Day', 'Outdoor', 'Indoor'],
//PHP Code
<?php
$query="select * from temp";
$res=mysqli_query($mysqli,$query);
while($data=mysqli_fetch_array($res)){
$day=$data['created_at'];
$outdoor=$data['outdoor'];
$indoor=$data['indoor'];
?>
['<?php echo $day;?>',<?php echo $outdoor;?>,
<?php echo $indoor;?>],
<?php
}
?>
]);
var options = {
title: 'Temperature',
subtitle: 'Temperature outside and inside',
curveType: 'none',
legend: { position: 'bottom' }
};
var chart = new google.visualization.LineChart
(document.getElementById('curve_chart'));
chart.draw(data, options);
}
</script>
mysql table:
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed last year.
Locked. This question and its answers are locked because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions.
I have searched a lot to find a good example for generating a Google Chart using MySQL table data as the data source. I searched for a couple of days and realised that there are few examples available for generating a Google Chart (pie, bar, column, table) using a combination of PHP and MySQL. I finally managed to get one example working.
I have previously received a lot of help from StackOverflow, so this time I will return some.
I have two examples; one uses Ajax and the other does not. Today, I will only show the non-Ajax example.
Usage:
Requirements: PHP, Apache and MySQL
Installation:
--- Create a database by using phpMyAdmin and name it "chart"
--- Create a table by using phpMyAdmin and name it "googlechart" and make
sure table has only two columns as I have used two columns. However,
you can use more than 2 columns if you like but you have to change the
code a little bit for that
--- Specify column names as follows: "weekly_task" and "percentage"
--- Insert some data into the table
--- For the percentage column only use a number
---------------------------------
example data: Table (googlechart)
---------------------------------
weekly_task percentage
----------- ----------
Sleep 30
Watching Movie 10
job 40
Exercise 20
PHP-MySQL-JSON-Google Chart Example:
<?php
$con=mysql_connect("localhost","Username","Password") or die("Failed to connect with database!!!!");
mysql_select_db("Database Name", $con);
// The Chart table contains two fields: weekly_task and percentage
// This example will display a pie chart. If you need other charts such as a Bar chart, you will need to modify the code a little to make it work with bar chart and other charts
$sth = mysql_query("SELECT * FROM chart");
/*
---------------------------
example data: Table (Chart)
--------------------------
weekly_task percentage
Sleep 30
Watching Movie 40
work 44
*/
//flag is not needed
$flag = true;
$table = array();
$table['cols'] = array(
// Labels for your chart, these represent the column titles
// Note that one column is in "string" format and another one is in "number" format as pie chart only required "numbers" for calculating percentage and string will be used for column title
array('label' => 'Weekly Task', 'type' => 'string'),
array('label' => 'Percentage', 'type' => 'number')
);
$rows = array();
while($r = mysql_fetch_assoc($sth)) {
$temp = array();
// the following line will be used to slice the Pie chart
$temp[] = array('v' => (string) $r['Weekly_task']);
// Values of each slice
$temp[] = array('v' => (int) $r['percentage']);
$rows[] = array('c' => $temp);
}
$table['rows'] = $rows;
$jsonTable = json_encode($table);
//echo $jsonTable;
?>
<html>
<head>
<!--Load the Ajax API-->
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
// Load the Visualization API and the piechart package.
google.load('visualization', '1', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
function drawChart() {
// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable(<?=$jsonTable?>);
var options = {
title: 'My Weekly Plan',
is3D: 'true',
width: 800,
height: 600
};
// Instantiate and draw our chart, passing in some options.
// Do not forget to check your div ID
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<!--this is the div that will hold the pie chart-->
<div id="chart_div"></div>
</body>
</html>
PHP-PDO-JSON-MySQL-Google Chart Example:
<?php
/*
Script : PHP-PDO-JSON-mysql-googlechart
Author : Enam Hossain
version : 1.0
*/
/*
--------------------------------------------------------------------
Usage:
--------------------------------------------------------------------
Requirements: PHP, Apache and MySQL
Installation:
--- Create a database by using phpMyAdmin and name it "chart"
--- Create a table by using phpMyAdmin and name it "googlechart" and make sure table has only two columns as I have used two columns. However, you can use more than 2 columns if you like but you have to change the code a little bit for that
--- Specify column names as follows: "weekly_task" and "percentage"
--- Insert some data into the table
--- For the percentage column only use a number
---------------------------------
example data: Table (googlechart)
---------------------------------
weekly_task percentage
----------- ----------
Sleep 30
Watching Movie 10
job 40
Exercise 20
*/
/* Your Database Name */
$dbname = 'chart';
/* Your Database User Name and Passowrd */
$username = 'root';
$password = '123456';
try {
/* Establish the database connection */
$conn = new PDO("mysql:host=localhost;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
/* select all the weekly tasks from the table googlechart */
$result = $conn->query('SELECT * FROM googlechart');
/*
---------------------------
example data: Table (googlechart)
--------------------------
weekly_task percentage
Sleep 30
Watching Movie 10
job 40
Exercise 20
*/
$rows = array();
$table = array();
$table['cols'] = array(
// Labels for your chart, these represent the column titles.
/*
note that one column is in "string" format and another one is in "number" format
as pie chart only required "numbers" for calculating percentage
and string will be used for Slice title
*/
array('label' => 'Weekly Task', 'type' => 'string'),
array('label' => 'Percentage', 'type' => 'number')
);
/* Extract the information from $result */
foreach($result as $r) {
$temp = array();
// the following line will be used to slice the Pie chart
$temp[] = array('v' => (string) $r['weekly_task']);
// Values of each slice
$temp[] = array('v' => (int) $r['percentage']);
$rows[] = array('c' => $temp);
}
$table['rows'] = $rows;
// convert data into JSON format
$jsonTable = json_encode($table);
//echo $jsonTable;
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
?>
<html>
<head>
<!--Load the Ajax API-->
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
// Load the Visualization API and the piechart package.
google.load('visualization', '1', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
function drawChart() {
// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable(<?=$jsonTable?>);
var options = {
title: 'My Weekly Plan',
is3D: 'true',
width: 800,
height: 600
};
// Instantiate and draw our chart, passing in some options.
// Do not forget to check your div ID
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<!--this is the div that will hold the pie chart-->
<div id="chart_div"></div>
</body>
</html>
PHP-MySQLi-JSON-Google Chart Example
<?php
/*
Script : PHP-JSON-MySQLi-GoogleChart
Author : Enam Hossain
version : 1.0
*/
/*
--------------------------------------------------------------------
Usage:
--------------------------------------------------------------------
Requirements: PHP, Apache and MySQL
Installation:
--- Create a database by using phpMyAdmin and name it "chart"
--- Create a table by using phpMyAdmin and name it "googlechart" and make sure table has only two columns as I have used two columns. However, you can use more than 2 columns if you like but you have to change the code a little bit for that
--- Specify column names as follows: "weekly_task" and "percentage"
--- Insert some data into the table
--- For the percentage column only use a number
---------------------------------
example data: Table (googlechart)
---------------------------------
weekly_task percentage
----------- ----------
Sleep 30
Watching Movie 10
job 40
Exercise 20
*/
/* Your Database Name */
$DB_NAME = 'chart';
/* Database Host */
$DB_HOST = 'localhost';
/* Your Database User Name and Passowrd */
$DB_USER = 'root';
$DB_PASS = '123456';
/* Establish the database connection */
$mysqli = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
/* select all the weekly tasks from the table googlechart */
$result = $mysqli->query('SELECT * FROM googlechart');
/*
---------------------------
example data: Table (googlechart)
--------------------------
Weekly_Task percentage
Sleep 30
Watching Movie 10
job 40
Exercise 20
*/
$rows = array();
$table = array();
$table['cols'] = array(
// Labels for your chart, these represent the column titles.
/*
note that one column is in "string" format and another one is in "number" format
as pie chart only required "numbers" for calculating percentage
and string will be used for Slice title
*/
array('label' => 'Weekly Task', 'type' => 'string'),
array('label' => 'Percentage', 'type' => 'number')
);
/* Extract the information from $result */
foreach($result as $r) {
$temp = array();
// The following line will be used to slice the Pie chart
$temp[] = array('v' => (string) $r['weekly_task']);
// Values of the each slice
$temp[] = array('v' => (int) $r['percentage']);
$rows[] = array('c' => $temp);
}
$table['rows'] = $rows;
// convert data into JSON format
$jsonTable = json_encode($table);
//echo $jsonTable;
?>
<html>
<head>
<!--Load the Ajax API-->
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
// Load the Visualization API and the piechart package.
google.load('visualization', '1', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
function drawChart() {
// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable(<?=$jsonTable?>);
var options = {
title: 'My Weekly Plan',
is3D: 'true',
width: 800,
height: 600
};
// Instantiate and draw our chart, passing in some options.
// Do not forget to check your div ID
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<!--this is the div that will hold the pie chart-->
<div id="chart_div"></div>
</body>
</html>
Some might encounter this error either locally or on the server:
syntax error var data = new google.visualization.DataTable(<?=$jsonTable?>);
This means that their environment does not support short tags the solution is to use this instead:
<?php echo $jsonTable; ?>
And everything should work fine!
You can do this more easy way. And 100% works that you want
<?php
$servername = "localhost";
$username = "root";
$password = ""; //your database password
$dbname = "demo"; //your database name
$con = new mysqli($servername, $username, $password, $dbname);
if ($con->connect_error) {
die("Connection failed: " . $con->connect_error);
}
else
{
//echo ("Connect Successfully");
}
$query = "SELECT Date_time, Tempout FROM alarm_value"; // select column
$aresult = $con->query($query);
?>
<!DOCTYPE html>
<html>
<head>
<title>Massive Electronics</title>
<script type="text/javascript" src="loder.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart(){
var data = new google.visualization.DataTable();
var data = google.visualization.arrayToDataTable([
['Date_time','Tempout'],
<?php
while($row = mysqli_fetch_assoc($aresult)){
echo "['".$row["Date_time"]."', ".$row["Tempout"]."],";
}
?>
]);
var options = {
title: 'Date_time Vs Room Out Temp',
curveType: 'function',
legend: { position: 'bottom' }
};
var chart = new google.visualization.AreaChart(document.getElementById('areachart'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="areachart" style="width: 900px; height: 400px"></div>
</body>
</html>
loder.js link here loder.js
use this, it realy works:
data.addColumn no of your key, you can add more columns or remove
<?php
$con=mysql_connect("localhost","USername","Password") or die("Failed to connect with database!!!!");
mysql_select_db("Database Name", $con);
// The Chart table contain two fields: Weekly_task and percentage
//this example will display a pie chart.if u need other charts such as Bar chart, u will need to change little bit to make work with bar chart and others charts
$sth = mysql_query("SELECT * FROM chart");
while($r = mysql_fetch_assoc($sth)) {
$arr2=array_keys($r);
$arr1=array_values($r);
}
for($i=0;$i<count($arr1);$i++)
{
$chart_array[$i]=array((string)$arr2[$i],intval($arr1[$i]));
}
echo "<pre>";
$data=json_encode($chart_array);
?>
<html>
<head>
<!--Load the AJAX API-->
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
// Load the Visualization API and the piechart package.
google.load('visualization', '1', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
function drawChart() {
// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable();
data.addColumn("string", "YEAR");
data.addColumn("number", "NO of record");
data.addRows(<?php $data ?>);
]);
var options = {
title: 'My Weekly Plan',
is3D: 'true',
width: 800,
height: 600
};
// Instantiate and draw our chart, passing in some options.
//do not forget to check ur div ID
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<!--Div that will hold the pie chart-->
<div id="chart_div"></div>
</body>
</html>
I stuck completely going through scripting with openlayers. I have database in postgis with coordinates and height values and even geometry column for each row. I create form with submit button to retrieve data only according to entered value by the user. When I press the submit button the PHP is getting correct data and transform into JSON format which I have displayed as result. Somebody know how to load these results into openlayers layer and display those points?
Thats the main page:
`<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Welcome to my maps</title>
<script src="http://www.openlayers.org/api/OpenLayers.js"></script>
<script src="http://www.openstreetmap.org/openlayers/OpenStreetMap.js"></script>
<link rel="stylesheet" href="http://openlayers.org/api/theme/default/style.css" type="text/css" />
<style type="text/css">
#bmap {
width:83%;
height:90%;
border:2px solid black;
position:absolute;
top:10px;
left:200px;
}
body{
background:yellow;
}
</style>
<script>
var mapoptions = {
theme: null,
maxExtent: new OpenLayers.Bounds(-20037508.34,-20037508.34,20037508.34,20037508.34),
maxResolution: 156543.0399,
numZoomLevels: 20,
units: 'm',
projection: new OpenLayers.Projection("EPSG:900913"),
displayProjection: new OpenLayers.Projection("EPSG:4326"),
controls:[
new OpenLayers.Control.PanZoomBar(),
new OpenLayers.Control.Navigation(),
new OpenLayers.Control.LayerSwitcher(),
new OpenLayers.Control.MousePosition(),
new OpenLayers.Control.ScaleLine(),
new OpenLayers.Control.Scale()
]
};
function init() {
map = new OpenLayers.Map("bmap", mapoptions);
var mapnik = new OpenLayers.Layer.OSM("OSM Mapnik");
map.addLayer(mapnik);
var cyclemap = new OpenLayers.Layer.OSM("OSM CycleMap");
map.addLayer(cyclemap);
var wmslayer = new OpenLayers.Layer.WMS(
"Altitude points",
"http://192.168.56.101:8080/geoserver/wms",
{'layers': 'dublin_flooding:dublin', 'format':'image/png', 'transparent':'true'},
{'opacity': 1.0, 'isBaseLayer': false, 'visibility': false}
);
map.addLayer(wmslayer);
var veclayer=new OpenLayers.Layer.Vector("geojson",{
strategies: [new OpenLayers.Strategy.Fixed()],
protocol: new OpenLayers.Protocol.HTTP({
url: "query5.php",
format: new OpenLayers.Format.GeoJSON(),
internalProjection: new OpenLayers.Projection("EPSG:900913"),
externalProjection: new OpenLayers.Projection("EPSG:4326")
}),
});
map.addLayer(veclayer);
map.setCenter(new OpenLayers.LonLat(-6.26555,53.34590) // Center of the map
.transform(
new OpenLayers.Projection("EPSG:4326"), // transform from WGS 1984
new OpenLayers.Projection("EPSG:900913") // to Spherical Mercator Projection
), 12 // Zoom level
);
}
</script>
</head>
<body>
<h3>Flooding projection</h3>
<form action="query5.php" method="POST" name="form">
<table cellpadding="0">
<tr>
<td>
<p>Meters:</p>
</td>
<td>
<input name="sliderValue" id="sliderValue" type="Text" size="3">
</td>
</tr>
<tr>
<td>
<input name="Submit" type="Submit" value="Submit">
</td>
</tr>
</table>
</form>
<body onload="init();">
<div id="bmap"></div>
</body>
</html>
`
And PHP query is looks like that:
`<?php
$db = pg_connect("host=localhost port=5432 dbname=firstSpatialDB user=postgres password=postgres");
$query = "SELECT* FROM dublin where alt<='$_POST[sliderValue]'";
$result = pg_query($query);
// Return route as GeoJSON
$geojson = array(
'type' => 'FeatureCollection',
'features' => array()
);
// Add edges to GeoJSON array
while($row=pg_fetch_array($result)) {
$feature = array(
'type' => 'Feature',
'geometry' => array(
'type' => 'Point',
'coordinates' => array($row[1], $row[2])
),
'properties' => array(
'gid' => $row[0],
'alt' => $row[3]
)
);
// Add feature array to feature collection array
array_push($geojson['features'], $feature);
}
pg_close($dbconn);
// Return routing result
header("Content-Type:application/json",true);
//header("Location:map.html");
echo json_encode($geojson);
?> `
In my view that should be working, but is not at all.
Maybe somebody has idea what is wrong. Thanks for any suggestions, as I really have enough my own.
I have never used php, so I don't know if that's where your problem is.
Compare your code to this, it worked for me, maybe your error is in the javascript.
var map;
function init(){
map = new OpenLayers.Map('map');
var options = {numZoomLevels: 3}
var floorplan = new OpenLayers.Layer.Image(
'Floorplan Map',
'../../temp_photos/sample-floor-plan.jpg',
new OpenLayers.Bounds(-300, -188.759, 300, 188.759),
new OpenLayers.Size(580, 288),
options
);
map.addLayer(floorplan);
//Create a Format object
var vector_format = new OpenLayers.Format.GeoJSON({});
//Create a Protocol object using the format object just created
var vector_protocol = new OpenLayers.Protocol.HTTP({
url: 'ex5_data.json',
format: vector_format
});
//Create an array of strategy objects
var vector_strategies = [new OpenLayers.Strategy.Fixed()];
//Create a vector layer that contains a Format, Protocol, and Strategy class
var vector_layer = new OpenLayers.Layer.Vector('More Advanced Vector Layer',{
protocol: vector_protocol,
strategies: vector_strategies
});
map.addLayer(vector_layer);
if(!map.getCenter()){
map.zoomToMaxExtent();
}
}
I just tried your code (chri_chri) .
I tried to load an images but seem to be wrong...
Im also now to openlayers
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Floorplan test</title>
<script src="http://www.openlayers.org/api/OpenLayers.js"></script>
<script src="http://www.openstreetmap.org/openlayers/OpenStreetMap.js"></script>
<link rel="stylesheet" href="http://openlayers.org/api/theme/default/style.css" type="text/css" />
<style type="text/css">
#bmap {
width:83%;
height:90%;
border:2px solid black;
position:absolute;
top:10px;
left:200px;
}
body{
background:yellow;
}
</style>
<script>
var map;
function init(){
map = new OpenLayers.Map('map');
var options = {numZoomLevels: 3}
var floorplan = new OpenLayers.Layer.Image(
'Floorplan Map',
'png_1.jpg',
new OpenLayers.Bounds(-300, -188.759, 300, 188.759),
new OpenLayers.Size(580, 288),
options
);
map.addLayer(floorplan);
//Create a Format object
var vector_format = new OpenLayers.Format.GeoJSON({});
//Create a Protocol object using the format object just created
var vector_protocol = new OpenLayers.Protocol.HTTP({
url: 'ex5_data.json',
format: vector_format
});
//Create an array of strategy objects
var vector_strategies = [new OpenLayers.Strategy.Fixed()];
//Create a vector layer that contains a Format, Protocol, and Strategy class
var vector_layer = new OpenLayers.Layer.Vector('More Advanced Vector Layer',{
protocol: vector_protocol,
strategies: vector_strategies
});
map.addLayer(vector_layer);
if(!map.getCenter()){
map.zoomToMaxExtent();
}
}
</script>
</head>
<body>
<h3>Floorplan</h3>
<body onload="init();">
<div id="bmap"></div>
</body>
</html>
What im starting up with is to load a floorplan map and try to scale it.
you can look at this example postgis to geojson php clarifying how to use a php script the get geojson data through postgis database.
and as you did in your geojson layer url, u pass the url of your php script...
hope it helps;
I use PostGis together with Openlayers 3/4 without GeoServer. The way I choose is to get geojson from a Postgis-database via a function I call, which returns the data and styles it acording to my settings.
In Javascript I define the data and styling => Javascript-function calls a php-script via GET to retrive data from Postgis => function styles the data to render in Openlayers 3. The whole sripts can be seen in Is there an easy way to use Postgis-geojson in Openlayers 3?
Be aware, that the proposed solution is not secure, because GET-strings could be manipulated (sql-injections). I use a call via https and the serverside php-script checks if a SESSION is set. So the scripts cannot be executed without beeing logged in. We use this in a very small group, but it might be not a good idea to use it in an environment, where many poeple are accessing the data.
So improvments in security would be good.
You can use PHP
<?php
ini_set('display_errors', 1);
# Connect to PostgreSQL database
$conn = pg_connect("dbname='gisdata' user='username'
password='password' host='localhost'")
or die ("Could not connect to server\n");
$result = pg_fetch_all(pg_query($conn, "SELECT row_to_json(fc)
FROM ( SELECT 'FeatureCollection' As type,
array_to_json(array_agg(f)) As features
FROM (SELECT 'Feature' As type
, ST_AsGeoJSON(lg.geom, 4)::json As geometry
, row_to_json((SELECT l FROM (SELECT id, designacao) As l
)) As properties
FROM hidrog As lg ) As f ) As fc;"));
if (!$result) {
echo "An error occurred.\n";
exit;
}
#echo json_encode($result, JSON_NUMERIC_CHECK);
$json_data = json_encode($result);
file_put_contents('test.json', $json_data);
$jsonString = file_get_contents('test.json');
$json_new = substr($jsonString, 17,-2);
$json_new = str_ireplace('\"', '"', $json_new);
echo $json_new;
file_put_contents('test_new.json', $json_new);
?>
I'm curious if I can inject PHP code to the datatable of google visualization instead of using JSON strings.
<html>
<head>
<!--Load the AJAX API-->
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
// Load the Visualization API and the piechart package.
google.load('visualization', '1.0', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
// Callback that creates and populates a data table,
// instantiates the pie chart, passes in the data and
// draws it.
function drawChart() {
// Create the data table.
var data = new google.visualization.DataTable();
data.addColumn('string', 'Topping');
data.addColumn('number', 'Slices');
data.addRows(
<?php
some PHP code that echoes the same format like this
[['Mushrooms', 3],['Onions', 1],['Olives', 1],['Zucchini', 1],['Pepperoni', 2]]
?>);
// Set chart options
var options = {'title':'How Much Pizza I Ate Last Night',
'width':400,
'height':300};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<!--Div that will hold the pie chart-->
<div id="chart_div"></div>
</body>
</html>
I'm trying to make events on google visualization. Any help/suggestions is very much appreciated. Thanks!
#scibuff has the right idea.
$my_array = array(
array('Mushrooms',3),
array('Onions',1),
array('Olives',1),
array('Zucchini',1),
array('Pepperoni',2)
);
echo json_encode( $my_array );
will give you [["Mushrooms",3],["Onions",1],["Olives",1],["Zucchini",1],["Pepperoni",2]]