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!
Related
I have a tracking map using Leaflet.js and I want to display:
a) current speed,
b) average speed and
c) total distance traveled.
How would I do this? https://jsfiddle.net/chovy/rfvtwed5/
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<script src="https://cdn.jsdelivr.net/npm/#turf/turf#6/turf.min.js"></script>
<link
rel="stylesheet"
href="https://unpkg.com/leaflet#1.7.1/dist/leaflet.css"
integrity="sha512-xodZBNTC5n17Xt2atTPuE1HxjVMSvLVW9ocqUKLsCC5CXdbqCmblAshOMAS6/keqq/sMZMZ19scR4PsZChSR7A=="
crossorigin=""
/>
<link
rel="stylesheet"
href="https://unpkg.com/leaflet-control-geocoder/dist/Control.Geocoder.css"
/>
<style>
html {
font-size: 62.5%;
}
body {
margin: 0;
padding: 0;
font-size: 1.6rem;
font-family: sans-serif;
width: 95vw;
height: 90vh;
margin: 0 auto;
}
header {
padding: 1rem 0;
}
#map {
width: 100%;
height: 100%;
}
.marker img {
width: 3rem;
}
.marker span {
display: block;
background: #fff;
width: 10rem;
padding: 1rem;
border-radius: 0.4rem;
border: 1px solid black;
}
#media (max-width: 481px) {
/* portrait e-readers (Nook/Kindle), smaller tablets # 600 or # 640 wide. */
#status {
display: block;
}
}
</style>
</head>
<body>
<header>
<button id="start">start</button>
<button id="stop">stop</button>
<button id="marker">add marker</button>
<button id="export">export</button>
<span id="status"></span>
</header>
<div id="map"></div>
<script
src="https://unpkg.com/leaflet#1.7.1/dist/leaflet.js"
integrity="sha512-XQoYMqMTK8LvdxXYG3nZ448hOEQiglfqkJs1NOQV44cWnUrBc8PkAOcXy20w0vlaXaVUearIOBhiXZ5V3ynxwA=="
crossorigin=""
></script>
<script src="https://unpkg.com/leaflet-control-geocoder/dist/Control.Geocoder.js"></script>
<script>
const exportButton = document.getElementById("export");
let intv;
const status = document.getElementById("status");
var map = L.map("map", {
center: [9.082, 8.6753],
zoom: 8,
});
var osm = L.tileLayer(
"https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png",
{
attribution:
'© SkateSpot, Inc.',
}
).addTo(map);
L.Control.geocoder().addTo(map);
if (!navigator.geolocation) {
console.log("Your browser doesn't support geolocation feature!");
}
const trackingPath = [];
const polyline = L.polyline([], {
color: "red",
weight: 3,
className: "path",
}).addTo(map);
function start() {
navigator.geolocation.getCurrentPosition(getPosition);
intv = setInterval(() => {
navigator.geolocation.getCurrentPosition(getPosition);
}, 1000);
}
function getPosition(position) {
// console.log(position)
const { latitude, longitude, accuracy } = position.coords;
const pos = [latitude, longitude];
//const pos = turf.randomPosition([49, 23, 43, 20])
trackingPath.push(pos);
polyline.addLatLng(pos);
map.fitBounds(polyline.getBounds());
console.log(
"Your coordinate is: Lat: " +
latitude +
" Long: " +
longitude +
" Accuracy: " +
accuracy
);
}
exportButton.addEventListener("click", function () {
console.log("trackingPath", trackingPath);
save("data.txt", JSON.stringify(trackingPath));
});
function save(filename, data) {
const blob = new Blob([data], { type: "text/csv" });
if (window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveBlob(blob, filename);
} else {
const elem = window.document.createElement("a");
elem.href = window.URL.createObjectURL(blob);
elem.download = filename;
document.body.appendChild(elem);
elem.click();
document.body.removeChild(elem);
}
}
function addMarker(e) {
e.preventDefault();
console.log("add marker");
status.innerText = "adding marker...";
navigator.geolocation.getCurrentPosition((position) => {
const { latitude, longitude, accuracy } = position.coords;
const pos = [latitude, longitude];
var marker = L.marker(pos, {
icon: new L.DivIcon({
className: "marker",
html: `<img src="/marker.svg" alt="" />
<span contenteditable>click to edit</span>`,
}),
}).addTo(map);
var Overlaymaps = {
Marker: marker,
};
L.control.layers(Overlaymaps).addTo(map);
status.innerText = `Marker added at ${pos.join(", ")}`;
});
}
function startTracking(e) {
status.innerText = "Started tracking...";
e.preventDefault();
start();
}
function stopTracking(e) {
status.innerText = "Stopped tracking.";
e.preventDefault();
clearInterval(intv);
}
document.getElementById("start").addEventListener("click", startTracking);
document.getElementById("stop").addEventListener("click", stopTracking);
document.getElementById("marker").addEventListener("click", addMarker);
</script>
</body>
</html>
I'm just guessing here but I think for "current speed" I'd have to take the last 2 readings (every 1 second) and calculate distance and time passed to get speed. as for average speed I'd just take the first and the last data points and do the same.
Total distance I'd have to add up all the data points I assume since a path is not always a straight line.
I just have no idea how to do all this using gps coordinates.
Leaflet provides a useful latlngA.distanceTo(latlngB) method to convert a pair of GPS coordinates into actual distance:
Returns the distance (in meters) to the given LatLng calculated using the Spherical Law of Cosines.
With this, you can do something like:
let totalElapsedTime = 0;
let totalDistance = 0;
let previousTime;
let previousLatLng;
function getPosition(position) {
const currentTime = new Date();
const currentLatLng = L.latLng(
position.coords.latitude,
position.coords.longitude
);
// Skip first point (no computation is possible)
if (previousTime && previousLatLng) {
const elapsedTime = (currentTime.getTime() - previousTime.getTime()) / 1000; // In seconds
const distance = previousLatLng.distanceTo(currentLatLng);
const currentSpeed = distance / elapsedTime; // In meters / second
totalElapsedTime += elapsedTime;
totalDistance += distance;
const averageSpeed = totalDistance / totalElapsedTime; // In meters / second
}
// Record time and position for next computation
previousTime = currentTime;
previousLatLng = currentLatLng;
// Graphic stuff...
}
Note: for average speed you also need total travelled distance to account for non straight line path, unless you want to compute "flying distance" irrespective of actual path, which can therefore decrease back to 0 in case the path becomes a loop back to starting point.
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.
here is my script, I'm currently having a bad time with leaflet, it is taking substantial amounts of time to load my markers yet I'm only playing with up to 200-500 at a time and can't seem to find the reason why.
Markers are pulled from an API and stored into an array then plotted onto the map upon clicking a section on the map, see for yourself on the live demo, it works fine until loading markers then it starts to lag a lot when zooming
If anybody has a solution for me it would be much appreciated as I intend to have a lot more markers than it is currently pulling.
var postcode;
var police_api_dates = [
"&date=2017-03",
];
var completed_requests = 0;
var police_api_base_url = "https://data.police.uk/api/crimes-street/all-crime?poly=";
var crimes = [];
var count = 0;
var mymap = L.map('map').setView([53.7983587, -1.6191674], 11);
mymap.createPane('labels');
mymap.getPane('labels').style.zIndex = 650;
mymap.getPane('labels').style.pointerEvents = 'none';
var positron = L.tileLayer('http://{s}.basemaps.cartocdn.com/light_nolabels/{z}/{x}/{y}.png', {
attribution: '©OpenStreetMap, ©CartoDB'
}).addTo(mymap);
var positronLabels = L.tileLayer('http://{s}.basemaps.cartocdn.com/light_only_labels/{z}/{x}/{y}.png', {
attribution: '©OpenStreetMap, ©CartoDB',
pane: 'labels'
}).addTo(mymap);
L.tileLayer('https://api.mapbox.com/styles/v1/adam97x/cjavcj1680vgz2sqshn70q5pg/tiles/256/{z}/{x}/{y}?access_token=pk.eyJ1IjoiYWRhbTk3eCIsImEiOiJjamF2Y2k1NmswYzhuMnZtazlpNXU2NDExIn0.RifBBI5nelL-4d21mkn7Wg', {
maxZoom: 18,
attribution: 'Map data © OpenStreetMap contributors, ' +
'CC-BY-SA, ' +
'Imagery © Mapbox',
id: 'mapbox.streets'
}).addTo(mymap);
// control that shows state info on hover
var info = L.control();
info.onAdd = function (mymap) {
this._div = L.DomUtil.create('div', 'info');
this.update();
return this._div;
};
info.update = function (properties) {
this._div.innerHTML = '<h4>Highlighted Postcode</h4>' + (properties ?
'<b> Postcode: ' + properties.Name
: 'Hover over a state');
};
info.addTo(mymap);
function style(feature) {
return {
fillColor: 'grey',
weight: 2,
opacity: 1,
color: 'white',
dashArray: '3',
fillOpacity: 0.5
};
}
L.geoJson(statesdata, {style: style}).addTo(mymap);
function highlightFeature(e) {
var layer = e.target;
layer.setStyle({
weight: 5,
opacity: 1,
color: '#000',
dashArray: '',
fillOpacity: 0.7
});
if (!L.Browser.ie && !L.Browser.opera && !L.Browser.edge) {
layer.bringToFront();
}
info.update(layer.feature.properties);
postcode = layer.feature.properties.Name.substr(2)-1;
console.log(postcode);
}
/*global statesdata*/
var geojson;
function resetHighlight(e) {
geojson.resetStyle(e.target);
info.update();
}
function zoomFeature(e) {
mymap.fitBounds(e.target.getBounds());
var colonString = statesdata
.features[postcode]
.geometry
.coordinates[0]
.map(pair => pair.reverse().join())
.join(':');
for (var a = 0; a < 1; a++){
var request = police_api_base_url + colonString + police_api_dates[a]
get_JSON(request, JSON_callback);
}
}
function onEachFeature(feature, layer) {
layer.on({
mouseover: highlightFeature,
mouseout: resetHighlight,
click: zoomFeature
});
}
geojson = L.geoJson(statesdata, {
style: style,
onEachFeature: onEachFeature
}).addTo(mymap);
geojson.eachLayer(function (layer) {
layer.bindPopup(layer.feature.properties.Name);
});
function JSON_callback(data){
completed_requests++;
var data_len = data.length;
if (data[0] != undefined){
for (var i = 0; i < data_len; i++){
cat = data[i]["category"];
lat = data[i]["location"]["latitude"];
lng = data[i]["location"]["longitude"];
if (cat in crimes) {
crimes[cat]++;
} else {
crimes[cat] = 1;
}
create_marker(lat, lng);
}
}
if (completed_requests == 1){
console.log("Requests done");
console.log(crimes);
}
}
function create_crime_markers(lat, lng, cat){
show_by_id("num_of_crimes_load_img");
show_by_id("popular_crime_load_img");
completed_requests = 0;
num_of_crimes = 0;
crimes = {};;
for (var a = 0; a < 1; a++){
var request = police_api_base_url + lat + "&lng=" + lng + police_api_dates[a]
get_JSON(request, JSON_callback);
}
}
var current_lat_lng = [];
function create_marker(lat, lng, title){
current_lat_lng.push(lat, lng, cat);
chunksize = 3;
var chunks = [];
current_lat_lng.forEach((item)=>{
if(!chunks.length || chunks[chunks.length-1].length == chunksize)
chunks.push([]);
chunks[chunks.length-1].push(item);
});
var markers = L.markerClusterGroup({
chunkedloading: true,
spiderfyOnMaxZoom: true,
showCoverageOnHover: false,
zoomToBoundsOnClick: true,
spiderfyDistanceMultiplier: 2.4
});
var markerList = [];
for (var f = 0; f < chunks.length; f++) {
var marker = new L.circleMarker([chunks[f][0],chunks[f][1]])
markerList.push(marker);
}
markers.addLayers(markerList);
mymap.addLayer(markers);
}
body { margin:0; padding:0; }
#map { position:absolute; top:0; bottom:0; width:100%; }
.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; }
<html>
<head>
<meta charset=utf-8 />
<title>KML Data</title>
<meta name='viewport' content='initial-scale=1,maximum-scale=1,user-scalable=no' />
<link rel="stylesheet" href="https://unpkg.com/leaflet#1.2.0/dist/leaflet.css" />
<link rel="stylesheet" href="https://unpkg.com/leaflet.markercluster#1.2.0/dist/MarkerCluster.Default.css" />
<script src="https://unpkg.com/leaflet#1.2.0/dist/leaflet.js"></script>
<script type="text/javascript" src="https://project-adam97.c9users.io/asset/bd.js"></script>
<script src="https://project-adam97.c9users.io/asset/requests.js"></script>
</head>
<body>
<script> src='https://api.mapbox.com/mapbox.js/plugins/leaflet-omnivore/v0.2.0/leaflet-omnivore.min.js'></script>
<script src="https://unpkg.com/leaflet.markercluster#1.2.0/dist/leaflet.markercluster.js"></script>
<div id='map'></div>
</body>
</html>
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>
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();
});
});