Decimal Degrees to Hours, Mins, Secs in PHP via a variable - php

I have a php/javascript code that takes a GPS coordinate from an Iphone/website app (instamapper) and adds it to my website page. (using snippets of other peoples code examples so far) I'd like to change the popup from displaying the decimal coordinates to proper Lat / Long but cant quite work it out. Any help or pointers you guys could give would be great. My code is below.
found here http://www.morvargh-sailing.co.uk/tracker/test2.php
<?php
$key = "16194603621692259587";
$fichier = "http://www.instamapper.com/api?action=getPositions&key=".$key."&num=1";
$fp=#fopen($fichier,"r");
$texte = "";
if($fp)
{
while(!feof($fp))
{
$texte .= fgets($fp,1024);
}
}
$donnees = explode(',',$texte);
/*
0 : first line plus device number
1 : Device label
2. Position timestamp in UTC (number of seconds since January 1, 1970)
3. Latitude
4. Longitude
5. Altitude in meters
6. Speed in meters / second
7. Heading in degrees
*/
date_default_timezone_set('GMT');
$name = $donnees[1];
$date = date('H:i:s d-m-Y e', $donnees[2]);
$lat = $donnees[3];
$longitude = $donnees[4];
$altitude = $donnees[5];
$speed = $donnees[6];
$heading = $donnees[7];
echo('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>Where am I</title>
<script src="http://maps.google.com/maps?file=api&v=2&key=ABQIAAAA_GqVjhr7wgurGjr_zR-wJxSbxjqNwl0XTkuBKGwUYonF3JCDWBRyXrxgjwLgrUjcet0gLjyGZOGwCA" type="text/javascript"></script>
<style type="text/css">
v\:* {behavior:url(#default#VML);}
html, body {width: 100%; height: 350px}
body, form, p {margin: 0; padding: 0; text-align:center; font-family:"lucida grande","trebuchet ms",sans-serif; font-size:12px;}
a:link, a:visited, a:hover {color: #369; background:transparent; text-decoration: none;}
#instamapper {position:absolute; left:80px; bottom:10px;}
#instamapper p {text-align:right;}
</style>
</head>
<body onLoad="showAddress(\''.$lat.', '.$longitude.'\'); return false" onunload="GUnload()">
<div id="map" style="width: 100%; height: 100%;"></div>
<div id="instamapper">
<p>
GPS tracking powered by InstaMapper
<p>
<div>
<script type="text/javascript">
//<![CDATA[
var momento = "'.$date.'";
var altitud = "'.$altitude.'" + "m";
var velocidad = "'.$speed.'" + " Km/h";
var longitude = "'.$longitude.'";
var latitude = "'.$lat.'";
if (GBrowserIsCompatible()) {
var map = new GMap2(document.getElementById("map"));
var geocoder = new GClientGeocoder();
map.addControl(new GLargeMapControl());
map.addControl(new GMapTypeControl());
function showAddress(address) {
geocoder.getLatLng(
address,
function(point) {
if (!point) {
alert("\"" + address + "\" no encontrado");
} else {
map.setCenter(point, 12);
var marker = new GMarker(point);
var info = "<b>Last known location:</b><p>Time: " + momento + "<br>Latitude: " + latitude + "<br>Longitude: " + longitude + "<br>Heading: " + '.$heading.' +"º";
GEvent.addListener(marker, "click", function() {
marker.openInfoWindowHtml(info);
});
map.addOverlay(marker);
marker.openInfoWindowHtml(info);
}
}
);
}
}
//]]>
</script>
</body>
</html>');
?>

Try this function: http://jsfiddle.net/eAUJr/1/
function format(newLat, newLng) {
if (newLat < 0) {
newLat = myround(Math.abs(newLat)) + "S";
} else {
newLat = myround(newLat) + "N";
}
if (newLng < 0) {
newLng = myround(Math.abs(newLng)) + "W";
} else {
newLng = myround(newLng) + "E";
}
return[newLat, newLng];
}
function myround(val) {
deg = parseInt(val);
val -= deg;
val *= 60;
min = parseInt(val);
val -= min;
val *= 60;
sec = parseInt(val);
remainder = val - sec;
if(remainder >= 0.5) {
sec += 1;
}
return deg + "°" + min + "'" + sec + '"';
}
document.write(format(-0.000277778, 20.292))
// output: 0°0'1"S,20°17'31"E

Related

Why the coordinates of a polygon in Google Map returns false Lat, Lng values?

Here is my code that i am using for fetching data from Google Maps also fetching coordinates of polygon and polylines from Drawer.
**
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<meta charset="UTF-8" />
<title>Muhammad</title>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false&libraries=drawing"></script>
<style type="text/css">
#map,
html,
body {
padding: 0;
margin: 0;
width: 95%;
height: 700px;
float: right;
}
#panel {
width: 200px;
font-family: Arial, sans-serif;
font-size: 13px;
float: right;
margin: 10px;
}
#color-palette {
clear: both;
}
.color-button {
width: 14px;
height: 14px;
font-size: 0;
margin: 2px;
float: left;
cursor: pointer;
}
#delete-button {
margin-top: 5px;
}
</style>
<script type="text/javascript">
var drawingManager;
var selectedShape;
var colors = ["#1E90FF", "#FF1493", "#32CD32", "#FF8C00", "#4B0082"];
var selectedColor;
var colorButtons = {};
function clearSelection() {
if (selectedShape) {
selectedShape.setEditable(false);
selectedShape = null;
}
}
function setSelection(shape) {
clearSelection();
// getting shape coordinates
var v = shape.getPath();
var coords = [];
for (var i = 0; i < v.getLength(); i++) {
var xy = v.getAt(i);
console.log(`Cordinate lat ${i}: ` + xy.lat() + `and long ${i}: ` + xy.lng());
var x = document.createElement('INPUT');
x.setAttribute('type', 'text');
x.setAttribute('value', xy);
document.body.appendChild(x);
coords.push([xy.lat()], [xy.lng()]);
}
console.log(coords + 'Muhammad');
document.getElementById('coords_value').value = coords;
selectedShape = shape;
shape.setEditable(true);
selectColor(shape.get("fillColor") || shape.get("strokeColor"));
}
function saveButton(shape) {
}
function deleteSelectedShape() {
if (selectedShape) {
selectedShape.setMap(null);
}
}
function selectColor(color) {
selectedColor = color;
for (var i = 0; i < colors.length; ++i) {
var currColor = colors[i];
colorButtons[currColor].style.border = currColor == color ? "2px solid #789" : "2px solid #fff";
}
// Retrieves the current options from the drawing manager and replaces the
// stroke or fill color as appropriate.
var polylineOptions = drawingManager.get("polylineOptions");
polylineOptions.strokeColor = color;
drawingManager.set("polylineOptions", polylineOptions);
var rectangleOptions = drawingManager.get("rectangleOptions");
rectangleOptions.fillColor = color;
drawingManager.set("rectangleOptions", rectangleOptions);
var circleOptions = drawingManager.get("circleOptions");
circleOptions.fillColor = color;
drawingManager.set("circleOptions", circleOptions);
var polygonOptions = drawingManager.get("polygonOptions");
polygonOptions.fillColor = color;
drawingManager.set("polygonOptions", polygonOptions);
}
function setSelectedShapeColor(color) {
console.log("fn setSelectedShapeColor()");
console.log(selectedShape);
if (selectedShape) {
if (selectedShape.type == google.maps.drawing.OverlayType.POLYLINE) {
selectedShape.set("strokeColor", color);
} else {
selectedShape.set("fillColor", color);
}
}
}
function makeColorButton(color) {
var button = document.createElement("span");
button.className = "color-button";
button.style.backgroundColor = color;
google.maps.event.addDomListener(button, "click", function() {
selectColor(color);
setSelectedShapeColor(color);
});
return button;
}
function buildColorPalette() {
var colorPalette = document.getElementById("color-palette");
for (var i = 0; i < colors.length; ++i) {
var currColor = colors[i];
var colorButton = makeColorButton(currColor);
colorPalette.appendChild(colorButton);
colorButtons[currColor] = colorButton;
}
selectColor(colors[0]);
}
function initialize() {
var pakistan = new google.maps.LatLng(30.3753, 69.3451);
var map = new google.maps.Map(document.getElementById("map"), {
zoom: 3,
center: pakistan,
disableDefaultUI: true,
zoomControl: true
});
var marker = new google.maps.Marker({
position: pakistan,
map: map
});
var polyOptions = {
strokeWeight: 0,
fillOpacity: 0.45,
editable: true,
draggable: true
};
// Creates a drawing manager attached to the map that allows the user to draw
// markers, lines, and shapes.
drawingManager = new google.maps.drawing.DrawingManager({
drawingMode: google.maps.drawing.OverlayType.POLYGON,
markerOptions: {
draggable: true
},
polylineOptions: {
editable: true,
draggable: true
},
rectangleOptions: polyOptions,
circleOptions: polyOptions,
polygonOptions: polyOptions,
map: map
});
google.maps.event.addListener(drawingManager, "overlaycomplete", function(e) {
if (e.type !== google.maps.drawing.OverlayType.MARKER) {
// Switch back to non-drawing mode after drawing a shape.
drawingManager.setDrawingMode(null);
// Add an event listener that selects the newly-drawn shape when the user
// mouses down on it.
var newShape = e.overlay;
newShape.type = e.type;
google.maps.event.addListener(newShape, "click", function(e) {
if (e.vertex !== undefined) {
if (newShape.type === google.maps.drawing.OverlayType.POLYGON) {
var path = newShape.getPaths().getAt(e.path);
path.removeAt(e.vertex);
if (path.length < 3) {
newShape.setMap(null);
}
}
if (newShape.type === google.maps.drawing.OverlayType.POLYLINE) {
var path = newShape.getPath();
path.removeAt(e.vertex);
if (path.length < 2) {
newShape.setMap(null);
}
}
}
setSelection(newShape);
saveButton(newShape);
});
setSelection(newShape);
saveButton(newShape);
}
});
// Clear the current selection when the drawing mode is changed, or when the
// map is clicked.
google.maps.event.addListener(drawingManager, "drawingmode_changed", clearSelection);
google.maps.event.addListener(map, "click", clearSelection);
google.maps.event.addDomListener(document.getElementById("delete-button"), "click", deleteSelectedShape);
buildColorPalette();
}
google.maps.event.addDomListener(window, "load", initialize);
var IO = {
//returns array with storable google.maps.Overlay-definitions
IN: function(
arr, //array with google.maps.Overlays
encoded //boolean indicating if pathes should be stored encoded
) {
var shapes = [],
goo = google.maps,
shape,
tmp;
for (var i = 0; i < arr.length; i++) {
shape = arr[i];
tmp = {
type: this.t_(shape.type),
id: shape.id || null
};
switch (tmp.type) {
case "CIRCLE":
tmp.radius = shape.getRadius();
tmp.geometry = this.p_(shape.getCenter());
break;
case "MARKER":
tmp.geometry = this.p_(shape.getPosition());
break;
case "RECTANGLE":
tmp.geometry = this.b_(shape.getBounds());
break;
case "POLYLINE":
tmp.geometry = this.l_(shape.getPath(), encoded);
break;
case "POLYGON":
tmp.geometry = this.m_(shape.getPaths(), encoded);
break;
}
shapes.push(tmp);
}
return shapes;
},
//returns array with google.maps.Overlays
OUT: function(
arr, //array containg the stored shape-definitions
map //map where to draw the shapes
) {
var shapes = [],
goo = google.maps,
map = map || null,
shape,
tmp;
for (var i = 0; i < arr.length; i++) {
shape = arr[i];
switch (shape.type) {
case "CIRCLE":
tmp = new goo.Circle({
radius: Number(shape.radius),
center: this.pp_.apply(this, shape.geometry)
});
break;
case "MARKER":
tmp = new goo.Marker({
position: this.pp_.apply(this, shape.geometry)
});
break;
case "RECTANGLE":
tmp = new goo.Rectangle({
bounds: this.bb_.apply(this, shape.geometry)
});
break;
case "POLYLINE":
tmp = new goo.Polyline({
path: this.ll_(shape.geometry)
});
break;
case "POLYGON":
tmp = new goo.Polygon({
paths: this.mm_(shape.geometry)
});
break;
}
tmp.setValues({
map: map,
id: shape.id
});
shapes.push(tmp);
}
return shapes;
},
l_: function(path, e) {
path = path.getArray ? path.getArray() : path;
if (e) {
return google.maps.geometry.encoding.encodePath(path);
} else {
var r = [];
for (var i = 0; i < path.length; ++i) {
r.push(this.p_(path[i]));
}
return r;
}
},
ll_: function(path) {
if (typeof path === "string") {
return google.maps.geometry.encoding.decodePath(path);
} else {
var r = [];
for (var i = 0; i < path.length; ++i) {
r.push(this.pp_.apply(this, path[i]));
}
return r;
}
},
m_: function(paths, e) {
var r = [];
paths = paths.getArray ? paths.getArray() : paths;
for (var i = 0; i < paths.length; ++i) {
r.push(this.l_(paths[i], e));
}
return r;
},
mm_: function(paths) {
var r = [];
for (var i = 0; i < paths.length; ++i) {
r.push(this.ll_.call(this, paths[i]));
}
return r;
},
p_: function(latLng) {
return [latLng.lat(), latLng.lng()];
},
pp_: function(lat, lng) {
return new google.maps.LatLng(lat, lng);
},
b_: function(bounds) {
return [this.p_(bounds.getSouthWest()), this.p_(bounds.getNorthEast())];
},
bb_: function(sw, ne) {
return new google.maps.LatLngBounds(this.pp_.apply(this, sw), this.pp_.apply(this, ne));
},
t_: function(s) {
var t = ["CIRCLE", "MARKER", "RECTANGLE", "POLYLINE", "POLYGON"];
for (var i = 0; i < t.length; ++i) {
if (s === google.maps.drawing.OverlayType[t[i]]) {
return t[i];
}
}
}
};
</script>
</head>
<body>
<div id="panel">
<div id="color-palette"></div>
<form method="POST" action="submit.php">
<input type="text" id="coords_value" name="coords" value="Muhammad">
<button onclick="saveButton()">Muhammad</button>
</form>
<div><button id="delete-button">Delete Selected Shape</button></div>
</div>
<div id="map"></div>
</body>
</html>
**
and my submit.php file
**
<?php $servername = "localhost";
$username = "root";
$password = "";
$db = "users";
$mysqli = new mysqli($servername, $username, $password, $db);
// SET #g = 'POLYGON($_POST[coords])';
$coords = $_POST['coords'];
//$stmt = "INSERT INTO polygon_data (polygon_values) VALUES (GeomFromText('POLYGON((30 10, 40 40, 20 40, 10 20, 30 10))'))";
$stmt = "INSERT INTO polygon_data (polygon_values) VALUES (PolygonFromText('POLYGON((40.95269385429521, -74.14416921914062,40.959175907354734, -74.11670339882812,40.9419322410085, -74.13009298623047))'))";
if ($mysqli->query($stmt) === TRUE) {
echo "feedback sucessfully submitted";
} else {
echo "Error: " . $stmt . "<br>" . $mysqli->error;
}
$mysqli->close();
?>
**
For example if i draw a pollygon and then i gets the following points that are not correct, this is because in a polygon the first and last point's coordinates would be same but in mine case it seems to be somehow different as below.
(61.81599137659937,102.17362172851564,62.956500953314375,117.64237172851564,56.80241721826492,111.84159047851564)
and this difference is a huge difference.And i did not getting my expecting result?
Thanks

JS Countdown does not move seconds

I am trying to pass time in microseconds from my PHP server to this Hilios countdown code. Well, it's passing and calculating correctly, but the countdown is static, I need it to keep updating until it resets:
01 days 00:00:10 (09, 08, ..., 00:00:00)
 
Any idea what I can do to keep the countdown updated, I tried setTimeout and interval, but to no avail. Thanks !!!
<html>
<head>
<script src="//code.jquery.com/jquery.js"></script>
<!--<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.3/moment-with-locales.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.4.0/moment-timezone-with-data-2010-2020.min.js"></script>
<!-- Include MomentJS library -->
<?php
setlocale(LC_TIME, 'pt_BR', 'pt_BR.utf-8', 'pt_BR.utf-8', 'portuguese');
date_default_timezone_set('America/Sao_Paulo');
echo '<b>ServerTime</b> = '.date('D M d Y H:i:s').' GMT-0300 (Horário Padrão de Brasília)';
?>
<br><br>
<script>
function horaServer(){
return '<?php echo round(microtime(true) * 1000);?>';
}
(function(factory) {
"use strict";
if (typeof define === "function" && define.amd) {
define([ "jquery" ], factory);
} else {
factory(jQuery);
}
})(function($) {
"use strict";
var PRECISION = 100;
var instances = [], matchers = [];
matchers.push(/^[0-9]*$/.source);
matchers.push(/([0-9]{1,2}\/){2}[0-9]{4}( [0-9]{1,2}(:[0-9]{2}){2})?/.source);
matchers.push(/[0-9]{4}([\/\-][0-9]{1,2}){2}( [0-9]{1,2}(:[0-9]{2}){2})?/.source);
matchers = new RegExp(matchers.join("|"));
function parseDateString(dateString) {
if (dateString instanceof Date) {
return dateString;
}
if (String(dateString).match(matchers)) {
if (String(dateString).match(/^[0-9]*$/)) {
dateString = Number(dateString);
}
if (String(dateString).match(/\-/)) {
dateString = String(dateString).replace(/\-/g, "/");
}
return new Date(dateString);
} else {
throw new Error("Couldn't cast `" + dateString + "` to a date object.");
}
}
var DIRECTIVE_KEY_MAP = {
Y: "years",
m: "months",
w: "weeks",
d: "days",
D: "totalDays",
H: "hours",
M: "minutes",
S: "seconds"
};
function strftime(offsetObject) {
return function(format) {
var directives = format.match(/%(-|!)?[A-Z]{1}(:[^;]+;)?/gi);
if (directives) {
for (var i = 0, len = directives.length; i < len; ++i) {
var directive = directives[i].match(/%(-|!)?([a-zA-Z]{1})(:[^;]+;)?/), regexp = new RegExp(directive[0]), modifier = directive[1] || "", plural = directive[3] || "", value = null;
directive = directive[2];
if (DIRECTIVE_KEY_MAP.hasOwnProperty(directive)) {
value = DIRECTIVE_KEY_MAP[directive];
value = Number(offsetObject[value]);
}
if (value !== null) {
if (modifier === "!") {
value = pluralize(plural, value);
}
if (modifier === "") {
if (value < 10) {
value = "0" + value.toString();
}
}
format = format.replace(regexp, value.toString());
}
}
}
format = format.replace(/%%/, "%");
return format;
};
}
function pluralize(format, count) {
var plural = "s", singular = "";
if (format) {
format = format.replace(/(:|;|\s)/gi, "").split(/\,/);
if (format.length === 1) {
plural = format[0];
} else {
singular = format[0];
plural = format[1];
}
}
if (Math.abs(count) === 1) {
return singular;
} else {
return plural;
}
}
// importante
var Countdown = function(el, finalDate, callback) {
this.el = el;
this.$el = $(el);
this.interval = null;
this.offset = {};
this.instanceNumber = instances.length;
instances.push(this);
this.$el.data("countdown-instance", this.instanceNumber);
if (callback) {
this.$el.on("update.countdown", callback);
this.$el.on("stoped.countdown", callback);
this.$el.on("finish.countdown", callback);
}
this.setFinalDate(finalDate);
this.start();
};
$.extend(Countdown.prototype, {
start: function() {
if (this.interval !== null) {
clearInterval(this.interval);
}
var self = this;
this.update();
this.interval = setInterval(function() {
self.update.call(self);
}, PRECISION);
},
stop: function() {
clearInterval(this.interval);
this.interval = null;
this.dispatchEvent("stoped");
},
pause: function() {
this.stop.call(this);
},
resume: function() {
this.start.call(this);
},
remove: function() {
this.stop();
instances[this.instanceNumber] = null;
delete this.$el.data().countdownInstance;
},
setFinalDate: function(value) { // pega o valor de data-countdown
//alert(value);
this.finalDate = parseDateString(value);
},
update: function() {
if (this.$el.closest("html").length === 0) {
this.remove();
return;
}
//this.totalSecsLeft = this.finalDate.getTime() - new Date().getTime();
/* setar hora do servidor */
/*
function horaServidor(){
//var qq = new Date("<?php echo date('D M d Y H:i:s').' GMT-0300 (Horário Padrão de Brasília)'; ?>").getTime();
//alert(''+qq);
//return new Date("<?php echo date('D M d Y H:i:s').' GMT-0300 (Horário Padrão de Brasília)'; ?>").getTime();
return new Date("<?php echo date('D M d Y H:i:s').' GMT-0300 (Horário Padrão de Brasília)'; ?>");
//setInterval(horaServidor(), 1000);
}
*/
this.totalSecsLeft = this.finalDate.getTime() - horaServer();
//this.totalSecsLeft = this.finalDate.getTime() - horaServidor().getTime();
//this.totalSecsLeft = this.finalDate.getTime() - new Date('Sat Oct 26 2019 18:37:04 GMT-0300 (Horário Padrão de Brasília)').getTime();
// this.totalSecsLeft = this.finalDate.getTime() - new Date().getTime(); LINHA ORIGINAL
this.totalSecsLeft = Math.ceil(this.totalSecsLeft / 1e3);
this.totalSecsLeft = this.totalSecsLeft < 0 ? 0 : this.totalSecsLeft;
this.offset = {
seconds: this.totalSecsLeft % 60,
minutes: Math.floor(this.totalSecsLeft / 60) % 60,
hours: Math.floor(this.totalSecsLeft / 60 / 60) % 24,
days: Math.floor(this.totalSecsLeft / 60 / 60 / 24) % 7,
totalDays: Math.floor(this.totalSecsLeft / 60 / 60 / 24),
weeks: Math.floor(this.totalSecsLeft / 60 / 60 / 24 / 7),
months: Math.floor(this.totalSecsLeft / 60 / 60 / 24 / 30),
years: Math.floor(this.totalSecsLeft / 60 / 60 / 24 / 365)
};
if (this.totalSecsLeft === 0) {
this.stop();
this.dispatchEvent("finish");
} else {
this.dispatchEvent("update");
}
},
dispatchEvent: function(eventName) {
var event = $.Event(eventName + ".countdown");
event.finalDate = this.finalDate;
event.offset = $.extend({}, this.offset);
event.strftime = strftime(this.offset);
this.$el.trigger(event);
}
});
$.fn.countdown = function() {
var argumentsArray = Array.prototype.slice.call(arguments, 0);
return this.each(function() {
var instanceNumber = $(this).data("countdown-instance");
if (instanceNumber !== undefined) {
var instance = instances[instanceNumber], method = argumentsArray[0];
if (Countdown.prototype.hasOwnProperty(method)) {
instance[method].apply(instance, argumentsArray.slice(1));
} else if (String(method).match(/^[$A-Z_][0-9A-Z_$]*$/i) === null) {
instance.setFinalDate.call(instance, method);
instance.start();
} else {
$.error("Method %s does not exist on jQuery.countdown".replace(/\%s/gi, method));
}
} else {
new Countdown(this, argumentsArray[0], argumentsArray[1]);
}
});
};
});
</script>
</head>
<body>
<b>Countdown</b>
<div data-countdown="2019/10/26 20:30:31"></div>
<div data-countdown="2019/10/27 14:35:18"></div>
<div data-countdown="2019/10/26 12:30:35"></div>
<div data-countdown="2019/10/29 10:57:04"></div>
<script>
$('[data-countdown]').each(function() {
var $this = $(this), finalDate = $(this).data('countdown');
$this.countdown(finalDate, function(event) {
$this.html(event.strftime('%D dias %H:%M:%S'));
});
});
</script>
Idk whats wrong with your code but I can help you with another one that I used (u can adapt it):
<style>
#import url('https://fonts.googleapis.com/css?family=Lato:400,700|Montserrat:900');
.timer {
color: #F6F4F3;
text-align: center;
text-transform: uppercase;
font-family: 'Lato', sans-serif;
}
.days,
.hours,
.minutes,
.seconds {
display: inline-block;
padding: 5px;
min-width: 20%;
margin: 1px;
height: 70px;
border-radius: 5px;
text-align: center;
font-size: 12px;
}
.days {
background-color: #EF2F3C;
}
.hours {
background: #F6F4F3;
color: #183059;
}
.minutes {
background: #276FBF;
}
.seconds {
background: #F0A202;
}
.numbers {
font-family: 'Montserrat', sans-serif;
color: #183059;
font-size: 18px;
}
</style>
<?php
foreach ($events as $index => $event) { ?>
<div id="timer<?php echo $index; ?>" class="card-deck timer-wrap" data-event-date="<?php echo $formatted; ?>"></div>
<?php } ?>
<script>
initTimers('.timer-wrap');
function initTimers(selector) {
var timers = document.querySelectorAll(selector);
if (timers.length > 0) {
for (var i = 0; i < timers.length; i++) {
countdown(timers[i]);
}
}
}
function countdown(timerElem) {
const year = new Date().getFullYear();
const dat = new Date(timerElem.dataset.eventDate);
let timer = setInterval(function() {
const today = new Date().getTime();
const diff = dat - today;
let days = Math.floor(diff / (1000 * 60 * 60 * 24));
let hours = Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
let minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
let seconds = Math.floor((diff % (1000 * 60)) / 1000);
timerElem.innerHTML =
"<div class=\"card days\"> \<div class=\"numbers\">" + days + "</div>days</div> \<div class=\"card hours\"> \
<div class=\"numbers\">" + hours + "</div>hours</div> \<div class=\"card minutes\"> \
<div class=\"numbers\">" + minutes + "</div>minutes</div> \<div class=\"card seconds\"> \
<div class=\"numbers\">" + seconds + "</div>seconds</div> \</div>";
}, 1000);
}
</script>

How to prevent multiple pages?

I have a site that gives to the user 1000 points for every timer (30 min).
When the user clicks on the button "Start timer" the timer count down 30 min, when the timer is over button appears that gives the user 1000 points.
My problem is: the users can open this page a lot of times and get a lot of points for 30 min instead of 1000.
Timer script:
<script type="text/javascript">
var interval;
var minutes = 30;
var seconds = 0;
var a;
var audio = new Audio('timer.mp3');
function AutoRefresh( t ) {
setTimeout("location.reload(true);", t);
}
function countdown(element) {
interval = setInterval(function () {
var el = document.getElementById(element);
if (seconds == 0) {
if (minutes == 0) {
el.innerHTML = '<h2>The Timer is over!</h2>';
el.innerHTML += '<form action="timer.php" method="post" onsubmit="hide();" id="hide"><input type="submit" value="Get 1000 points" name="update" class="newslesubmit" style="width: 100%; font-size: 16px; box-shadow: inset 0px 1px 2px 0px rgba(238,238,238,1);" /></form>';
audio.play();
AutoRefresh(600000);
clearInterval(interval);
return;
} else {
minutes--;
seconds = 59;
}
}
if (minutes > 0) {
var minute_text = minutes + (minutes > 1 ? ' :' : ' :');
} else {
var minute_text = '';
}
if(minutes < 10) {
var minute_text = '0' + minutes + ' :';
}
var second_text = seconds > 1 ? '' : '';
if(seconds < 10) {
var a = ' 0';
} else {
var a = ' ';
}
el.innerHTML = minute_text + a + seconds + ' ' + second_text + '';
seconds--;
}, 1000);
}
function start() {
if (!interval) {
countdown('countdown');
}
};
function hide() {
var hide = document.getElementById('hide');
hide.style.display='none';
}
</script>
The PHP and the HTML:
<?php
if(isset($_POST['update'])) {
$req = mysql_query('SELECT last_earn FROM users WHERE id="'.mysql_real_escape_string($_SESSION['userid']).'"');
$dnn = mysql_fetch_array($req);
$a = $dnn['last_earn'] + 3000;
if($a <= time()){
$date = date('Y-m-d H:i:s');
mysql_query('UPDATE users SET last_earn="'.$date.'" WHERE id="'.mysql_real_escape_string($_SESSION['userid']).'"');
mysql_query('UPDATE users SET earn=earn+1000 WHERE id="'.mysql_real_escape_string($_SESSION['userid']).'"');
echo "<meta http-equiv='refresh' content='0;URL=index.php' />";
}
}
?>
<input type="button" value="Start timer" onclick="start(); this.style.display='none'" class="newslesubmit" style="width: 100%; font-size: 16px; box-shadow: inset 0px 1px 2px 0px rgba(238,238,238,1);" />
<div id="countdown" style="font-size: 40px; font-weight: bold;"></div>
Whenever you give the user points set a column in the database for "Points last received at". Simply save it as a timestamp or datetime. Then, when updating with points, only update if they last received their points more than 30min ago :D No user can ever cheat it and get more than is possible.

Puzzle image code I want more images for aromatic sliding page

Below is my Puzzle image code. I have getting only one image because of onload function so please suggest me to getting more image
this file is include in my main html code but one Image will be displayed and another is display NULL
<html>
<head>
<title>HTML5 Puzzle Game</title>
<script type="text/javascript">
window.onload = onReady;
var can;
var ctx;
var img;
var clickX;
var clickY;
var selected1;
var selected2;
var blockSize = 160;
var piecesArray = new Array();
function onReady()
{
can = document.getElementById('myCanvas');
ctx = can.getContext('2d');
img = new Image();
img.onload = onImage1Load;
img.src = "images/<?php echo $crows['product_image1']; ?>";
}
function onImage1Load()
{
var r;
for(var i = 0; i < 4; i++)
{
for(var j = 0; j < 3; j++)
{
r = new Rectangle(i * blockSize, j * blockSize, i*blockSize + blockSize, j * blockSize + blockSize);
piecesArray.push(r);
}
}
scrambleArray(piecesArray, 30);
drawImage();
}
function Rectangle(left, top, right, bottom)
{
this.left = left;
this.top = top;
this.right = right;
this.bottom = bottom;
this.width = right - left;
this.height = bottom - top;
}
function scrambleArray(ar, times)
{
var count = 0;
var temp;
var index1;
var index2;
while(count < times)
{
index1 = Math.floor(Math.random()*piecesArray.length);
index2 = Math.floor(Math.random()*piecesArray.length);
temp = piecesArray[index1];
piecesArray[index1] = piecesArray[index2];
piecesArray[index2] = temp;
count++;
}
}
function drawImage()
{
var r;
for(var i = 0; i < 4; i++)
{
for(var j = 0; j < 3; j++)
{
r = piecesArray[i*3+j];
ctx.drawImage(img, r.left, r.top, r.width, r.height, i*blockSize, j*blockSize, blockSize, blockSize);
ctx.strokeStyle = "#fff";
}
}
}
function highlightRect(drawX, drawY)
{
ctx.beginPath();
ctx.moveTo(drawX, drawY);
ctx.lineTo(drawX + blockSize, drawY);
ctx.lineTo(drawX + blockSize, drawY + blockSize);
ctx.lineTo(drawX, drawY + blockSize);
ctx.lineTo(drawX, drawY);
ctx.lineWidth = 2;
// set line color
ctx.strokeStyle = "#fff";
ctx.stroke();
}
function swapRects(r1, r2)
{
var index1;
var index2;
var temp = r1;
index1 = piecesArray.indexOf(r1);
index2 = piecesArray.indexOf(r2);
piecesArray[index1] = r2;
piecesArray[index2] = temp;
}
function onCanvasClick(evt)
{
clickX = evt.offsetX;
clickY = evt.offsetY;
var drawX = Math.floor(clickX / blockSize);
var drawY = Math.floor(clickY / blockSize);
var index = drawX * 3 + drawY;
var targetRect = piecesArray[index];
var drawHighlight = true;
drawX *= blockSize;
drawY *= blockSize;
ctx.clearRect(0, 0, 640, 480);
if(selected1 != undefined && selected2 != undefined)
{
selected1 = selected2 = undefined;
}
if(selected1 == undefined)
{
selected1 = targetRect;
}
else
{
selected2 = targetRect;
swapRects(selected1, selected2);
drawHighlight = false;
}
drawImage();
if(drawHighlight)
highlightRect(drawX, drawY);
}
</script>
</head>
<body>
<div style="margin:0 auto; width:640px; height:480px; border: 4px none #cc6699;">
<canvas id="myCanvas" width="640" height="480" onclick="onCanvasClick(event);" style="border:1px dotted #fff;">
</canvas>
</div>
</body>
</html>

Javascript re-write of js/php music composition program

A while ago, I created (with much help) a program that uses php and javascript to make some ambient music by randomizing an array of .ogg files. Now I am trying to re-write it with js alone.
The new code immediately below does not work (the .ogg files do play properly when clicked individually, but nothing happens when you press the 'start' button, which is the main feature). (The code below that (containing php) does work.) I've been over the new code several times and I think I've got the 'typos'. I'm pretty sure the problem is in the syntax of the window.setTimeout line, but haven't quite figured out how it should be.
Thanks for any help you can offer!
<!DOCTYPE html>
<html>
<head>
<title>Audio Testing</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
function getRandInt (min, max)
{
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function shuffle(o)
{
for(var j, x, i = o.length; i; j = parseInt(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
return o;
}
</script>
<script type="text/javascript">
var tonesTotal = 150;
function getDelays(tonesTotal)
{
var return_array = array();
for (var i = 0; i < tonesTotal; i++)
{
var r = getRandInt(0, 600);
var delay = r * 1000;
return_array.push(delay);
}
return return_array;
}
var delays = new Array();
delays = getDelays(tonesTotal);
$(document).ready(function()
{
$("#start").click(function()
{
var base = 'sound';
for(var i = 0; i < tonesTotal; i++)
var id = base + ((i + 1) );
window.setTimeout ("document.getElementById('" + id + "').play()", delays[i]);
});
});
</script>
</head>
<body style="background-color: #999;">
<button id="start">Start</button>
<br><br>
<script>
var tonesTotal = 150;
var samples = new Array("tone0.ogg", "tone2.ogg", "tone4.ogg", "tone6.ogg", "tone7.ogg", "tone9.ogg", "tone11.ogg", "tone12.ogg");
for (var i=1; i <= tonesTotal; i++)
{
shuffle (samples);
var samplepick = samples[0];
document.write ("<audio controls id='sound" + i + "'><source src='" + samplepick + "' type='audio/ogg'></audio>");
}
</script>
</body>
</html>
PREVIOUS CODE:
<!DOCTYPE html>
<html>
<head>
<title>Audio Testing</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<?php
//$randC = rand(1,4);
$C = 150;
function getDelays($C)
{
$return_array = array();
for($i = 0; $i < $C; $i++)
{
$r = rand(0, 600);
$delay = $r * 1000;
array_push($return_array, $delay);
}
return $return_array;
}
echo "<script type=\"text/javascript\">\n";
echo "var delays = new Array();";
$delays = getDelays($C);
for($i = 0; $i < sizeof($delays); $i++)
{
echo "delays[" . $i . "] = " . $delays[$i] . ";\n";
}
echo "
$(document).ready(function()
{
$(\"#start\").click(function()
{
var base = 'sound';
for(i = 0; i < $C; i++)
{
var id = base + ((i + 1) );
window.setTimeout (\"document.getElementById('\" + id + \"').play()\", delays[i]);
}
});
});
</script>
";
?>
<style type="text/css">
</style>
</head>
<body style="background-color: #999;">
<button id="start">Start</button>
<br><br>
<?php
$samples = array("tone0.ogg", "tone2.ogg", "tone4.ogg", "tone6.ogg", "tone7.ogg", "tone9.ogg", "tone11.ogg", "tone12.ogg");
for ($i=1; $i<= $C; $i++) {
shuffle ($samples);
$samplepick = $samples[0];
echo '<audio controls id="sound'.$i.'">
<source src='.$samplepick.' type="audio/ogg">
</audio>';
}
?>
</body>
</html>
When I tested it locally I found a Javascript error in the getDelays() function: First line of code should be:
var return_array = new Array();

Categories