In my website plotting of Flot Bargraphs is done successfully.On the pageload I am inlcluding 2 bargraphs in div's,with one div style as none.I have a hyperlink on click of that The graph in the div with style none would be visible and the other graph should be invisible.
My code :
Javascript:
function abc()
{
alert("hi");
document.getElementById('none').style.display='none';
document.getElementById('two').style.display='block';
}
PHP Code:
<a onclick="abc()" href="#">click me</a>
<div id="one">
<?php include "graphs/newbar.php";?>
</div>
<div id="two" style="display:none">
<?php include "graphs/anotherbarquery.php";?>
</div>
when I click the hyperlink,the second graph is invisible.
anotherbarquery.php:
<?php require_once('../../Connections/finalkms.php'); ?>
<?php
mysql_select_db($database_finalkms, $finalkms);
$query_get_couunt = "SELECT EquipmentMainCatagory,count(EquipmentMainCatagory) FROM `assetinfo` group by `EquipmentMainCatagory` HAVING EquipmentMainCatagory <>''";
$get_couunt = mysql_query($query_get_couunt, $finalkms) or die(mysql_error());
$row_get_couunt = mysql_fetch_assoc($get_couunt);
$totalRows_get_couunt = mysql_num_rows($get_couunt);
$rows = array();
while($row_get_couunt = mysql_fetch_assoc($get_couunt))
{
$rows[] = array( $row_get_couunt['EquipmentMainCatagory'],(int)$row_get_couunt['count(EquipmentMainCatagory)']);
}
// convert data into JSON format
$jsonTable = json_encode($rows);
print_r($jsonTable);
?>
<script type="text/javascript" src="../../assets/plugins/jquery-1.8.1.min.js"></script>
<script type="text/javascript" src="../../assets/plugins/flot/jquery.flot.js"></script>
<script type="text/javascript" language="javascript" src="../../assets/plugins/flot/jquery.flot.axislabels.js"></script>
<script type="text/javascript" language="javascript" src="../../assets/plugins/flot/jquery.flot.orderBars.js"></script>
<script type="text/javascript" language="javascript" src="../../assets/plugins/flot/jquery.flot.tickrotatotor.min.js"></script>
<script type="text/javascript" language="javascript" src="../../assets/plugins/flot/jquery.flot.axislabels.js"></script>
<script type="text/javascript" language="javascript" src="../../assets/plugins/flot/jquery.flot.labelangle.min.js"></script>
<div id="placeholder1" style="width:900px;height:450px;"></div>
<script type="text/javascript">
//******* 2012 Average Temperature - BAR CHART
var data =<?php echo $jsonTable;?>;
//alert(data);
//var data = [["item1",277],["item2",635],["item3",133]];
var ticks = [];
for (var i = 0; i < data.length; i++) {
ticks.push([i,data[i][0]]);
data[i][0] = i;
}
alert(ticks);
//var data = [[0, 11],[1, 15],[2, 25],[3, 24],[4, 13],[5, 18]];
var dataset = [{ data: data, color: "#5482FF" }];
//var ticks = [[0, "London"], [1, "New York"], [2, "New Delhi"], [3, "Taipei"],[4, "Beijing"], [5, "Sydney"]];
var options = {
series: {
lineWidth: 5,
bars: {
show: true,
barWidth: 0.5,
align:"center"
}
},
xaxis: {
axisLabel: "EquipmentMainCatagory",
axisLabelUseCanvas: true,
axisLabelFontSizePixels: 12,
axisLabelFontFamily: 'Verdana, Arial',
axisLabelPadding: 10,
ticks: ticks,
//rotateTicks:90
labelAngle: 90
},
yaxis: {
axisLabel: "# Assets",
axisLabelUseCanvas: true,
axisLabelFontSizePixels: 12,
axisLabelFontFamily: 'Verdana, Arial',
axisLabelPadding: 3,
},
grid: {
hoverable: true,
borderWidth: 0,
backgroundColor: { colors: ["#ffffff", "#EDF5FF"] }
}
};
$(document).ready(function () {
$.plot($("#placeholder1"), dataset, options);
$("#placeholder1").UseTooltip();
});
var previousPoint = null, previousLabel = null;
$.fn.UseTooltip = function () {
$(this).bind("plothover", function (event, pos, item) {
if (item) {
if ((previousLabel != item.series.label) || (previousPoint != item.dataIndex)) {
previousPoint = item.dataIndex;
previousLabel = item.series.label;
$("#tooltip").remove();
var x = item.datapoint[0];
var y = item.datapoint[1];
var color = item.series.color;
//console.log(item.series.xaxis.ticks[x].label);
showTooltip(item.pageX,
item.pageY,
color,
// "<strong>" + y + "</strong>");
item.series.xaxis.ticks[x].label + " : <strong>" + y + "</strong>");
}
} else {
$("#tooltip").remove();
previousPoint = null;
}
});
};
function showTooltip(x, y, color, contents) {
$('<div id="tooltip">' + contents + '</div>').css({
position: 'absolute',
display: 'none',
top: y ,
left: x,
border: '2px solid ' + color,
padding: '3px',
'font-size': '9px',
'border-radius': '5px',
'background-color': '#fff',
'font-family': 'Verdana, Arial, Helvetica, Tahoma, sans-serif',
opacity: 0.9
}).appendTo("body").fadeIn(200);
}
</script>
<?php
mysql_free_result($get_couunt);
?>
newbar.php:
<?php
/* Your Database Name */
$dbname = 'dbname';
/* Your Database User Name and Passowrd */
$username = 'username';
$password = 'password';
try {
/* Establish the database connection */
$conn = new PDO("mysql:host=localhost;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$result = $conn->query("SELECT EquipmentMainCatagory,count(EquipmentMainCatagory) FROM `assetinfo` group by `EquipmentMainCatagory` HAVING EquipmentMainCatagory <>''");
$rows = array();
foreach($result as $r) {
$rows[] = array( $r['EquipmentMainCatagory'],(int)$r['count(EquipmentMainCatagory)']);
}
// convert data into JSON format
$jsonTable = json_encode($rows);
//print_r($jsonTable);
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
//mysql_close($conn);
$conn=null;
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Flot Bar Chart</title>
<!--<style type="text/css">
body { font-family: Verdana, Arial, sans-serif; font-size: 12px; }
h1 { width: 450px; margin: 0 auto; font-size: 12px; text-align: center; }
#placeholder { width: 450px; height: 200px; position: relative; margin: 0 auto; }
.legend table, .legend > div { height: 82px !important; opacity: 1 !important; right: -55px; top: 10px; width: 116px !important; }
.legend table { border: 1px solid #555; padding: 5px; }
#flot-tooltip { font-size: 12px; font-family: Verdana, Arial, sans-serif; position: absolute; display: none; border: 2px solid; padding: 2px; background-color: #FFF; opacity: 0.8; -moz-border-radius: 5px; -webkit-border-radius: 5px; -khtml-border-radius: 5px; border-radius: 5px; }
</style>-->
<!--[if lte IE 8]><script type="text/javascript" language="javascript" src="excanvas.min.js"></script><![endif]-->
<script type="text/javascript" src="assets/plugins/jquery-1.8.1.min.js"></script>
<script type="text/javascript" src="assets/plugins/flot/jquery.flot.js"></script>
<script src="assets/plugins/flot/jquery.flot.time.min.js" type="text/javascript"></script>
<script type="text/javascript" language="javascript" src="assets/plugins/flot/jquery.flot.axislabels.js"></script>
<script type="text/javascript" language="javascript" src="assets/plugins/flot/jquery.flot.orderBars.js"></script>
<script type="text/javascript" language="javascript" src="assets/plugins/flot/jquery.flot.tickrotatotor.min.js"></script>
<script type="text/javascript" language="javascript" src="assets/plugins/flot/jquery.flot.axislabels.js"></script>
<script type="text/javascript" language="javascript" src="assets/plugins/flot/jquery.flot.labelangle.min.js"></script>
<div id="placeholder" style="width:900px;height:450px;"></div>
<script type="text/javascript">
//******* 2012 Average Temperature - BAR CHART
var data =<?php echo $jsonTable;?>;
//alert(data);
//var data = [["item1",277],["item2",635],["item3",133]];
var ticks = [];
for (var i = 0; i < data.length; i++) {
ticks.push([i,data[i][0]]);
data[i][0] = i;
}
alert(ticks);
//var data = [[0, 11],[1, 15],[2, 25],[3, 24],[4, 13],[5, 18]];
var dataset = [{ data: data, color: "#5482FF" }];
//var ticks = [[0, "London"], [1, "New York"], [2, "New Delhi"], [3, "Taipei"],[4, "Beijing"], [5, "Sydney"]];
var options = {
series: {
lineWidth: 5,
bars: {
show: true,
barWidth: 0.5,
align:"center"
}
},
xaxis: {
axisLabel: "EquipmentMainCatagory",
axisLabelUseCanvas: true,
axisLabelFontSizePixels: 12,
axisLabelFontFamily: 'Verdana, Arial',
axisLabelPadding: 10,
ticks: ticks,
//rotateTicks:90
labelAngle: 90
},
yaxis: {
axisLabel: "# Assets",
axisLabelUseCanvas: true,
axisLabelFontSizePixels: 12,
axisLabelFontFamily: 'Verdana, Arial',
axisLabelPadding: 3,
},
grid: {
hoverable: true,
borderWidth: 0,
backgroundColor: { colors: ["#ffffff", "#EDF5FF"] }
}
};
$(document).ready(function () {
$.plot($("#placeholder"), dataset, options);
$("#placeholder").UseTooltip();
});
var previousPoint = null, previousLabel = null;
$.fn.UseTooltip = function () {
$(this).bind("plothover", function (event, pos, item) {
if (item) {
if ((previousLabel != item.series.label) || (previousPoint != item.dataIndex)) {
previousPoint = item.dataIndex;
previousLabel = item.series.label;
$("#tooltip").remove();
var x = item.datapoint[0];
var y = item.datapoint[1];
var color = item.series.color;
//console.log(item.series.xaxis.ticks[x].label);
showTooltip(item.pageX,
item.pageY,
color,
// "<strong>" + y + "</strong>");
item.series.xaxis.ticks[x].label + " : <strong>" + y + "</strong>");
}
} else {
$("#tooltip").remove();
previousPoint = null;
}
});
};
function showTooltip(x, y, color, contents) {
$('<div id="tooltip">' + contents + '</div>').css({
position: 'absolute',
display: 'none',
top: y ,
left: x,
border: '2px solid ' + color,
padding: '3px',
'font-size': '9px',
'border-radius': '5px',
'background-color': '#fff',
'font-family': 'Verdana, Arial, Helvetica, Tahoma, sans-serif',
opacity: 0.9
}).appendTo("body").fadeIn(200);
}
</script>
</head>
</html>
Flot needs a placeholder with a fixed size to draw the graph. As long as your div with id "two" is invisible, it has no size.
To fix this save your plot object to a variable:
var $plot2 = $.plot($("#placeholder"), dataset, options);
and draw it after showing the second div by adding this to your abc function:
$plot2.setupGrid();
$plot2.draw();
Instead of javascript please jquery . try it
$(function() {
$("a").click( function() {
$("#one").hide();
$("#two").show();
});
});
Related
If I use the below line of code:
return Plotly.newPlot(div1, data, layout, { displayModeBar: false, staticPlot: true }) ;
in the below plotly plot function and call plot(crypto("BTC")) in the online code editor I get
[object Promise]
and if I change the above line of code to:
CreateInputDiv();
return Plotly.newPlot(div1, data, layout, { displayModeBar: false, staticPlot: true }).Promise.resolve();
then I get the plot in the online code editor but then I also get the following error in the console.log
TypeError: Plotly.newPlot(...).Promise is undefined
I doubt I am doing thing correctly because I have a hard time understanding how async functions and promises work. The solution to my problem might be very simple or not. If the above code was working correctly I would not have to create a new input div because function parse() creates input and output divs and I would also not get an error in the console log. How can the error message in the console.log be solved?
JavaS.js and HTML below
// counts the number of input divs created
function increment() {
increment.n = increment.n || 0;
return ++increment.n;
}
// creates an input div
function CreateInputDiv() {
increment();
cc = increment.n;
//console.log("increment.n = " + cc);
input = document.createElement("div");
input.setAttribute("id", "input" + cc);
input.setAttribute("class", "input");
input.innerHTML = " ";
input.setAttribute("contenteditable", "true");
input.setAttribute("onkeypress", "parse(event, this)");
document.getElementById('calc').appendChild(input);
input.focus();
}
// creates an output div
function CreateOutputDiv() {
output = document.createElement("div");
output.setAttribute("id", "output" + cc);
output.setAttribute("class", "output");
output.setAttribute("tabindex", "0");
output.setAttribute("contenteditable", "false");
document.getElementById('calc').appendChild(output);
}
function parse(e1, e2) {
console.log("e2 = " + e2);
if (e1.keyCode == 13) { // keycode for enter
event.preventDefault();
var inId = e2.id;
console.log("inId = " + inId);
var outId = "output" + inId.substring(5);
console.log("outId = " + outId);
var inz = input.innerText;
// check if input contains a colon. Hides output if colon exist.
if (inz.indexOf(':') > -1) {
var inz = input.innerText.replace(/:/g, '');
console.log("input with colon = " + inz);
var outz = eval(inz);
console.log("hidden out = " + outz);
document.getElementById("count").value += '\n' + '\n' + eval(cc + 1);
CreateOutputDiv();
CreateInputDiv();
}
else { // no colon = display and revaluate input
if (document.getElementById(outId)) {
console.log("Already created");
inz = document.getElementById(inId).innerText;
console.log("inz = " + inz);
var outz = eval(inz);
console.log("outz = " + outz);
document.getElementById(outId).innerHTML = outz;
input.focus();
}
else { // no colon = display create new lines
document.getElementById("count").value += '\n' + '\n' + eval(cc + 1);
CreateOutputDiv();
// calculate and assign output value to output div
// console.log("input = " + inz);
var outz = eval(inz);
// console.log("out z = " + outz);
output.innerHTML = outz;
CreateInputDiv();
}
}
}
}
function T(UNIX_timestamp) {
var MyDate = new Date(UNIX_timestamp * 1000);
var MyDateString = MyDate.getFullYear() + '-' + ('0' + (MyDate.getMonth() + 1)).slice(-2) + '-' + ('0' + MyDate.getDate()).slice(-2);
return JSON.stringify(MyDateString);
}
function crypto(ticker) {
var ApiKey = "ddd85b386e1a7c889e468a4933f75f22f52b0755b747bdb637ab39c88a3bc19b";
var urlA = "https://min-api.cryptocompare.com/data/histoday?fsym=" + ticker + "&tsym=USD&limit=1000&api_key=" + ApiKey;
var result = null;
$.ajax({
url: urlA,
async: false, // makes a synchrously data call to cryptocompare
dataType: "json",
success: function (data) { result = data; }
});
var y = result.Data;
var D1 = [];
var D2 = [];
for (var i = 0; i < y.length; i++) {
D1.push(T(y[i].time));
D2.push(y[i].close);
}
console.log(D2);
return D2;
}
// plots a give data array
function plot(z) {
var yy = z;
var xx = [];
for (var i = 0; i <= yy.length; i++) {
xx[i] = JSON.stringify(i);
}
var data = [{
x: xx,
y: yy,
type: 'scatter',
line: { color: 'green', width: 2 }
}];
var layout =
{
width: 700,
height: 300,
paper_bgcolor: 'lightblue',
plot_bgcolor: 'lightblue',
margin: { l: 60, b: 60, r: 20, t: 20 },
title: "",
xaxis: {
title: 'x-axis', titlefont: {
family: 'Courier New, monospace', size: 18,
color: 'black'
}
},
yaxis: {
title: 'y-axis', titlefont: { family: 'Courier New, monospace', size: 18, color: 'black' },
width: 1000, height: 380,
xaxis: {
tickfont: { size: 12, color: 'black' }, showgrid: true, tickmode: "linear",
gridcolor: 'black', linecolor: 'black'
},
yaxis: {
tickfont: { size: 12, color: 'black' }, showgrid: true,
gridcolor: 'black', linecolor: 'black'
}
}
};
cc = increment.n;
div1 = 'output' + cc;
// return Plotly.newPlot(div1, data, layout, { displayModeBar: false, staticPlot: true }) ; // object promise
CreateInputDiv();
return Plotly.newPlot(div1, data, layout, { displayModeBar: false, staticPlot: true }).Promise.resolve();
}
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="JavaS.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
<meta charset="utf-8" />
<style>
.input {
background-color: lightgreen;
width: 980px;
border: none;
font-size: 16px;
resize: none;
}
.output {
background-color: lightblue;
width: 980px;
line-height: 20px;
border: none;
font-size: 16px;
resize: none;
overflow-wrap: break-word;
}
#count {
background-color: lightblue;
color: black;
width: 25px;
height: 500px;
font-size: 17px;
resize: none;
border: none;
}
#calc {
background-color: lightblue;
vertical-align: top;
border: none;
overflow: hidden;
}
</style>
</head>
<body bgcolor="grey">
<table align="center" width="1000px" height="500px" bgcolor="lightblue" overflow="hidden">
<tr>
<td><textarea id="count" disabled>1 </textarea> </td>
<td id="calc"></td>
</tr>
</table>
<script> CreateInputDiv(); </script>
</body>
</html>
A working solution to the above plotting problem can be found below. Replace
the line
return Plotly.newPlot(div1, data, layout, { displayModeBar: false, staticPlot: true }) ; // object promise
in the plot function with
setTimeout(function(){Plotly.newPlot(div1, data, layout, { displayModeBar: false, staticPlot: true });}, 10);
return "";
That will give you the plotly.js plot in the web editor without getting [object Promise] or any error messages in the console log.
I am looking to add a small label near each of the countries name that will show it's population (e.g. Brazil [200,0000] ). Is there a way to do this with Google maps JS api?
My current code for map initialization:
// Define options
var options = {
center: {
lat: 48.1250223,
lng: 4.1264001
},
zoom: 3
};
// Init map
map = new google.maps.Map( $container.get(0), options );
Any help would be appreciated!
Data for the population is not available in the Google Maps API v3.
You will need to import data from an external source.
You can check this example from Google API https://developers.google.com/maps/documentation/javascript/combining-data
Full code
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<title>Mashups with google.maps.Data</title>
<style>
html, body, #map { height: 100%; margin: 0; padding: 0; overflow: hidden; }
.nicebox {
position: absolute;
text-align: center;
font-family: "Roboto", "Arial", sans-serif;
font-size: 13px;
z-index: 5;
box-shadow: 0 4px 6px -4px #333;
padding: 5px 10px;
background: rgb(255,255,255);
background: linear-gradient(to bottom,rgba(255,255,255,1) 0%,rgba(245,245,245,1) 100%);
border: rgb(229, 229, 229) 1px solid;
}
#controls {
top: 10px;
left: 110px;
width: 360px;
height: 45px;
}
#data-box {
top: 10px;
left: 500px;
height: 45px;
line-height: 45px;
display: none;
}
#census-variable {
width: 360px;
height: 20px;
}
#legend { display: flex; display: -webkit-box; padding-top: 7px }
.color-key {
background: linear-gradient(to right,
hsl(5, 69%, 54%) 0%,
hsl(29, 71%, 51%) 17%,
hsl(54, 74%, 47%) 33%,
hsl(78, 76%, 44%) 50%,
hsl(102, 78%, 41%) 67%,
hsl(127, 81%, 37%) 83%,
hsl(151, 83%, 34%) 100%);
flex: 1;
-webkit-box-flex: 1;
margin: 0 5px;
text-align: left;
font-size: 1.0em;
line-height: 1.0em;
}
#data-value { font-size: 2.0em; font-weight: bold }
#data-label { font-size: 2.0em; font-weight: normal; padding-right: 10px; }
#data-label:after { content: ':' }
#data-caret { margin-left: -5px; display: none; font-size: 14px; width: 14px}
</style>
</head>
<body>
<div id="controls" class="nicebox">
<div>
<select id="census-variable">
<option value="https://storage.googleapis.com/mapsdevsite/json/DP02_0066PE">Percent of population over 25 that completed high
school</option>
<option value="https://storage.googleapis.com/mapsdevsite/json/DP05_0017E">Median age</option>
<option value="https://storage.googleapis.com/mapsdevsite/json/DP05_0001E">Total population</option>
<option value="https://storage.googleapis.com/mapsdevsite/json/DP02_0016E">Average family size</option>
<option value="https://storage.googleapis.com/mapsdevsite/json/DP03_0088E">Per-capita income</option>
</select>
</div>
<div id="legend">
<div id="census-min">min</div>
<div class="color-key"><span id="data-caret">◆</span></div>
<div id="census-max">max</div>
</div>
</div>
<div id="data-box" class="nicebox">
<label id="data-label" for="data-value"></label>
<span id="data-value"></span>
</div>
<div id="map"></div>
<script>
var mapStyle = [{
'stylers': [{'visibility': 'off'}]
}, {
'featureType': 'landscape',
'elementType': 'geometry',
'stylers': [{'visibility': 'on'}, {'color': '#fcfcfc'}]
}, {
'featureType': 'water',
'elementType': 'geometry',
'stylers': [{'visibility': 'on'}, {'color': '#bfd4ff'}]
}];
var map;
var censusMin = Number.MAX_VALUE, censusMax = -Number.MAX_VALUE;
function initMap() {
// load the map
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 40, lng: -100},
zoom: 4,
styles: mapStyle
});
// set up the style rules and events for google.maps.Data
map.data.setStyle(styleFeature);
map.data.addListener('mouseover', mouseInToRegion);
map.data.addListener('mouseout', mouseOutOfRegion);
// wire up the button
var selectBox = document.getElementById('census-variable');
google.maps.event.addDomListener(selectBox, 'change', function() {
clearCensusData();
loadCensusData(selectBox.options[selectBox.selectedIndex].value);
});
// state polygons only need to be loaded once, do them now
loadMapShapes();
}
/** Loads the state boundary polygons from a GeoJSON source. */
function loadMapShapes() {
// load US state outline polygons from a GeoJson file
map.data.loadGeoJson('https://storage.googleapis.com/mapsdevsite/json/states.js', { idPropertyName: 'STATE' });
// wait for the request to complete by listening for the first feature to be
// added
google.maps.event.addListenerOnce(map.data, 'addfeature', function() {
google.maps.event.trigger(document.getElementById('census-variable'),
'change');
});
}
/**
* Loads the census data from a simulated API call to the US Census API.
*
* #param {string} variable
*/
function loadCensusData(variable) {
// load the requested variable from the census API (using local copies)
var xhr = new XMLHttpRequest();
xhr.open('GET', variable + '.json');
xhr.onload = function() {
var censusData = JSON.parse(xhr.responseText);
censusData.shift(); // the first row contains column names
censusData.forEach(function(row) {
var censusVariable = parseFloat(row[0]);
var stateId = row[1];
// keep track of min and max values
if (censusVariable < censusMin) {
censusMin = censusVariable;
}
if (censusVariable > censusMax) {
censusMax = censusVariable;
}
// update the existing row with the new data
map.data
.getFeatureById(stateId)
.setProperty('census_variable', censusVariable);
});
// update and display the legend
document.getElementById('census-min').textContent =
censusMin.toLocaleString();
document.getElementById('census-max').textContent =
censusMax.toLocaleString();
};
xhr.send();
}
/** Removes census data from each shape on the map and resets the UI. */
function clearCensusData() {
censusMin = Number.MAX_VALUE;
censusMax = -Number.MAX_VALUE;
map.data.forEach(function(row) {
row.setProperty('census_variable', undefined);
});
document.getElementById('data-box').style.display = 'none';
document.getElementById('data-caret').style.display = 'none';
}
/**
* Applies a gradient style based on the 'census_variable' column.
* This is the callback passed to data.setStyle() and is called for each row in
* the data set. Check out the docs for Data.StylingFunction.
*
* #param {google.maps.Data.Feature} feature
*/
function styleFeature(feature) {
var low = [5, 69, 54]; // color of smallest datum
var high = [151, 83, 34]; // color of largest datum
// delta represents where the value sits between the min and max
var delta = (feature.getProperty('census_variable') - censusMin) /
(censusMax - censusMin);
var color = [];
for (var i = 0; i < 3; i++) {
// calculate an integer color based on the delta
color[i] = (high[i] - low[i]) * delta + low[i];
}
// determine whether to show this shape or not
var showRow = true;
if (feature.getProperty('census_variable') == null ||
isNaN(feature.getProperty('census_variable'))) {
showRow = false;
}
var outlineWeight = 0.5, zIndex = 1;
if (feature.getProperty('state') === 'hover') {
outlineWeight = zIndex = 2;
}
return {
strokeWeight: outlineWeight,
strokeColor: '#fff',
zIndex: zIndex,
fillColor: 'hsl(' + color[0] + ',' + color[1] + '%,' + color[2] + '%)',
fillOpacity: 0.75,
visible: showRow
};
}
/**
* Responds to the mouse-in event on a map shape (state).
*
* #param {?google.maps.MouseEvent} e
*/
function mouseInToRegion(e) {
// set the hover state so the setStyle function can change the border
e.feature.setProperty('state', 'hover');
var percent = (e.feature.getProperty('census_variable') - censusMin) /
(censusMax - censusMin) * 100;
// update the label
document.getElementById('data-label').textContent =
e.feature.getProperty('NAME');
document.getElementById('data-value').textContent =
e.feature.getProperty('census_variable').toLocaleString();
document.getElementById('data-box').style.display = 'block';
document.getElementById('data-caret').style.display = 'block';
document.getElementById('data-caret').style.paddingLeft = percent + '%';
}
/**
* Responds to the mouse-out event on a map shape (state).
*
* #param {?google.maps.MouseEvent} e
*/
function mouseOutOfRegion(e) {
// reset the hover state, returning the border to normal
e.feature.setProperty('state', 'normal');
}
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?callback=initMap">
</script>
</body>
</html>
You could use the label of a marker without displaying the marker. Attached a short example. Mmmmh, or use the country flag as icon and show the label over it.
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Marker with Label</title>
<style>
#map {height: 100%;}
html, body {height: 100%;}
</style>
</head>
<body>
<div id="map"></div>
<script>
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: {lat: 48.1, lng: 4.1},
mapTypeId: 'terrain'
});
//set the text as marker label without displayinge the marker
var m = new google.maps.Marker({
position: {lat: 48.1, lng: 4.1},
label: {
color: 'purple',
fontWeight: 'bold',
text: 'people: 67 Mio',
},
icon: {
url: 'none_marker.png',
anchor: new google.maps.Point(10, -25),
},
map: map
});
}
</script>
<script async defer src="https://maps.googleapis.com/maps/api/js?callback=initMap"></script>
</body>
</html>
trying to compare two sensor readings - the data is coming from thingspeak. I've got the zoom part working, but for some reason I cant get the scroll to work.
<script type="text/javascript">
// variables for the first series
var series_1_channel_id = 43330;
var series_1_field_number = 4;
var series_1_read_api_key = '7ZPHNX2SXPM0CA1K';
var series_1_results = 480;
var series_1_color = '#d62020';
var series_1_name = 'Zims Sensor';
// variables for the second series
var series_2_channel_id = 45473;
var series_2_field_number = 2;
var series_2_read_api_key = 'N12T3CWQB5IWJAU9';
var series_2_results = 480;
var series_2_color = '#00aaff';
var series_2_name = 'UVM30a';
// chart title
var chart_title = 'UV Sensors Zim / UVM30A';
// y axis title
var y_axis_title = 'UV Index';
// user's timezone offset
var my_offset = new Date().getTimezoneOffset();
// chart variable
var my_chart;
// when the document is ready
$(document).on('ready', function() {
// add a blank chart
addChart();
// add the first series
addSeries(series_1_channel_id, series_1_field_number, series_1_read_api_key, series_1_results, series_1_color, series_1_name);
// add the second series
addSeries(series_2_channel_id, series_2_field_number, series_2_read_api_key, series_2_results, series_2_color, series_2_name);
});
// add the base chart
function addChart() {
// variable for the local date in milliseconds
var localDate;
// specify the chart options
var chartOptions = {
chart: {
renderTo: 'chart-container',
defaultSeriesType: 'line',
zoomType: 'x', // added here
backgroundColor: '#ffffff',
events: { }
},
title: { text: chart_title },
plotOptions: {
series: {
marker: { radius: 3 },
animation: true,
step: false,
borderWidth: 0,
turboThreshold: 0
}
},
tooltip: {
// reformat the tooltips so that local times are displayed
formatter: function() {
var d = new Date(this.x + (my_offset*60000));
var n = (this.point.name === undefined) ? '' : '<br>' + this.point.name;
return this.series.name + ':<b>' + this.y + '</b>' + n + '<br>' + d.toDateString() + '<br>' + d.toTimeString().replace(/\(.*\)/, "");
}
},
xAxis: {
type: 'datetime',
scrollbar: {
enabled: true,
barBackgroundColor: 'gray',
barBorderRadius: 7,
barBorderWidth: 0,
buttonBackgroundColor: 'gray',
buttonBorderWidth: 0,
buttonArrowColor: 'yellow',
buttonBorderRadius: 7,
rifleColor: 'yellow',
trackBackgroundColor: 'white',
trackBorderWidth: 1,
trackBorderColor: 'silver',
trackBorderRadius: 7
},
title: { text: 'Date' }
},
yAxis: { title: { text: y_axis_title } },
exporting: { enabled: true },
legend: { enabled: true },
credits: {
text: 'ThingSpeak.com',
href: 'https://thingspeak.com/',
style: { color: '#D62020' }
}
};
// draw the chart
my_chart = new Highcharts.Chart(chartOptions);
}
// add a series to the chart
function addSeries(channel_id, field_number, api_key, results, color, name) {
var field_name = 'field' + field_number;
// get the data with a webservice call
$.getJSON('https://api.thingspeak.com/channels/' + channel_id + '/fields/' + field_number + '.json?offset=0&round=2&results=' + results + '&api_key=' + api_key, function(data) {
// blank array for holding chart data
var chart_data = [];
// iterate through each feed
$.each(data.feeds, function() {
var point = new Highcharts.Point();
// set the proper values
var value = this[field_name];
point.x = getChartDate(this.created_at);
point.y = parseFloat(value);
// add location if possible
if (this.location) { point.name = this.location; }
// if a numerical value exists add it
if (!isNaN(parseInt(value))) { chart_data.push(point); }
});
// add the chart data
my_chart.addSeries({ data: chart_data, name: data.channel[field_name], color: color });
});
}
// converts date format from JSON
function getChartDate(d) {
// offset in minutes is converted to milliseconds and subtracted so that chart's x-axis is correct
return Date.parse(d) - (my_offset * 60000);
}
</script>
<style type="text/css">
body { background-color: white; height: 100%; margin: 0; padding: 0; }
#chart-container { width: 800px; height: 400px; display: block; position:absolute; bottom:0; top:0; left:0; right:0; margin: 5px 15px 15px 0; overflow: hidden; }
</style>
<!DOCTYPE html>
<html style="height: 100%;">
<head>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript" src="//code.highcharts.com/stock/highstock.js"></script>
<script type="text/javascript" src="//thingspeak.com/exporting.js"></script>
</head>
<body>
<div id="chart-container">
// <img alt="Ajax loader" src="//thingspeak.com/assets/ajax-loader.gif" style="position: absolute; margin: auto; top: 0; left: 0; right: 0; bottom: 0;" />
</div>
</body>
</html>
I would also like to get the chart updating automatically, so any help on that score would also be appreciated. The final issue I am having is trying to get the legend to display the sensor names properly: UV Index (red) should read "Zims Sensor" and UV Index (blue) should read "UVM30A"
I am using jQuery flot. I can't seem to explain the bug well. But by the looks of it, the hover does not work when the user moves down to the page: Here's the video:
http://screencast.com/t/qZIjJ8jsi
Notice when i'm on top of my page the hover is working, but when I'll go down the page, then the hover on the points won't work.
My page is responsive(not sure if that's related, but just saying). Looks like this is a CSS problem. So here's my code:
var graphData = decodeURIComponent(jQuery("#graphData").val());
graphData = jQuery.parseJSON(graphData);
var visitors = new Array();
var totalVisitors = 0;
jQuery.each(graphData,function(index,value){
visitors[index] = [value[0],value[1]];
totalVisitors = totalVisitors + parseInt(value[1]);
});
jQuery(".date-figures").text(totalVisitors);
var visitor = $("#activeUsers"),
data_visitor = [{
data: visitors,
color: '#058DC7'
}],
options_lines = {
series: {
lines: {
show: true,
fill: true,
fillColor: "#E5F3F9",
color:"#058DC7",
},
points: {
show: true
},
hoverable: true
},
grid: {
backgroundColor: '#FFFFFF',
borderWidth: 0,
borderColor: '#CDCDCD',
hoverable: true
},
legend: {
show: true
},
xaxis: {
mode: "time",
},
yaxis: {
show:true
},
};
$.plot(visitor, data_visitor, options_lines);
function showTooltip(x, y, contents) {
$('<div id="tooltip">' + contents + '</div>').css({
position: 'absolute',
display: 'none',
top: y + 5,
left: x + 5,
padding: '2px 10px 2px 10px',
opacity: 0.8,
}).appendTo("body").fadeIn(200);
}
var previousPoint = null;
$('#visitor-stat, #order-stat, #user-stat,#activeUsers').bind("plothover", function (event, pos, item) {
if (item) {
if (previousPoint != item.dataIndex) {
previousPoint = item.dataIndex;
$("#tooltip").remove();
var d = new Date(item.datapoint[0]);
var day = parseDay(d.getDay());
var date = d.getDate();
var month = parseMonth(d.getMonth());
var year = d.getFullYear();
var tooltipWording = "<b>"+day+", "+month+" "+date+", "+year+"</b>";
tooltipWording += "<ul>";
tooltipWording += "<li>Visits: <b>"+item.datapoint[1]+"</b></li>";
tooltipWording += "</ul>";
showTooltip(item.pageX, item.pageY, tooltipWording);
}
}
else {
$("#tooltip").remove();
previousPoint = null;
}
});
});
What seems to be problem here? Your help will be greatly appreciated! Thanks! :)
I am attempting to add this example to a content management system. The mapping feature will then be modified to meet our needs once it works in all 4 browsers. No i cant give you any more info on the CMS as it is private. Please dont mention some of the code using the character entities. ex < is & lt;
Ie8 claims L is not defined.
Chrome claims uncaught reference error L is not defined.
However FF21 and Safari 5.1.7 have no issues displaying this example http://leafletjs.com/examples/choropleth.html
Why is it when the example is inside the CMS some browsers wont display the map. Is this poor coding from the demo? Is this a difference of how the scripts are loaded. What is the best way to go about troubleshooting this?
The doctype is frameset because of the CMS.
<html>
<head>
<title>Leaflet Layers Control Example</title>
<link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.5.1/leaflet.css" />
<!--[if lte IE 8]><link rel="stylesheet" href="http://leafletjs.com/examples/dist/leaflet.ie.css" /></link><![endif]-->
<style>
#map {
width: 800px;
height: 500px;
}
.info {
padding: 6px 8px;
font: 14px/16px Arial, Helvetica, sans-serif;
background: white;
background: rgba(255,255,255,0.8);
box-shadow: 0 0 15px rgba(0,0,0,0.2);
border-radius: 5px;
}
.info h4 {
margin: 0 0 5px;
color: #777;
}
.legend {
text-align: left;
line-height: 18px;
color: #555;
}
.legend i {
width: 18px;
height: 18px;
float: left;
margin-right: 8px;
opacity: 0.7;
}
</style>
</head>
<body>
<div id="map"></div>
<script src="http://cdn.leafletjs.com/leaflet-0.5.1/leaflet.js"></script>
<script type="text/javascript" src="http://leafletjs.com/examples/us-states.js"></script>
<script type="text/javascript">
var map = L.map('map').setView([37.8, -96], 4);
var cloudmade = L.tileLayer('http://{s}.tile.cloudmade.com/{key}/{styleId}/256/{z}/{x}/{y}.png', {
attribution: 'Map data © 2011 OpenStreetMap contributors, Imagery © 2011 CloudMade',
key: 'BC9A493B41014CAABB98F0471D759707',
styleId: 22677
}).addTo(map);
// control that shows state info on hover
var info = L.control();
info.onAdd = function (map) {
this._div = L.DomUtil.create('div', 'info');
this.update();
return this._div;
};
info.update = function (props) {
this._div.innerHTML = '<h4>US Population Density</h4>' + (props ?
'<b>' + props.name + '</b><br />' + props.density + ' people / mi<sup>2</sup>'
: 'Hover over a state');
};
info.addTo(map);
// get color depending on population density value
function getColor(d) {
return d > 1000 ? '#800026' :
d > 500 ? '#BD0026' :
d > 200 ? '#E31A1C' :
d > 100 ? '#FC4E2A' :
d > 50 ? '#FD8D3C' :
d > 20 ? '#FEB24C' :
d > 10 ? '#FED976' :
'#FFEDA0';
}
function style(feature) {
return {
weight: 2,
opacity: 1,
color: 'white',
dashArray: '3',
fillOpacity: 0.7,
fillColor: getColor(feature.properties.density)
};
}
function highlightFeature(e) {
var layer = e.target;
layer.setStyle({
weight: 5,
color: '#666',
dashArray: '',
fillOpacity: 0.7
});
if (!L.Browser.ie && !L.Browser.opera) {
layer.bringToFront();
}
info.update(layer.feature.properties);
}
var geojson;
function resetHighlight(e) {
geojson.resetStyle(e.target);
info.update();
}
function zoomToFeature(e) {
map.fitBounds(e.target.getBounds());
}
function onEachFeature(feature, layer) {
layer.on({
mouseover: highlightFeature,
mouseout: resetHighlight,
click: zoomToFeature
});
}
geojson = L.geoJson(statesData, {
style: style,
onEachFeature: onEachFeature
}).addTo(map);
map.attributionControl.addAttribution('Population data © US Census Bureau');
var legend = L.control({position: 'bottomright'});
legend.onAdd = function (map) {
var div = L.DomUtil.create('div', 'info legend'),
grades = [0, 10, 20, 50, 100, 200, 500, 1000],
labels = [],
from, to;
for (var i = 0; i < grades.length; i++) {
from = grades[i];
to = grades[i + 1];
labels.push(
'<i style="background:' + getColor(from + 1) + '"></i> ' +
from + (to ? '–' + to : '+'));
}
div.innerHTML = labels.join('<br />');
return div;
};
legend.addTo(map);
</script>
</body>
</html>
The CMS is probably running in a secure zone (SSL / https://), then the unsecure Leaflet .js and .css resources (http://) won't be loaded in most browsers, and you get some 'L is undefined' error message. There are some browsers that do load unsecure elements.
Try to include the Leaflet resources from a https:// location.
Please dont mention some of the code using the character entities. ex < is & lt;
And yet your code works fine when I suppress them.
<html>
<head>
<title>Leaflet Layers Control Example</title>
<link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.5.1/leaflet.css" />
<!--[if lte IE 8]><link rel="stylesheet" href="http://leafletjs.com/examples/dist/leaflet.ie.css" /></link><![endif]-->
<style>
#map {
width: 800px;
height: 500px;
}
.info {
padding: 6px 8px;
font: 14px/16px Arial, Helvetica, sans-serif;
background: white;
background: rgba(255,255,255,0.8);
box-shadow: 0 0 15px rgba(0,0,0,0.2);
border-radius: 5px;
}
.info h4 {
margin: 0 0 5px;
color: #777;
}
.legend {
text-align: left;
line-height: 18px;
color: #555;
}
.legend i {
width: 18px;
height: 18px;
float: left;
margin-right: 8px;
opacity: 0.7;
}
</style>
</head>
<body>
<div id="map"></div>
<script src="http://cdn.leafletjs.com/leaflet-0.5.1/leaflet.js"></script>
<script type="text/javascript" src="http://leafletjs.com/examples/us-states.js"></script>
<script type="text/javascript">
var map = L.map('map').setView([37.8, -96], 4);
var cloudmade = L.tileLayer('http://{s}.tile.cloudmade.com/{key}/{styleId}/256/{z}/{x}/{y}.png', {
attribution: 'Map data © 2011 OpenStreetMap contributors, Imagery © 2011 CloudMade',
key: 'BC9A493B41014CAABB98F0471D759707',
styleId: 22677
}).addTo(map);
// control that shows state info on hover
var info = L.control();
info.onAdd = function (map) {
this._div = L.DomUtil.create('div', 'info');
this.update();
return this._div;
};
info.update = function (props) {
this._div.innerHTML = '<h4>US Population Density</h4>' + (props ?
'<b>' + props.name + '</b><br />' + props.density + ' people / mi<sup>2</sup>'
: 'Hover over a state');
};
info.addTo(map);
// get color depending on population density value
function getColor(d) {
return d > 1000 ? '#800026' :
d > 500 ? '#BD0026' :
d > 200 ? '#E31A1C' :
d > 100 ? '#FC4E2A' :
d > 50 ? '#FD8D3C' :
d > 20 ? '#FEB24C' :
d > 10 ? '#FED976' :
'#FFEDA0';
}
function style(feature) {
return {
weight: 2,
opacity: 1,
color: 'white',
dashArray: '3',
fillOpacity: 0.7,
fillColor: getColor(feature.properties.density)
};
}
function highlightFeature(e) {
var layer = e.target;
layer.setStyle({
weight: 5,
color: '#666',
dashArray: '',
fillOpacity: 0.7
});
if (!L.Browser.ie && !L.Browser.opera) {
layer.bringToFront();
}
info.update(layer.feature.properties);
}
var geojson;
function resetHighlight(e) {
geojson.resetStyle(e.target);
info.update();
}
function zoomToFeature(e) {
map.fitBounds(e.target.getBounds());
}
function onEachFeature(feature, layer) {
layer.on({
mouseover: highlightFeature,
mouseout: resetHighlight,
click: zoomToFeature
});
}
geojson = L.geoJson(statesData, {
style: style,
onEachFeature: onEachFeature
}).addTo(map);
map.attributionControl.addAttribution('Population data © US Census Bureau');
var legend = L.control({position: 'bottomright'});
legend.onAdd = function (map) {
var div = L.DomUtil.create('div', 'info legend'),
grades = [0, 10, 20, 50, 100, 200, 500, 1000],
labels = [],
from, to;
for (var i = 0; i < grades.length; i++) {
from = grades[i];
to = grades[i + 1];
labels.push(
'<i style="background:' + getColor(from + 1) + '"></i> ' +
from + (to ? '–' + to : '+'));
}
div.innerHTML = labels.join('<br />');
return div;
};
legend.addTo(map);
</script>
</body>
</html>
Works fine on chrome. Try it yourself!