I am working on a graph that shows the temperature, date and time. Until now everything is working pretty good, but in order to get the new values from my MySQL database in need to completely refresh my page.
I want to be able to update the graph without pressing the Refresh button.
This is the code:
<?php require($_SERVER['DOCUMENT_ROOT'] . '/assets/php/getTemp.php' ); ?>
<!DOCTYPE html>
<meta charset="utf-8">
<head>
<title>RPi</title>
</head>
<style>
div.tooltip {
position: absolute;
text-align: center;
width: 120px;
height: 28px;
padding: 3px;
font: 12px sans-serif;
background: lightgrey;
border: 0px;
border-radius: 8px;
pointer-events: none;
}
body { font: 14px Arial;}
path {
stroke: #FF8C00;
stroke-width: 3;
fill: none;
}
.axis path,
.axis line {
fill: none;
stroke: black;
stroke-width: 2;
shape-rendering: crispEdges;
}
.grid .tick {
stroke: grey;
stroke-opacity: 0.3;
shape-rendering: geometricPrecision;
}
.grid path {
stroke-width: 0;
}
</style>
<body>
<div id="option">
<input name="updateButton"
type="button"
value="Update"
onclick="updateData()"
/>
</div>
<!-- load the d3.js library -->
<script src="http://d3js.org/d3.v3.min.js"></script>
<script>
var margin = {top: 30, right: 20, bottom: 30, left: 50},
width = 800 - margin.left - margin.right,
height = 270 - margin.top - margin.bottom;
var parseDate = d3.time.format("%Y-%m-%d %H:%M:%S").parse;
var formatTime = d3.time.format("%d-%m-%Y %H:%M:%S");
var x = d3.time.scale().range([0, width]);
var y = d3.scale.linear().range([height, 0]);
var xAxis = d3.svg.axis().scale(x)
.orient("bottom");
var yAxis = d3.svg.axis().scale(y)
.orient("left").ticks(5);
var valueline = d3.svg.line()
.interpolate("basis")
.x(function(d) { return x(d.datetime); })
.y(function(d) { return y(d.temperature); });
var div = d3.select("body").append("div")
.attr("class", "tooltip")
.style("opacity", 0);
var svg = d3.select("body")
.append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform",
"translate(" + margin.left + "," + margin.top + ")");
function make_x_axis() {
return d3.svg.axis()
.scale(x)
.orient("bottom")
.ticks(5)
}
function make_y_axis() {
return d3.svg.axis()
.scale(y)
.orient("left")
.ticks(5)
}
<?php echo "data=".$json_data.";" ?>
data.forEach(function(d) {
d.datetime = parseDate(d.datetime);
d.temperature = +d.temperature;
});
x.domain(d3.extent(data, function(d) { return d.datetime; }));
y.domain([0, d3.max(data, function(d) { return d.temperature; })]);
svg.append("path")
.attr("class", "line")
.attr("d", valueline(data));
svg.selectAll("dot")
.data(data)
.enter().append("circle")
.attr("r", 4)
.attr("cx", function(d) { return x(d.datetime); })
.attr("cy", function(d) { return y(d.temperature); })
.on("mouseover", function(d) {
div.transition()
.duration(200)
.style("opacity", 1);
div.html(formatTime(d.datetime) + "<br/>" + d.temperature + " ℃")
.style("left", (d3.event.pageX + 16) + "px")
.style("top", (d3.event.pageY + 16) + "px")
.style("position", "absolute");
})
.on("mouseout", function(d) {
div.transition()
.duration(50)
.style("opacity", 0);
});
svg.append("g")
.attr("class", "grid")
.attr("transform", "translate(0," + height + ")")
.call(make_x_axis()
.tickSize(-height, 0, 0)
.tickFormat("")
)
svg.append("g")
.attr("class", "grid")
.call(make_y_axis()
.tickSize(-width, 0, 0)
.tickFormat("")
)
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
svg.append("g")
.attr("class", "y axis")
.call(yAxis);
</script>
</body>
I tried to do this:
function updateData() {
//d3.json("/assets/php/getTemp.php", function(error, data) {
<?php echo "data=".$json_data.";" ?>
data.forEach(function(d) {
d3.select("body").selectAll("svg")
d.datetime = parseDate(d.datetime);
d.temperature = +d.temperature;
});
x.domain(d3.extent(data, function(d) { return d.datetime; }));
y.domain([0, d3.max(data, function(d) { return d.temperature; })]);
var svg = d3.select("body").transition();
svg.select(".line")
.duration(750)
.attr("d", valueline(data));
svg.select(".x.axis")
.duration(750)
.call(xAxis);
svg.select(".y.axis")
.duration(750)
.call(yAxis);
};
but nothing happens, not even an error.
If it matters this is the PHP code used to get the temperatures and time form MySQL:
<?php
$hostname = 'localhost';
$username = 'root';
$password = 'admin';
try {
$dbh = new PDO("mysql:host=$hostname;dbname=temp_database",
$username, $password);
$sth = $dbh->prepare("
SELECT `datetime`, `temperature` FROM `tempLog`
");
$sth->execute();
$result = $sth->fetchAll(PDO::FETCH_ASSOC);
$dbh = null;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
$json_data = json_encode($result);
?>
What i need to do ?
Look into using the d3.json function. This lets you get json from php scripts without reloading the entire page from scratch. It's AJAX stuff, but the d3 helper functions hide the details.
https://github.com/mbostock/d3/wiki/Requests
PS. Remember, it will be an asynchronous call, so see the accepted answer here as well:
JSON output from PHP using d3.json
As to why it doesn't work currently, my hunch*, though there's not enough info to confirm, is that there's no change because it's always the same data, so nothing will change
<?php echo "data=".$json_data.";" ?>
That line^^^ in updateData is evaluated once at the start and then the whole function is plonked into the javascript realm. However many times you then call updateData, that previously generated javascript variable (data={some_json}) won't change without reloading the php page that generated updateData, even if you call that database related php that generates the server side variable.
*could be nonsense, but the bit above the line is still right
Related
I have a big problem. I have a mysql database which contains 12 character length fields. I would like to display somehow.
Sample data from the field:
233215334523
I would like to display 0 and 1 with red background 2 3 with yellow background and 4 5 with green background.
Important! I know str_split could split the string into characters, or I could use $string[1] $string[2] etc. also, but not now, because this cms use the lex parser ( you couldn't use php variables here!).
So I need some great idea how could I split virtual this 12 character length variable. The best should be some which display these numbers with the background colors what I wrote earlier.
I hope someone could help for me, because I have no idea. Many thanks!
Wrap each character in a span, with a classname:
HTML:
<div id="fieldToSplit">233215334523</div>
javascript:
var element = document.getElementById("fieldToSplit")
var data = element.innerHTML.split("");
var wrappedString = "";
for (var i = 0; i < data.length; i++) {
wrappedString += "<span class='shade" + data[i] + "'>" + data[i] + "</span>";
}
element.innerHTML = wrappedString;
CSS:
.shade0, .shade1 {
background-color: #FF0000;
}
.shade2, .shade3 {
background-color: #FFFF00;
}
.shade4, .shade5 {
background-color: #00FF00;
}
This solution allows you to freely style each digit independently, say you wanted a darker green for 5 than for 4. And if later you need styles for 6,7,8, and 9, all you need to do is add classes .shade6, .shade7, .shade8, and .shade9.
Fiddle here:
http://jsfiddle.net/rwbm9ttn/1/
Something like this?
$(document).ready(function() {
var letters = $('.source').html().split(/\s?/)
for (var i = 0; i <= letters.length; ++i) {
$('<span class="lt' + letters[i] + '">').html(letters[i]).appendTo(".letters");
}
});
.lt2 {
background: yellow;
}
.lt3 {
background: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<div class="source">233215334523</div>
<div class="letters"></div>
Here is a pure jquery & CSS solution:
http://jsfiddle.net/k91ax5g9/1/
HTML
<div class='num'>101234567</div>
<div class='num'>1011223444</div>
<div class='num'>124413223</div>
<div class='num'>323123133</div>
JS
$(".num").each(function(){
var $el = $(this);
var t =$el.html();
$el.html('');
for(var c in t){
var char = t[c];
$el.append($("<span>", {'text_val': char}).html(char));
}
});
CSS
[text_val="0"], [text_val="1"]{
background: red;
}
[text_val="2"], [text_val="3"]{
background: orange;
}
[text_val="4"], [text_val="5"]{
background: green;
}
An entirely jQuery version would be like this -
$(document).ready(function(){
var data = 233215334523;
var str = data.toString();
var hold = '';
for(var i = 0; i<str.length; i++)
{
if(str[i] == 0 || str[i] == 1)
{
hold = hold + '<span style="background-color: red;">'+str[i]+'</span>';
$('.print').html(hold);
}
else if(str[i] == 2 || str[i] == 3)
{
hold = hold + '<span style="background-color: yellow;">'+str[i]+'</span>';
$('.print').html(hold);
}
else if(str[i] == 4 || str[i] == 5)
{
hold = hold + '<span style="background-color: green;">'+str[i]+'</span>';
$('.print').html(hold);
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="print"></p>
I am working on custom form builder for one of my clients where we have functionality like drag fields , resize, apply css like borders and align fields using jquery. i am done with dragging,resizing and css but one of the major requirement is to apply "google drawing red rule " as we have in google drawing.
i have attached a screencast video as well as screencast images to clarify what red rule is.
http://screencast.com/t/ow6s5zKt9P
http://screencast.com/t/e1SL26gFJT8v
http://screencast.com/t/QAJGB7PzEwB
http://screencast.com/t/OoM6BqAH
Video:
http://screencast.com/t/ORaqAVWX4XGu
As can be seen in the above screen casts when ever we drag/draw a field and overlap with other fields it highlights the vertical and horizontal center of the dragging field or the overlap field in Red color (hence the title red rule). it also highlights the borders of any field overlapping the other field or moving out of the canvas area. it also shows whether field can be inscribed inside in another field while dragging.
I am looking at some one who can guide me in correct direction to acchive this functionality. i need to apply this red rule effect other than drawing or any thing. please sugguest any possibilities.
Any help is greatly appreciated.
i got the solutuon.
you can check her http://jsfiddle.net/elin/A6CpP/
<div id="parent">
<div class="other-objects" style="left:0px;top:300px;background:#a00;"></div>
<div class="other-objects"></div>
<div class="other-objects" style="left:400px;top:20px;"></div>
<div class="objectx"></div>
<div class="objecty"></div>
</div>
$.ui.plugin.add("draggable", "smartguides", {
start: function(event, ui) {
var i = $(this).data("draggable"), o = i.options;
i.elements = [];
$(o.smartguides.constructor != String ? ( o.smartguides.items || ':data(draggable)' ) : o.smartguides).each(function() {
var $t = $(this); var $o = $t.offset();
if(this != i.element[0]) i.elements.push({
item: this,
width: $t.outerWidth(), height: $t.outerHeight(),
top: $o.top, left: $o.left
});
});
},
stop: function(event, ui) {
$(".objectx").css({"display":"none"});
$(".objecty").css({"display":"none"});
},
drag: function(event, ui) {
var inst = $(this).data("draggable"), o = inst.options;
var d = o.tolerance;
$(".objectx").css({"display":"none"});
$(".objecty").css({"display":"none"});
var x1 = ui.offset.left, x2 = x1 + inst.helperProportions.width,
y1 = ui.offset.top, y2 = y1 + inst.helperProportions.height,
xc = (x1 + x2) / 2, yc = (y1 + y2) / 2;
for (var i = inst.elements.length - 1; i >= 0; i--){
var l = inst.elements[i].left, r = l + inst.elements[i].width,
t = inst.elements[i].top, b = t + inst.elements[i].height,
hc = (l + r) / 2, vc = (t + b) / 2;
var ls = Math.abs(l - x2) <= d;
var rs = Math.abs(r - x1) <= d;
var ts = Math.abs(t - y2) <= d;
var bs = Math.abs(b - y1) <= d;
var hs = Math.abs(hc - xc) <= d;
var vs = Math.abs(vc - yc) <= d;
if(ls) {
ui.position.left = inst._convertPositionTo("relative", { top: 0, left: l - inst.helperProportions.width }).left - inst.margins.left;
$(".objectx").css({"left":l-d-4,"display":"block"});
}
if(rs) {
ui.position.left = inst._convertPositionTo("relative", { top: 0, left: r }).left - inst.margins.left;
$(".objectx").css({"left":r-d-4,"display":"block"});
}
if(ts) {
ui.position.top = inst._convertPositionTo("relative", { top: t - inst.helperProportions.height, left: 0 }).top - inst.margins.top;
$(".objecty").css({"top":t-d-4,"display":"block"});
}
if(bs) {
ui.position.top = inst._convertPositionTo("relative", { top: b, left: 0 }).top - inst.margins.top;
$(".objecty").css({"top":b-d-4,"display":"block"});
}
if(hs) {
ui.position.left = inst._convertPositionTo("relative", { top: 0, left: hc - inst.helperProportions.width/2 }).left - inst.margins.left;
$(".objectx").css({"left":hc-d-4,"display":"block"});
}
if(vs) {
ui.position.top = inst._convertPositionTo("relative", { top: vc - inst.helperProportions.height/2, left: 0 }).top - inst.margins.top;
$(".objecty").css({"top":vc-d-4,"display":"block"});
}
};
}
});
$('.other-objects').draggable({
containment: 'parent',
smartguides:".other-objects",
tolerance:5
});
#parent{
width:600px;
height:500px;
border:1px solid #000;
position:relative;
}
.other-objects{
background:#aaa;
width:100px;
height:100px;
display:block;
position:relative;
left:140px;
top:50px;
}
.objectx{
display:none;
//background:#fff;
width:0px;
height:100%;
position:absolute;
top:0px;
left:10px;
border-left: 2px solid red;
}
.objecty{
display:none;
//background:#fff;
width:100%;
height:0px;
position:absolute;
top:10px;
left:0px;
border-bottom: 2px solid red;
}
I want some suggestions regarding image upload form like facebook and tumblr which can preview multiple images with caption and description fields with each image and if user wants to remove any image before uploading he is able to do that. So please suggest me how to achieve this i have tried this but i am having issue with removing image from input type = file as it is readonly i am facing problem when i am submitting the form on server. Please give me your ideas i really need help i have deadline of this month i am badly stuck in this problem. I am using php and jquery. Note: Please dont suggest any plugins.
Thanks in advance.
I have face same problem like you
now i have found solution for that i think this will be useful for you to solve your problem
<input type="file" id="attachfile" name="replyFiles" multiple> <!--File Element for multiple intput-->
<div id="#filelist"></div>
<script>
var selDiv = "";
var storedFiles = []; //store the object of the all files
document.addEventListener("DOMContentLoaded", init, false);
function init() {
//To add the change listener on over file element
document.querySelector('#attachfile').addEventListener('change', handleFileSelect, false);
//allocate division where you want to print file name
selDiv = document.querySelector("#filelist");
}
//function to handle the file select listenere
function handleFileSelect(e) {
//to check that even single file is selected or not
if(!e.target.files) return;
//for clear the value of the selDiv
selDiv.innerHTML = "";
//get the array of file object in files variable
var files = e.target.files;
var filesArr = Array.prototype.slice.call(files);
//print if any file is selected previosly
for(var i=0;i<storedFiles.length;i++)
{
selDiv.innerHTML += "<div class='filename'> <span class='removefile' data-file='"+storedFiles[i].name+"'> " + storedFiles[i].name + "</span></div>";
}
filesArr.forEach(function(f) {
//add new selected files into the array list
storedFiles.push(f);
//print new selected files into the given division
selDiv.innerHTML += "<div class='filename'> <span class='removefile' data-file='"+storedFiles[i].name+"'> " + f.name + "</span></div>";
});
//store the array of file in our element this is send to other page by form submit
$("input[name=replyfiles]").val(storedFiles);
}
//This function is used to remove the file form the selection
function removeFile(e) {
var file = $(this).data("file"); //To take the name of the file
for(var i=0;i<storedFiles.length;i++) { //for find the file from the array
if(storedFiles[i].name === file) {
storedFiles.splice(i,1); //remove file from the list
break;
}
}
//now store the list of the all remaining file in our element name which will submit with the form
$("input[name=replyfiles]").val(storedFiles);
$(this).parent().remove();
}
$(document).ready(function(){
$("body").on("click", ".removefile", removeFile);
})
</script>
//I added event handler for the file upload control to access the files properties.
document.addEventListener("DOMContentLoaded", init, false);
//To save an array of attachments
var AttachmentArray = [];
//counter for attachment array
var arrCounter = 0;
//to make sure the error message for number of files will be shown only one time.
var filesCounterAlertStatus = false;
//un ordered list to keep attachments thumbnails
var ul = document.createElement("ul");
ul.className = "thumb-Images";
ul.id = "imgList";
function init() {
//add javascript handlers for the file upload event
document
.querySelector("#files")
.addEventListener("change", handleFileSelect, false);
}
//the handler for file upload event
function handleFileSelect(e) {
//to make sure the user select file/files
if (!e.target.files) return;
//To obtaine a File reference
var files = e.target.files;
// Loop through the FileList and then to render image files as thumbnails.
for (var i = 0, f; (f = files[i]); i++) {
//instantiate a FileReader object to read its contents into memory
var fileReader = new FileReader();
// Closure to capture the file information and apply validation.
fileReader.onload = (function(readerEvt) {
return function(e) {
//Apply the validation rules for attachments upload
ApplyFileValidationRules(readerEvt);
//Render attachments thumbnails.
RenderThumbnail(e, readerEvt);
//Fill the array of attachment
FillAttachmentArray(e, readerEvt);
};
})(f);
// Read in the image file as a data URL.
// readAsDataURL: The result property will contain the file/blob's data encoded as a data URL.
// More info about Data URI scheme https://en.wikipedia.org/wiki/Data_URI_scheme
fileReader.readAsDataURL(f);
}
document
.getElementById("files")
.addEventListener("change", handleFileSelect, false);
}
//To remove attachment once user click on x button
jQuery(function($) {
$("div").on("click", ".img-wrap .close", function() {
var id = $(this)
.closest(".img-wrap")
.find("img")
.data("id");
//to remove the deleted item from array
var elementPos = AttachmentArray.map(function(x) {
return x.FileName;
}).indexOf(id);
if (elementPos !== -1) {
AttachmentArray.splice(elementPos, 1);
}
//to remove image tag
$(this)
.parent()
.find("img")
.not()
.remove();
//to remove div tag that contain the image
$(this)
.parent()
.find("div")
.not()
.remove();
//to remove div tag that contain caption name
$(this)
.parent()
.parent()
.find("div")
.not()
.remove();
//to remove li tag
var lis = document.querySelectorAll("#imgList li");
for (var i = 0; (li = lis[i]); i++) {
if (li.innerHTML == "") {
li.parentNode.removeChild(li);
}
}
});
});
//Apply the validation rules for attachments upload
function ApplyFileValidationRules(readerEvt) {
//To check file type according to upload conditions
if (CheckFileType(readerEvt.type) == false) {
alert(
"The file (" +
readerEvt.name +
") does not match the upload conditions, You can only upload jpg/png/gif files"
);
e.preventDefault();
return;
}
//To check file Size according to upload conditions
if (CheckFileSize(readerEvt.size) == false) {
alert(
"The file (" +
readerEvt.name +
") does not match the upload conditions, The maximum file size for uploads should not exceed 300 KB"
);
e.preventDefault();
return;
}
//To check files count according to upload conditions
if (CheckFilesCount(AttachmentArray) == false) {
if (!filesCounterAlertStatus) {
filesCounterAlertStatus = true;
alert(
"You have added more than 10 files. According to upload conditions you can upload 10 files maximum"
);
}
e.preventDefault();
return;
}
}
//To check file type according to upload conditions
function CheckFileType(fileType) {
if (fileType == "image/jpeg") {
return true;
} else if (fileType == "image/png") {
return true;
} else if (fileType == "image/gif") {
return true;
} else {
return false;
}
return true;
}
//To check file Size according to upload conditions
function CheckFileSize(fileSize) {
if (fileSize < 300000) {
return true;
} else {
return false;
}
return true;
}
//To check files count according to upload conditions
function CheckFilesCount(AttachmentArray) {
//Since AttachmentArray.length return the next available index in the array,
//I have used the loop to get the real length
var len = 0;
for (var i = 0; i < AttachmentArray.length; i++) {
if (AttachmentArray[i] !== undefined) {
len++;
}
}
//To check the length does not exceed 10 files maximum
if (len > 9) {
return false;
} else {
return true;
}
}
//Render attachments thumbnails.
function RenderThumbnail(e, readerEvt) {
var li = document.createElement("li");
ul.appendChild(li);
li.innerHTML = [
'<div class="img-wrap"> <span class="close">×</span>' +
'<img class="thumb" src="',
e.target.result,
'" title="',
escape(readerEvt.name),
'" data-id="',
readerEvt.name,
'"/>' + "</div>"
].join("");
var div = document.createElement("div");
div.className = "FileNameCaptionStyle";
li.appendChild(div);
div.innerHTML = [readerEvt.name].join("");
document.getElementById("Filelist").insertBefore(ul, null);
}
//Fill the array of attachment
function FillAttachmentArray(e, readerEvt) {
AttachmentArray[arrCounter] = {
AttachmentType: 1,
ObjectType: 1,
FileName: readerEvt.name,
FileDescription: "Attachment",
NoteText: "",
MimeType: readerEvt.type,
Content: e.target.result.split("base64,")[1],
FileSizeInBytes: readerEvt.size
};
arrCounter = arrCounter + 1;
}
/*Copied from bootstrap to handle input file multiple*/
.btn {
display: inline-block;
padding: 6px 12px;
margin-bottom: 0;
font-size: 14px;
font-weight: normal;
line-height: 1.42857143;
text-align: center;
white-space: nowrap;
vertical-align: middle;
cursor: pointer;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
background-image: none;
border: 1px solid transparent;
border-radius: 4px;
}
/*Also */
.btn-success {
border: 1px solid #c5dbec;
background: #d0e5f5;
font-weight: bold;
color: #2e6e9e;
}
/* This is copied from https://github.com/blueimp/jQuery-File-Upload/blob/master/css/jquery.fileupload.css */
.fileinput-button {
position: relative;
overflow: hidden;
}
.fileinput-button input {
position: absolute;
top: 0;
right: 0;
margin: 0;
opacity: 0;
-ms-filter: "alpha(opacity=0)";
font-size: 200px;
direction: ltr;
cursor: pointer;
}
.thumb {
height: 80px;
width: 100px;
border: 1px solid #000;
}
ul.thumb-Images li {
width: 120px;
float: left;
display: inline-block;
vertical-align: top;
height: 120px;
}
.img-wrap {
position: relative;
display: inline-block;
font-size: 0;
}
.img-wrap .close {
position: absolute;
top: 2px;
right: 2px;
z-index: 100;
background-color: #d0e5f5;
padding: 5px 2px 2px;
color: #000;
font-weight: bolder;
cursor: pointer;
opacity: 0.5;
font-size: 23px;
line-height: 10px;
border-radius: 50%;
}
.img-wrap:hover .close {
opacity: 1;
background-color: #ff0000;
}
.FileNameCaptionStyle {
font-size: 12px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<div>
<label style="font-size: 14px;">
<span style='color:navy;font-weight:bold'>Attachment Instructions :</span>
</label>
<!--To give the control a modern look, I have applied a stylesheet in the parent span.-->
<span class="btn btn-success fileinput-button">
<span>Select Attachment</span>
<input type="file" name="files[]" id="files" multiple accept="image/jpeg, image/png, image/gif,"><br />
</span>
<output id="Filelist"></output>
</div>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>Yelp Search API Example</title>
<style type="text/css">
html, body {width: 100%; height: 100%; font-family: arial;}
body {margin:0;padding 0;overflow: hidden;}
#mapContainer {padding-top: 50px;}
#map, #mapContainer {width:100%; height: 100%;}
#top {position:absolute; top:0; left:0; width: 100%; height: 50px; line-height: 50px;}
#spinner { visibility: hidden; margin-left:3px;}
#poweredby, #searchbox {line-height: 50px;}
#searchbox {text-align: center;}
#poweredby { float: right; margin-right: 3px;}
#poweredby img { vertical-align: baseline;}
.marker {font-size: 11px;}
.marker .businessimage { float: left;}
.marker .ratingsimage {vertical-align:middle; margin-top:0px;}
.marker .businessinfo { margin-left: 110px;}
</style>
<script src="http://maps.google.com/maps?file=api&v=2&key=[AIzaSyByEg0pBD4dGr3gZCk863XZZ0ZBkqhDhR4]"
type="text/javascript"></script>
<script type="text/javascript">
var YWSID = "aSVpoAZwxvtcwsscdWjBBw"; // common required parameter (api key)
var map = null;
var icon = null;
/*
* Creates the map object and calls setCenterAndBounds
* to instantiate it.
*/
function load() {
map = new GMap2(document.getElementById("map"));
GEvent.addListener(map, "load", function() {updateMap();});
map.setCenter(new GLatLng(40.296448,-79.478141),13);
map.addControl(new GLargeMapControl());
map.addControl(new GMapTypeControl());
map.setMapType(G_HYBRID_MAP);
if (window.attachEvent) window.attachEvent("onresize", function() { map.checkResize()} );
else if (window.addEventListener) window.addEventListener("resize", function() { map.checkResize()}, false);
// setup our marker icon
icon = new GIcon();
icon.image = "images/marker_star.png";
icon.shadow = "images/marker_shadow.png";
icon.iconSize = new GSize(20, 29);
icon.shadowSize = new GSize(38, 29);
icon.iconAnchor = new GPoint(15, 29);
icon.infoWindowAnchor = new GPoint(15, 3);
}
/*
* Construct the URL to call for the API request
*/
function constructYelpURL() {
var mapBounds = map.getBounds();
var URL = "http://api.yelp.com/" +
"business_review_search?"+
"callback=" + "handleResults" +
"&term=" + document.getElementById("term").value +
"&num_biz_requested=10" +
"&tl_lat=" + mapBounds.getSouthWest().lat() +
"&tl_long=" + mapBounds.getSouthWest().lng() +
"&br_lat=" + mapBounds.getNorthEast().lat() +
"&br_long=" + mapBounds.getNorthEast().lng() +
"&ywsid=" + YWSID;
return encodeURI(URL);
}
/*
* Called on the form submission: updates the map by
* placing markers on it at the appropriate places
*/
function updateMap() {
// turn on spinner animation
document.getElementById("spinner").style.visibility = 'visible';
var yelpRequestURL = constructYelpURL();
/* clear existing markers */
map.clearOverlays();
/* do the api request */
var script = document.createElement('script');
script.src = yelpRequestURL;
script.type = 'text/javascript';
var head = document.getElementsByTagName('head').item(0);
head.appendChild(script);
return false;
}
/*
* If a sucessful API response is received, place
* markers on the map. If not, display an error.
*/
function handleResults(data) {
// turn off spinner animation
document.getElementById("spinner").style.visibility = 'hidden';
if(data.message.text == "OK") {
if (data.businesses.length == 0) {
alert("Error: No businesses were found near that location");
return;
}
for(var i=0; i<data.businesses.length; i++) {
biz = data.businesses[i];
createMarker(biz, new GLatLng(biz.latitude, biz.longitude), i);
}
}
else {
alert("Error: " + data.message.text);
}
}
/*
* Formats and returns the Info Window HTML
* (displayed in a balloon when a marker is clicked)
*/
function generateInfoWindowHtml(biz) {
var text = '<div class="marker">';
// image and rating
text += '<img class="businessimage" src="'+biz.photo_url+'"/>';
// div start
text += '<div class="businessinfo">';
// name/url
text += ''+biz.name+'<br/>';
// stars
text += '<img class="ratingsimage" src="'+biz.rating_img_url_small+'"/> based on ';
// reviews
text += biz.review_count + ' reviews<br/><br />';
// categories
text += formatCategories(biz.categories);
// neighborhoods
if(biz.neighborhoods.length)
text += formatNeighborhoods(biz.neighborhoods);
// address
text += biz.address1 + '<br/>';
// address2
if(biz.address2.length)
text += biz.address2+ '<br/>';
// city, state and zip
text += biz.city + ', ' + biz.state + ' ' + biz.zip + '<br/>';
// phone number
if(biz.phone.length)
text += formatPhoneNumber(biz.phone);
// Read the reviews
text += '<br/>Read the reviews »<br/>';
// div end
text += '</div></div>'
return text;
}
/*
* Formats the categories HTML
*/
function formatCategories(cats) {
var s = 'Categories: ';
for(var i=0; i<cats.length; i++) {
s+= cats[i].name;
if(i != cats.length-1) s += ', ';
}
s += '<br/>';
return s;
}
/*
* Formats the neighborhoods HTML
*/
function formatNeighborhoods(neighborhoods) {
s = 'Neighborhoods: ';
for(var i=0; i<neighborhoods.length; i++) {
s += '' + neighborhoods[i].name + '';
if (i != neighborhoods.length-1) s += ', ';
}
s += '<br/>';
return s;
}
/*
* Formats the phone number HTML
*/
function formatPhoneNumber(num) {
if(num.length != 10) return '';
return '(' + num.slice(0,3) + ') ' + num.slice(3,6) + '-' + num.slice(6,10) + '<br/>';
}
/*
* Creates a marker for the given business and point
*/
function createMarker(biz, point, markerNum) {
var infoWindowHtml = generateInfoWindowHtml(biz)
var marker = new GMarker(point, icon);
map.addOverlay(marker);
GEvent.addListener(marker, "click", function() {
marker.openInfoWindowHtml(infoWindowHtml, {maxWidth:400});
});
// automatically open first marker
if (markerNum == 0)
marker.openInfoWindowHtml(infoWindowHtml, {maxWidth:400});
}
//]]>
</script>
</head>
<body onload="load()">
<div id="top">
<div id="poweredby">Powered by <img src="http://static.px.yelp.com/i/map/miniMapLogo.png" border="0" /></div>
<div id="searchbox">
<form>
Search for <input type="text" id="term" name="term" value="flannery-cars-greensburg"/> <input type="button" value="Search" onclick="return updateMap();"/>
<img id="spinner" src="images/spinner.gif" />
<span class="error" id="errorMessage" />
</form>
</div>
</div>
<div id="mapContainer"><div id="map"></div></div>
</body>
</html>
Website
http://www.724-streamline-marketing.com/testing2.html
I am trying to gather metrics for reviews, rating, map location from the yelp api, I am unsure why it will not stay.
Any help would be grateful or even point me in the right direction on using a 3rd party app to create yelp data
Your problem is simple,
<script src="http://maps.google.com/maps?file=api&v=2&key=[AIzaSyByEg0pBD4dGr3gZCk863XZZ0ZBkqhDhR4]"
Get rid of the brackets [] surrounding the key.
I have recently gotten into the d3 javascript library.
I have made a scatter plot chart that grabs random values from an array
Here is the code
<!DOCTYPE html>
<meta charset="utf-8">
<head>
<script type="text/javascript" src="d3.v3.js"></script>
<style>
.axis path,
.axis line
{
fill: none;
stroke: black;
shape-rendering: crispEdges;
}
.axis text
{
font-family: sans-serif;
font-size: 11px;
}
</style>
</head>
<body>
<script type="text/javascript">
//Width and height
var w = 500;
var h = 300;
//fix padding issues
var padding = 30;
//var dataset = [
// [5, 20], [480, 90], [250, 50], [100, 33], [330, 95],
// [410, 12], [475, 44], [25, 67], [85, 21], [220, 88], [600, 150], [77, 69], [290, 68]
// ];
var dataset = [];
var numDataPoints = 50;
var xRange = Math.random() * 1000;
var yRange = Math.random() * 1000;
for (var i = 0; i < numDataPoints; i++) {
var newNumber1 = Math.round(Math.random() * xRange);
var newNumber2 = Math.round(Math.random() * yRange);
dataset.push([newNumber1, newNumber2]);
}
//Create scale functions
var rScale = d3.scale.linear()
.domain([0, d3.max(dataset, function(d) { return d[1]; })])
.range([2, 5]);
var xScale = d3.scale.linear()
.domain([0, d3.max(dataset, function(d) { return d[0]; })])
.range([padding, w - padding * 2]);
var yScale = d3.scale.linear()
.domain([0, d3.max(dataset, function(d) { return d[1]; })])
.range([h - padding, padding]);
//Create SVG element
var svg = d3.select("body")
.append("svg")
.attr("width", w)
.attr("height", h);
//create circles
svg.selectAll("circle")
.data(dataset)
.enter()
.append("circle")
.attr("cx", function(d) {
return xScale(d[0]); //use scale function
})
.attr("cy", function(d) {
return yScale(d[1]); //use scale function
})
.attr("r", function(d) {
return rScale(d[1]);
});
//create svg text
//svg.selectAll("text")
// .data(dataset)
// .enter()
// .append("text")
// .text(function(d) {
// return d[0] + "," + d[1];
// })
// .attr("x", function(d) {
// return xScale(d[0]);
// })
// .attr("y", function(d) {
// return yScale(d[1]);
// })
// .attr("font-family", "sans-serif")
// .attr("font-size", "11px")
// .attr("fill", "red");
//create axis
var xAxis = d3.svg.axis()
.scale(xScale)
.orient("bottom")
.ticks(5);
//place axis
svg.append("g")
.attr("class", "axis")
.attr("transform", "translate(0," + (h - padding) + ")")
.call(xAxis);
//define y axis
var yAxis = d3.svg.axis()
.scale(yScale)
.orient("left")
.ticks(5);
//place y axis
svg.append("g")
.attr("class", "axis")
.attr("transform", "translate(" + padding + ",0)")
.call(yAxis);
</script>
</body>
As you can see, it graphs the values that get randomly created and placed into an array. This is great, but I'd like to make one small change. I want to create a php file that generates random numbers and have those be plotted instead.
The php file is simple enough
<?php
echo rand(1, 50);
?>
So how do i actually
1. Get the php file to generate 20 random numbers
2. Actually place those numbers into the array for scatter graph.
Thanks!
This PHP code will do the trick:
<?php
$i=20;
while($i > 0) {
echo rand(1, 50);
$i--;
}
?>
To generate the random numbers in PHP, push items to an array, then echo:
$count = 0;
while($count < 20) {
$numbers[$count] = rand(1, 50);
$count++;
}
echo json_encode($numbers);
This should produce something like:
[35,5,46,25,22,47,23,27,15,17,30,27,17,36,24,40,10,30,14,20]
Using JavaScript and AJAX, get the PHP page and parse using JSON.parse
Getting the PHP page and parsing (using jQuery):
var random = [];
$.get("random.php",function(data) {
random = JSON.parse(data);
}
Note: for the PHP script, you could also use array_push, but I've used the above just because we already have a while loop.