dygraph, display day beside date on x-axis - charts

I have dygraph working.
Currently, x-axis granularity is 1 day and format displayed on axis is ddMMM, e.g. 02May.
I wish to display the day as well, e.g. Fri 02May.
How do I do this ?
Thank you
HTML page containing JavaScript:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>Temperature(°C) vs Time</title>
<script type='text/javascript' src='http://code.jquery.com/jquery-1.4.4rc2.js'></script>
<link rel="stylesheet" type="text/css" href="/css/result-light.css">
<script type='text/javascript' src="http://dygraphs.com/dygraph-combined.js"></script>
<style type='text/css'>
</style>
<script type='text/javascript'>//<![CDATA[
$(document).ready(function () {
var r = [ ];
var base_time = Date.parse("2014/03/05");
var num = 24 * 0.25 * 365;
for (var i = 0; i < num; i++) {
r.push([ new Date(base_time + i * 3600 * 1000),
i + 50 * (i % 60), // line
i * (num - i) * 4.0 / num // parabola
]);
}
var orig_range = [ r[0][0].valueOf(), r[r.length - 1][0].valueOf() ];
// NEW CODE INSERTED - STARTS
var one_month_previous = new Date();
one_month_previous.setMonth(one_month_previous.getMonth() - 1);
var one_week_previous = new Date();
one_week_previous.setDate(one_week_previous.getDate()-7);
var three_days_previous = new Date();
three_days_previous.setDate(three_days_previous.getDate()-3);
var one_days_previous = new Date();
one_days_previous.setDate(one_days_previous.getDate()-1);
var twelve_hours_previous = new Date();
twelve_hours_previous.setHours(twelve_hours_previous.getHours() - 12);
// NEW CODE INSERTED - ENDS
var d_names = ["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];
var m_names = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
g = new Dygraph(
document.getElementById("graphdiv3"),
"show_csv.php",
{
// NEW CODE INSERTED - STARTS
// dateWindow: [ Date.parse(one_month_previous) ,
// Date.parse(new Date()) ],
dateWindow: [ Date.parse(one_week_previous) ,
Date.parse(new Date()) ],
// dateWindow: [ Date.parse(three_days_previous) ,
// Date.parse(new Date()) ],
// dateWindow: [ Date.parse(one_days_previous) ,
// Date.parse(new Date()) ],
// dateWindow: [ Date.parse(twelve_hours_previous) ,
// Date.parse(new Date()) ],
// dateWindow: [ Date.parse("2014/03/01 12:00:00"),
// Date.parse("2014/03/31 12:00:00") ],
// NEW CODE INSERTED - ENDS
title: 'Temperature(°C) vs Time',
rollPeriod: 1,
showRoller: true,
xlabel: '',
ylabel: 'Temperature (°C)',
legend: 'always',
labelsKMB: 'true',
labelsSeparateLines: 'true',
colors: [
"rgb(51,204,204)",
"#00DD55",
"rgb(255,100,100)",
"rgba(50,50,200,0.4)"],
axes: {
x: {
axisLabelFormatter: function(d, gran) {
var curr_day = d_names[d.getDay()];
var curr_month = m_names[d.getMonth()];
return curr_day + " "
+ Dygraph.zeropad(d.getDate())
+ curr_month;
}
}
}
//
//
// below works
//
// axes: {
// x: {
// valueFormatter: function(x) {
// return 'text';
// },
// axisLabelFormatter: function(x) {
// return x;
// },
// }
// }
//
}
);
var desired_range = null;
function approach_range() {
if (!desired_range) return;
// go halfway there
var range = g.xAxisRange();
if (Math.abs(desired_range[0] - range[0]) < 60 &&
Math.abs(desired_range[1] - range[1]) < 60) {
g.updateOptions({dateWindow: desired_range});
// g.updateOptions(
// {dateWindow: desired_range,
//axes: {
// x: {
// axisLabelFormatter: function(d, gran) {
// var curr_day = d_names[d.getDay()];
// var curr_month = m_names[d.getMonth()];
// return curr_day + " "
// + Dygraph.zeropad(d.getDate())
// + curr_month;
// }
// }
// }
//});
// (do not set another timeout.)
} else {
var new_range;
new_range = [0.5 * (desired_range[0] + range[0]),
0.5 * (desired_range[1] + range[1])];
g.updateOptions({dateWindow: new_range});
// g.updateOptions(
//
//{dateWindow: new_range, axes: {
// x: {
// axisLabelFormatter: function(d, gran) {
// var curr_day = d_names[d.getDay()];
// var curr_month = m_names[d.getMonth()];
// return curr_day + " "
// + Dygraph.zeropad(d.getDate())
// + curr_month;
// }
// }
// }}
//);
animate();
}
}
function animate() {
setTimeout(approach_range, 50);
}
var zoom = function(res) {
var w = g.xAxisRange();
desired_range = [ w[0], w[0] + res * 1000 ];
animate();
}
var reset = function() {
desired_range = orig_range;
animate();
}
var pan = function(dir) {
var w = g.xAxisRange();
var scale = w[1] - w[0];
var amount = scale * 0.25 * dir;
desired_range = [ w[0] + amount, w[1] + amount ];
animate();
}
document.getElementById('hour').onclick = function() { zoom(3600); };
document.getElementById('day').onclick = function() { zoom(86400); };
document.getElementById('week').onclick = function() { zoom(604800); };
document.getElementById('month').onclick = function() { zoom(30 * 86400); };
document.getElementById('full').onclick = function() { reset(); };
document.getElementById('left').onclick = function() { pan(-1); };
document.getElementById('right').onclick = function() { pan(+1); };
}
);
//]]>
</script>
</head>
<body>
<center>
<div id="graphdiv3"
style="width:900px; height:400px;"></div>
</center>
<p>
<br>
<center>
<b>Zoom:</b>
<button id="hour">hour</button>
<button id="day">day</button>
<button id="week">week</button>
<button id="month">month</button>
<button id="full">full</button>
<br> or, click & drag. Double-click to zoom back out.
<br>
<b>Pan:</b>
<button id="left">left</button>
<button id="right">right</button>
or, shift & drag.
<br>
<b>Raw Data:</b>
<button onclick="window.location.href='show_csv_raw_data.php'">raw</button>
<!--
<b>Zoom:</b>
hour
day
week
month
full
<b>Pan:</b>
left
right
-->
<br>
<br>Measurements every 15 mins. Refresh with F5 button for update.
<br>Your last page refresh was on <b><span id="long_date"></span></b>
<script type='text/javascript'>
var datetime = new Date();
document.getElementById("long_date").innerHTML=datetime;
</script>
</center>
<br>
<br>
Notes:
<br> 1. Measurements before 19<sup>th</sup> March: Hall Cupboard was "Inside" sitting on Rasp Pi, Loft was just "Inside window", Hall was external temp measurement, "Outside window"
<br> 2. Mar 31<sup>st</sup>, green line, shows loft temp rise of ~8°C(8am) to 17°C(3pm), Δ ~ 9°C, in zero octave cloud/ direct sunlight conditions. Direct lift in hall temperature, red line, while heating off clear. Indicative that solar heating of loft as thermal barrier worthwhile.
<br> 3. April 3<sup>rd</sup>, red line, shows hall temp rise of ~14°C(17:45) to 20°C(19:45), Δ ~ 5°C, in two hours while loft temprature remains fairly constant (flat) ie no solar gain. Shows heating performance of approximately 2.5°C per hour
<br> 4. April 20<sup>th</sup>. Raw data can be viewed.
<br> 5. April 29<sup>th</sup>. Heating is off: the evening of Friday 25<sup>th</sup>, all of Sat 26<sup>th</sup>, all of Sun 27<sup>th</sup> and early morning Mon 28<sup>th</sup>. Consequences of heating off can be seen.
<br>6. April 29<sup>th</sup>. Loft space (green line) heats, with keroscene space heating off, through black colour concerete tiles, in zero octave cloud/ direct sunlight conditions. Solar gain is
<dl>
<dd>o Loft temp rise of ~7 °C(6:30am) to 20.9°C(5:30pm), Δ ~ 14°C, <i>and</i> </dd>
<dd>o Hall way temp rise of ~11.4°C(6:30am) to 15.6°C(5:30pm), Δ ~ 4°C </dd>
<br>
<dd> Conversion = 0.3°C rise in Hall way temperature per 1.0°C rise in loft space temperature</dd>
<br>
<dd>See solar (black-body) space heating ideas http://bit.ly/solar-air-heating </dd>
</dl>
7.
</p>
<div id="div_g"></div>
<br>
<br>
<iframe width="300" height="200" style="border: 1px solid #cccccc;" src="http://api.thingspeak.com/channels/11286/charts/3?width=450&height=260&results=1000&dynamic=true&yaxis=Hall&title=Hall%20Temp" ></iframe>
<iframe width="300" height="200" style="border: 1px solid #cccccc;" src="http://api.thingspeak.com/channels/11286/charts/1?width=450&height=260&results=1000&dynamic=true&yaxis=Hall%20Cupboard&title=Hall%20Cupboard%20Temp" ></iframe>
<iframe width="300" height="200" style="border: 1px solid #cccccc;" src="http://api.thingspeak.com/channels/11286/charts/2?width=450&height=260&results=1000&dynamic=true&yaxis=Loft&title=Loft%20Temp" ></iframe>
</body>
</html>

use the axisLabelFormatter property and format the date as desired
var d_names = ["Sun","Mon", "Tue", "Wed",
"Thu", "Fri", "Sat"];
var m_names = ["Jan", "Fe", "Mar",
"Apr", "May", "Jun", "Jul", "Aug", "Sep",
"Oct", "Novr", "Dec"];
var g3 = new Dygraph(
document.getElementById("g_div"),
DailyData(),
{
xAxisLabelWidth: 80,
axisLabelFontSize: 12,
width: 640,
height: 350,
axes: {
x: {
axisLabelFormatter: function(d, gran) {
var curr_day = d_names[d.getDay()];
var curr_month = m_names[d.getMonth()];
return curr_day + " "
+ Dygraph.zeropad(d.getDate())
+ curr_month;
}
}
}
});
Here is a DEMO

Related

Why does mic.getLevel() not go to 0 again after getAudioContext().suspend() is called?

Making a voice recorder visualizer and I'm just about finished but there's one thing, After I stop the recording, the values in mic.getLevel() do not go back to 0 but instead it seems like the last value that was recorded in mic.getLeve() is stored permanently and added to the height of my ellipse so the ellipse would then have a height of some value rather than 0 which it started with, is there anyway to fix this?
var recordAudio;
function setup() {
createCanvas(windowWidth, windowHeight);
recordAudio = new AudioFile()
}
function draw() {
background(0);
recordAudio.draw();
recordAudio.setup();
recordAudio.drawBorder();
recordAudio.drawNode();
}
function AudioFile() {
this.nodes = [];
var speed = 2;
var endBorder;
var mic = new p5.AudioIn();
var micLevel;
var level;
var recorder = new p5.SoundRecorder();
var soundFile = new p5.SoundFile();
var button = createButton('Start Recording');
var state = 0;
this.draw = function() {
background(0);
level = mic.getLevel();
micLevel = floor(map(level, 0, 0.6545, 0, 50));
}
this.drawNode = function() {
if (frameCount % 5 == 0) {
this.addNode()
}
for (var i = 0; i < this.nodes.length; i++) {
var node = this.nodes[i]
for (var j = 0; j < node.length; j++) {
fill(255);
node[j].x -= speed;
ellipse(node[j].x, node[j].y, node[j].width, node[j].height)
}
if (node[0].x < endBorder) {
this.nodes.splice(i, 1);
}
}
}
this.drawBorder = function() {
var x = windowWidth / 9;
var y = windowHeight / 10;
var width = (windowWidth / 9) * 7;
var height = windowHeight - y * 2;
stroke(255);
strokeWeight(2);
noFill();
rect(x, y, width, height);
}
this.addNode = function() {
this.nodes.push(
[{
x: ((windowWidth / 9) * 8) - 10,
y: windowHeight / 2,
width: 5,
height: 5 * micLevel
}])
}
this.setup = function() {
endBorder = windowWidth / 9 + 5;
mic.start();
recorder.setInput(mic);
button.position(windowWidth / 9, windowHeight / 10);
button.style('font-size', '18px');
button.mousePressed(this.recording)
}
this.recording = function() {
if (state === 0 && mic.enabled) {
button.html("Stop Recording");
getAudioContext().resume()
recorder.record(soundFile);
state++
} else if (state === 1) {
button.html("Start Recording");
getAudioContext().suspend();
recorder.stop();
state++;
} else if (state === 2) {
save(soundFile, 'Sound.wav');
state = 0;
}
}
}
<!DOCTYPE html>
<html>
<head>
<link href="style.css" rel="stylesheet">
<script src="p5.min.js"></script>
<script src="p5.dom.js"></script>
<script src="p5.sound.js"></script>
<script src="sketch.js"></script>
<!--<link rel="stylesheet" type="text/css" href="style.css">-->
<style>
body {
padding: 0;
margin: 0;
}
</style>
</head>
<body>
<div id="Button">
</div>
</body>
</html>
I ended up making a global variable called listening and used that in an if statement in draw to set the level to either mic.getLevel() or 0 based on if listening is true or false.

My javascript wont work on my chrome app

I am developing a chrome app (on chromebook) and the javascript wont load. Is it the code, the fact that it is an app? Can someone help? Here is my code:
<!DOCTYPE html>
<html>
<body>
<h1>Cash Register</h1>
//inputs
<input type="text" id="myText1" value="Name">
<input type="text" id="myText2" value="Price">
//add button
<button onclick="add()">Add</button>
//The total goes here
<div id="div1"><h2 id="demo1"><h2 id="demo2"></h2></div>
<script>
//my function
function add() {
//variables
var x = 'Total:'
var y = document.getElementById("myText2").value;
var z = document.getElementById("myText1").value;
//writes the items you enter
//makes a separating line
var para = document.createElement("h4");
var node = document.createTextNode('_____');
para.appendChild(node);
var element = document.getElementById("div1");
element.appendChild(para);
//makes the item
var para = document.createElement("h4");
var node = document.createTextNode(z);
para.appendChild(node);
var element = document.getElementById("div1");
element.appendChild(para);
//makes the price
var para = document.createElement("p");
var node = document.createTextNode(y);
para.appendChild(node);
var element = document.getElementById("div1");
element.appendChild(para);
//writes "Total (total price)"
var w = document.getElementsByTagName("p"); // this gets all the P's as an object
// setup a total starting at 0
var total = 0;
for (var i = 0; i < w.length; i++) {
total += parseInt(w[i].innerText); // make the inner text an integer for addition.
}
document.getElementById("demo1").innerHTML = x;
document.getElementById("demo2").innerHTML = total; // replace w with total
}
</script>
</body>
</html>
Anything would help. If you have a solution, please shoe it to me! Thank you. By the way, I am new at this. When I put it through jshint, this is what I got:
(Image)
So, all I had to do was add
//my function
function add() {
//variables
var x = 'Total:';
var y = document.getElementById("myText2").value;
var z = document.getElementById("myText1").value;
//writes the items you enter
//makes a separating line
var para = document.createElement("h4");
var node = document.createTextNode('_____');
para.appendChild(node);
var element = document.getElementById("div1");
element.appendChild(para);
//makes the item
para = document.createElement("h4");
node = document.createTextNode(z);
para.appendChild(node);
element = document.getElementById("div1");
element.appendChild(para);
//makes the price
para = document.createElement("p");
node = document.createTextNode(y);
para.appendChild(node);
element = document.getElementById("div1");
element.appendChild(para);
//writes "Total (total price)"
var w = document.getElementsByTagName("p"); // this gets all the P's as an object
// setup a total starting at 0
var total = 0;
for (var i = 0; i < w.length; i++) {
total += parseInt(w[i].innerText); // make the inner text an integer for addition.
}
document.getElementById("demo1").innerHTML = x;
document.getElementById("demo2").innerHTML = total; // replace w with total
}
document.addEventListener('DOMContentLoaded', function() {
var link = document.getElementById('link');
// onClick's logic below:
link.addEventListener('click', function() {
add()
});
});
to a javascript file and change my script tag to
<script src="add.js"></script>
If anyone wants to use this, here is the code:
Manifest:
{
"name": "Cash register",
"description": "Use at garage sales",
"version": "0.1",
"manifest_version": 2,
"app": {
"background": {
"scripts": ["background.js"]
}
},
"icons": { "16": "calculator-16.png", "128": "calculator-128.png" }
}
background.js:
chrome.app.runtime.onLaunched.addListener(function() {
chrome.app.window.create('index.html', {
'outerBounds': {
'width': 400,
'height': 500
}
});
});
add.js:
//my function
function add() {
//variables
var x = 'Total:';
var y = document.getElementById("myText2").value;
var z = document.getElementById("myText1").value;
//writes the items you enter
//makes a separating line
var para = document.createElement("h4");
var node = document.createTextNode('_____');
para.appendChild(node);
var element = document.getElementById("div1");
element.appendChild(para);
//makes the item
para = document.createElement("h4");
node = document.createTextNode(z);
para.appendChild(node);
element = document.getElementById("div1");
element.appendChild(para);
//makes the price
para = document.createElement("p");
node = document.createTextNode(y);
para.appendChild(node);
element = document.getElementById("div1");
element.appendChild(para);
//writes "Total (total price)"
var w = document.getElementsByTagName("p"); // this gets all the P's as an object
// setup a total starting at 0
var total = 0;
for (var i = 0; i < w.length; i++) {
total += parseInt(w[i].innerText); // make the inner text an integer for addition.
}
document.getElementById("demo1").innerHTML = x;
document.getElementById("demo2").innerHTML = total; // replace w with total
}
document.addEventListener('DOMContentLoaded', function() {
var link = document.getElementById('link');
// onClick's logic below:
link.addEventListener('click', function() {
add()
index.html:
<html>
<head>
<script src="add.js"></script>
</head>
<body>
<h1>Cash Register</h1>
<input type="text" id="myText1" value="Name">
<input type="text" id="myText2" value="Price (numbers only)">
<a id="link">Add</a>
<div id="div1"><h2 id="demo1"></h2><h2 id="demo2"></h2></div>
</body></html>
Thanks Everyone!!!
Ok, you are creating the same elements with the same name three times and I don't see how you are using the additional tags and elements but that is most likely the reason an error is being thrown.
Try putting your code through http://jshint.com and you'll see your issues.

Bing Maps containsLocation function

I have a site that uses both Bing and Google maps. Each function has a Bing and Google version. I am having trouble duplicating the google.maps.geometry.poly.containsLocation function in Bing maps. Is there such a thing?
Basically I build a polygon and am looking to determine if a pushpin is located inside the polygon on the map.
Bing Maps V8 has a Spatial Math module which can do this calculation for you easily using the intersects function:
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv='Content-Type' content='text/html; charset=utf-8'/>
</head>
<body>
<div id='myMap' style='width: 100vw; height: 100vh;'></div>
<script type='text/javascript'>
function load() {
var map = new Microsoft.Maps.Map(document.getElementById('myMap'), {
credentials: 'YOUR BING MAPS KEY'
});
//Create a polygon and location for testing.
var center = map.getCenter();
var polygon = new Microsoft.Maps.Polygon([new Microsoft.Maps.Location(center.latitude - 0.05, center.longitude - 0.05),
new Microsoft.Maps.Location(center.latitude + 0.01, center.longitude - 0.05),
new Microsoft.Maps.Location(center.latitude + 0.01, center.longitude + 0.05)], { fillColor: 'yellow', strokeColor: 'orange',
strokeThickness: 5, strokeDashArray: [1, 2, 5, 10] });
map.entities.push(polygon);
var location = new Microsoft.Maps.Location(center.latitude, center.longitude);
//Load the Spatial Math module
Microsoft.Maps.loadModule('Microsoft.Maps.SpatialMath', function () {
//Check to see if the shapes intersect.
var intersects = Microsoft.Maps.SpatialMath.Geometry.intersects(location, polygon);
if(intersects){
alert("The location is inside in the polygon");
} else {
alert("The location is NOT inside in the polygon");
}
});
}
</script>
<script type='text/javascript' src='https://www.bing.com/api/maps/mapcontrol?callback=load' async defer></script>
</body>
</html>
You can add your own method to do so using the extensibility of Bing Maps AJAX control. You can put that extension method on the Microsoft.Maps.Location class.
Microsoft.Maps.Location.prototype.IsInPolygon=function(polygon)
{
var isInside = false;
var j = 0;
var x = this.longitude;
var y = this.latitude;
var paths = polygon.getLocations();
for (var i = 0; i < paths.length ; i++) {
j++;
if (j == paths.length) { j = 0; }
if (((paths[i].latitude < y) && (paths[j].latitude >= y)) || ((paths[j].latitude < y) && (paths[i].latitude >= y))) {
if (paths[i].longitude + (y - paths[i].latitude) / (paths[j].latitude - paths[i].latitude) * (paths[j].longitude - paths[i].longitude) < x) {
isInside = !isInside
}
}
}
return isInside;
};
Here is a working example with Bing Maps V8:
<!DOCTYPE html>
<html>
<head>
<title>Bing Maps - V8 - Polygon test</title>
<meta http-equiv='Content-Type' content='text/html; charset=utf-8'/>
</head>
<body>
<div id='myMap' style='width: 100vw; height: 100vh;'></div>
<script type='text/javascript'>
function load() {
Microsoft.Maps.Location.prototype.IsInPolygon=function(polygon)
{
var isInside = false;
var j = 0;
var x = this.longitude;
var y = this.latitude;
var paths = polygon.getLocations();
for (var i = 0; i < paths.length ; i++) {
j++;
if (j == paths.length) { j = 0; }
if (((paths[i].latitude < y) && (paths[j].latitude >= y)) || ((paths[j].latitude < y) && (paths[i].latitude >= y))) {
if (paths[i].longitude + (y - paths[i].latitude) / (paths[j].latitude - paths[i].latitude) * (paths[j].longitude - paths[i].longitude) < x) {
isInside = !isInside
}
}
}
return isInside;
};
var map = new Microsoft.Maps.Map(document.getElementById('myMap'), {
credentials: 'YOUR KEY'
});
var center = map.getCenter();
var polygon = new Microsoft.Maps.Polygon([new Microsoft.Maps.Location(center.latitude - 0.05, center.longitude - 0.05),
new Microsoft.Maps.Location(center.latitude + 0.01, center.longitude - 0.05),
new Microsoft.Maps.Location(center.latitude + 0.01, center.longitude + 0.05)], { fillColor: 'yellow', strokeColor: 'orange',
strokeThickness: 5, strokeDashArray: [1, 2, 5, 10] });
map.entities.push(polygon);
var location = new Microsoft.Maps.Location(center.latitude, center.longitude);
alert("The location is inside in the polygon : " + location.IsInPolygon(polygon));
}
</script>
<script type='text/javascript' src='https://www.bing.com/api/maps/mapcontrol?callback=load' async defer></script>
</body>
</html>

Hijri, Gregorian date and time with arabic Numerals

I am working on to display the date in Arabic.
That includes Hijri(Islamic) Date, Gregorian Date and time.
The issue is, i want the numerals to be display the arabic numerals not the english ones.
Remember, i can't change the whole page numerals into arabic numerals. Just the script numerals to be converted.
and here is the code:
<div align="center">
<table border="0" width="39%" dir="rtl">
<tr>
<td>
<script language="JavaScript">
var fixd;
function isGregLeapYear(year)
{
return year%4 == 0 && year%100 != 0 || year%400 == 0;
}
function gregToFixed(year, month, day)
{
var a = Math.floor((year - 1) / 4);
var b = Math.floor((year - 1) / 100);
var c = Math.floor((year - 1) / 400);
var d = Math.floor((367 * month - 362) / 12);
if (month <= 2)
e = 0;
else if (month > 2 && isGregLeapYear(year))
e = -1;
else
e = -2;
return 1 - 1 + 365 * (year - 1) + a - b + c + d + e + day;
}
function Hijri(year, month, day)
{
this.year = year;
this.month = month;
this.day = day;
this.toFixed = hijriToFixed;
this.toString = hijriToString;
}
function hijriToFixed()
{
return this.day + Math.ceil(29.5 * (this.month - 1)) + (this.year - 1) * 354 +
Math.floor((3 + 11 * this.year) / 30) + 227015 - 1;
}
function hijriToString()
{
var months = new Array("محرم","صفر","ربيع أول","ربيع ثانى","جمادى أول","جمادى ثانى","رجب","شعبان","رمضان","شوال","ذو القعدة","ذو الحجة");
return this.day + " " + months[this.month - 1]+ " " + this.year;
}
function fixedToHijri(f)
{
var i=new Hijri(1100, 1, 1);
i.year = Math.floor((30 * (f - 227015) + 10646) / 10631);
var i2=new Hijri(i.year, 1, 1);
var m = Math.ceil((f - 29 - i2.toFixed()) / 29.5) + 1;
i.month = Math.min(m, 12);
i2.year = i.year;
i2.month = i.month;
i2.day = 1;
i.day = f - i2.toFixed() + 1;
return i;
}
var tod=new Date();
var weekday=new Array("الأحد","الإثنين","الثلاثاء","الأربعاء","الخميس","الجمعة","السبت");
var monthname=new Array("يناير","فبراير","مارس","إبريل","مايو","يونيو","يوليو","أغسطس","سبتمبر","أكتوبر","نوفمبر","ديسمبر");
var y = tod.getFullYear();
var m = tod.getMonth();
var d = tod.getDate();
var dow = tod.getDay();
document.write(weekday[dow] + " " + d + " " + monthname[m] + " " + y);
m++;
fixd=gregToFixed(y, m, d);
var h=new Hijri(1421, 11, 28);
h = fixedToHijri(fixd);
document.write(" م | " + h.toString() + "هـ");
</script>
|
<script>
<!-- Clock Code -->
var dayarray=new Array("","","","","","","")
var montharray=new Array("","","","","","","","","","","","")
function getthedate(){
var mydate=new Date()
var year=mydate.getYear()
if (year < 1000)
year+=1900
var day=mydate.getDay()
var month=mydate.getMonth()
var daym=mydate.getDate()
if (daym<10)
daym="0"+daym
var hours=mydate.getHours()
var minutes=mydate.getMinutes()
var seconds=mydate.getSeconds()
var dn="H:i"
if (hours>=12)
dn="مساءً"
else
dn="صباحاً"
if (hours>12){
hours=hours-12
}
if (hours==0)
hours=12
if (minutes<=9)
minutes="0"+minutes
if (seconds<=9)
seconds="0"+seconds
var cdate="<small><font color='000000' face='Times New Roman'>"+hours+":"+minutes+":"+seconds+" "+dn+"</font></small>"
if (document.all)
document.all.clock.innerHTML=cdate
else if (document.getElementById)
document.getElementById("clock").innerHTML=cdate
else
document.write(cdate)
}
if (!document.all&&!document.getElementById)
getthedate()
function goforit(){
if (document.all||document.getElementById)
setInterval("getthedate()",1000)
}
</script>
<span id="clock">
<body onLoad="goforit()">
</span></td>
</tr>
</table>
</div>
</td>
</tr>
</table>
function convertDigitIn(enDigit){ // PERSIAN, ARABIC, URDO
var newValue="";
for (var i=0;i<enDigit.length;i++)
{
var ch=enDigit.charCodeAt(i);
if (ch>=48 && ch<=57)
{
// european digit range
var newChar=ch+1584;
newValue=newValue+String.fromCharCode(newChar);
}
else
newValue=newValue+String.fromCharCode(ch);
}
return newValue;
}
i suggest for you to use HIJRI date script from AR-PHP , it's useful and very easy to edit.
to change numbers to arabic Numerals you need to change numbers font-face in css

Google Maps API GeoLocation not working for mobile

I'm not really sure why the GeoLocation works on my PC, but not my iPhone ... I've got sensor=true within the script call to the API, but apart from that, I'm at a loss. Here's the entire script:
<div id="info"></div>
<div id="map_canvas" style="width:908px; height:420px"></div>
<input type="text" id="addressInput" size="10"/>
<select id="radiusSelect">
<option value="5" selected>5mi</option>
<option value="15" selected>15mi</option>
<option value="25" selected>25mi</option>
<option value="100">100mi</option>
<option value="200">200mi</option>
<option value="4000">4000mi</option>
</select>
<input type="button" value="Search" onclick="searchLocations();">
<div><select id="locationSelect" style="width:100%;visibility:hidden"></select></div>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?key=AIzaSyCe49sI29q0AVNo9iVvQ-lDlDwZpFZuA4o&sensor=true"></script>
<script type="text/javascript" src="http://gmaps-samples-v3.googlecode.com/svn/trunk/geolocate/geometa.js"></script>
<script type="text/javascript">
var map;
var markers = [];
var infoWindow;
var locationSelect;
function load() {
map = new google.maps.Map(document.getElementById("map_canvas"), {
center: new google.maps.LatLng(40, -100),
zoom: 4,
mapTypeId: 'roadmap',
mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU}
});
infoWindow = new google.maps.InfoWindow();
locationSelect = document.getElementById("locationSelect");
locationSelect.onchange = function() {
var markerNum = locationSelect.options[locationSelect.selectedIndex].value;
if (markerNum != "none") {
google.maps.event.trigger(markers[markerNum], 'click');
}
};
// geolocation
prepareGeolocation();
doGeolocation();
}
function doGeolocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(positionSuccess, positionError);
} else {
positionError(-1);
}
}
function positionError(err) {
var msg;
switch(err.code) {
case err.UNKNOWN_ERROR:
msg = "Unable to find your location";
break;
case err.PERMISSION_DENINED:
msg = "Permission denied in finding your location";
break;
case err.POSITION_UNAVAILABLE:
msg = "Your location is currently unknown";
break;
case err.BREAK:
msg = "Attempt to find location took too long";
break;
default:
msg = "Location detection not supported in browser";
}
document.getElementById('info').innerHTML = msg;
}
function positionSuccess(position) {
// Centre the map on the new location
var coords = position.coords || position.coordinate || position;
var latLng = new google.maps.LatLng(coords.latitude, coords.longitude);
map.setCenter(latLng);
map.setZoom(15);
var marker = new google.maps.Marker({
map: map,
position: latLng,
title: 'Why, there you are!'
});
document.getElementById('info').innerHTML = 'Looking for <b>' +
coords.latitude + ', ' + coords.longitude + '</b>...';
// And reverse geocode.
(new google.maps.Geocoder()).geocode({latLng: latLng}, function(resp) {
var place = "You're around here somewhere!";
if (resp[0]) {
var bits = [];
for (var i = 0, I = resp[0].address_components.length; i < I; ++i) {
var component = resp[0].address_components[i];
if (contains(component.types, 'political')) {
bits.push('<b>' + component.long_name + '</b>');
}
}
if (bits.length) {
place = bits.join(' > ');
}
marker.setTitle(resp[0].formatted_address);
}
document.getElementById('info').innerHTML = place;
});
}
function contains(array, item) {
for (var i = 0, I = array.length; i < I; ++i) {
if (array[i] == item) return true;
}
return false;
}
function searchLocations() {
console.log("searching locations...");
var address = document.getElementById("addressInput").value;
var geocoder = new google.maps.Geocoder();
geocoder.geocode({address: address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
searchLocationsNear(results[0].geometry.location);
} else {
alert(address + ' not found');
}
});
}
function clearLocations() {
//infoWindow.close();
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(null);
}
markers.length = 0;
locationSelect.innerHTML = "";
var option = document.createElement("option");
option.value = "none";
option.innerHTML = "See all results:";
locationSelect.appendChild(option);
locationSelect.style.visibility = "visible";
}
function searchLocationsNear(center) {
clearLocations();
var radius = document.getElementById('radiusSelect').value;
/* var searchUrl = 'phpsqlajax_search.php?lat=' + center.lat() + '&lng=' + center.lng() + '&radius=' + radius; */
var searchUrl = 'http://dev-imac.local/phpsqlajax_search.php?lat=' + center.lat() + '&lng=' + center.lng() + '&radius=' + radius;
console.log(searchUrl);
downloadUrl(searchUrl, function(data) {
var xml = parseXml(data);
var markerNodes = xml.documentElement.getElementsByTagName("marker");
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < markerNodes.length; i++) {
var name = markerNodes[i].getAttribute("name");
var address = markerNodes[i].getAttribute("address");
var distance = parseFloat(markerNodes[i].getAttribute("distance"));
var latlng = new google.maps.LatLng(
parseFloat(markerNodes[i].getAttribute("lat")),
parseFloat(markerNodes[i].getAttribute("lng")));
createOption(name, distance, i);
createMarker(latlng, name, address);
bounds.extend(latlng);
}
map.fitBounds(bounds);
});
}
function createMarker(latlng, name, address) {
var html = "<b>" + name + "</b> <br/>" + address;
var marker = new google.maps.Marker({
map: map,
position: latlng
});
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(html);
infoWindow.open(map, marker);
});
markers.push(marker);
}
function createOption(name, distance, num) {
var option = document.createElement("option");
option.value = num;
option.innerHTML = name + "(" + distance.toFixed(1) + ")";
locationSelect.appendChild(option);
}
function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request.responseText, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function parseXml(str) {
if (window.ActiveXObject) {
var doc = new ActiveXObject('Microsoft.XMLDOM');
doc.loadXML(str);
return doc;
} else if (window.DOMParser) {
return (new DOMParser).parseFromString(str, 'text/xml');
}
}
function doNothing() {}
window.onload = load();
</script>
First of all,
mapTypeId: 'roadmap',
should be:
mapTypeId: google.maps.MapTypeId.ROADMAP,
but that should cause it to fail in your PC as well.
Other than that, your <script> section should be in the <head> section of the document and not in the <body>. Maybe the iPhone browser is more strict about this than the browser on your PC. What browser(s) are you using in each system? (I'm guessing you're using IE on the PC. Have you tried other browsers?)