Trying to implement own function in an existing GitHub project - javascript

L.interpolatePosition = function(p1, p2, duration, t) {
var k = t/duration;
k = (k > 0) ? k : 0;
k = (k > 1) ? 1 : k;
return L.latLng(p1.lat + k * (p2.lat - p1.lat),
p1.lng + k * (p2.lng - p1.lng));
};
L.Marker.MovingMarker = L.Marker.extend({
//state constants
statics: {
notStartedState: 0,
endedState: 1,
pausedState: 2,
runState: 3
},
options: {
autostart: false,
loop: false,
},
initialize: function (latlngs, durations, options) {
L.Marker.prototype.initialize.call(this, latlngs[0], options);
this._latlngs = latlngs.map(function(e, index) {
return L.latLng(e);
});
if (durations instanceof Array) {
this._durations = durations;
} else {
this._durations = this._createDurations(this._latlngs, durations);
}
this._currentDuration = 0;
this._currentIndex = 0;
this._state = L.Marker.MovingMarker.notStartedState;
this._startTime = 0;
this._startTimeStamp = 0; // timestamp given by requestAnimFrame
this._pauseStartTime = 0;
this._animId = 0;
this._animRequested = false;
this._currentLine = [];
this._stations = {};
},
isRunning: function() {
return this._state === L.Marker.MovingMarker.runState;
},
isEnded: function() {
return this._state === L.Marker.MovingMarker.endedState;
},
isStarted: function() {
return this._state !== L.Marker.MovingMarker.notStartedState;
},
isPaused: function() {
return this._state === L.Marker.MovingMarker.pausedState;
},
start: function() {
if (this.isRunning()) {
return;
}
if (this.isPaused()) {
this.resume();
} else {
this._loadLine(0);
this._startAnimation();
this.fire('start');
}
},
resume: function() {
if (! this.isPaused()) {
return;
}
// update the current line
this._currentLine[0] = this.getLatLng();
this._currentDuration -= (this._pauseStartTime - this._startTime);
this._startAnimation();
},
pause: function() {
if (! this.isRunning()) {
return;
}
this._pauseStartTime = Date.now();
this._state = L.Marker.MovingMarker.pausedState;
this._stopAnimation();
this._updatePosition();
},
stop: function(elapsedTime) {
if (this.isEnded()) {
return;
}
this._stopAnimation();
if (typeof(elapsedTime) === 'undefined') {
// user call
elapsedTime = 0;
this._updatePosition();
}
this._state = L.Marker.MovingMarker.endedState;
this.fire('end', {elapsedTime: elapsedTime});
},
addLatLng: function(latlng, duration) {
this._latlngs.push(L.latLng(latlng));
this._durations.push(duration);
},
moveTo: function(latlng, duration) {
this._stopAnimation();
this._latlngs = [this.getLatLng(), L.latLng(latlng)];
this._durations = [duration];
this._state = L.Marker.MovingMarker.notStartedState;
this.start();
this.options.loop = false;
},
addStation: function(pointIndex, duration) {
if (pointIndex > this._latlngs.length - 2 || pointIndex < 1) {
return;
}
this._stations[pointIndex] = duration;
},
onAdd: function (map) {
L.Marker.prototype.onAdd.call(this, map);
if (this.options.autostart && (! this.isStarted())) {
this.start();
return;
}
if (this.isRunning()) {
this._resumeAnimation();
}
},
onRemove: function(map) {
L.Marker.prototype.onRemove.call(this, map);
this._stopAnimation();
},
_createDurations: function (latlngs, duration) {
var lastIndex = latlngs.length - 1;
var distances = [];
var totalDistance = 0;
var distance = 0;
// compute array of distances between points
for (var i = 0; i < lastIndex; i++) {
distance = latlngs[i + 1].distanceTo(latlngs[i]);
distances.push(distance);
totalDistance += distance;
}
var ratioDuration = duration / totalDistance;
var durations = [];
for (i = 0; i < distances.length; i++) {
durations.push(distances[i] * ratioDuration);
}
return durations;
},
_startAnimation: function() {
this._state = L.Marker.MovingMarker.runState;
this._animId = L.Util.requestAnimFrame(function(timestamp) {
this._startTime = Date.now();
this._startTimeStamp = timestamp;
this._animate(timestamp);
}, this, true);
this._animRequested = true;
},
_resumeAnimation: function() {
if (! this._animRequested) {
this._animRequested = true;
this._animId = L.Util.requestAnimFrame(function(timestamp) {
this._animate(timestamp);
}, this, true);
}
},
_stopAnimation: function() {
if (this._animRequested) {
L.Util.cancelAnimFrame(this._animId);
this._animRequested = false;
}
},
_updatePosition: function() {
var elapsedTime = Date.now() - this._startTime;
this._animate(this._startTimeStamp + elapsedTime, true);
},
_loadLine: function(index) {
this._currentIndex = index;
this._currentDuration = this._durations[index];
this._currentLine = this._latlngs.slice(index, index + 2);
},
/**
* Load the line where the marker is
* #param {Number} timestamp
* #return {Number} elapsed time on the current line or null if
* we reached the end or marker is at a station
*/
_updateLine: function(timestamp) {
// time elapsed since the last latlng
var elapsedTime = timestamp - this._startTimeStamp;
// not enough time to update the line
if (elapsedTime <= this._currentDuration) {
return elapsedTime;
}
var lineIndex = this._currentIndex;
var lineDuration = this._currentDuration;
var stationDuration;
while (elapsedTime > lineDuration) {
// substract time of the current line
elapsedTime -= lineDuration;
stationDuration = this._stations[lineIndex + 1];
// test if there is a station at the end of the line
if (stationDuration !== undefined) {
if (elapsedTime < stationDuration) {
this.setLatLng(this._latlngs[lineIndex + 1]);
return null;
}
elapsedTime -= stationDuration;
}
lineIndex++;
// test if we have reached the end of the polyline
if (lineIndex >= this._latlngs.length - 1) {
if (this.options.loop) {
lineIndex = 0;
this.fire('loop', {elapsedTime: elapsedTime});
} else {
// place the marker at the end, else it would be at
// the last position
this.setLatLng(this._latlngs[this._latlngs.length - 1]);
this.stop(elapsedTime);
return null;
}
}
lineDuration = this._durations[lineIndex];
}
this._loadLine(lineIndex);
this._startTimeStamp = timestamp - elapsedTime;
this._startTime = Date.now() - elapsedTime;
return elapsedTime;
},
_animate: function(timestamp, noRequestAnim) {
this._animRequested = false;
// find the next line and compute the new elapsedTime
var elapsedTime = this._updateLine(timestamp);
if (this.isEnded()) {
// no need to animate
return;
}
if (elapsedTime != null) {
// compute the position
var p = L.interpolatePosition(this._currentLine[0],
this._currentLine[1],
this._currentDuration,
elapsedTime);
this.setLatLng(p);
}
if (! noRequestAnim) {
this._animId = L.Util.requestAnimFrame(this._animate, this, false);
this._animRequested = true;
}
}
});
L.Marker.movingMarker = function (latlngs, duration, options) {
return new L.Marker.MovingMarker(latlngs, duration, options);
};
I’m still new with JS and I have this problem. I was working on a js that I got from GitHub
https://github.com/ewoken/Leaflet.MovingMarker. Its a project where you have animated markers moving from a to b. I trying to demonstrate a transport environment for my thesis and I wrote my own functions to it.
function train_station(number){
const countries_train = [];
countries_train[1] = [71, "Germany", "Munich", 48.1351, 11.582, "Train Stration", "Europe"]
countries_train[2] = [72, "England", "London", 51.5074, 0.1278, "Train Stration", "Europe"]
countries_train[3] = [73, "Belgium", "Antwerp", 51.2194, 4.4025, "Train Stration", "Europe"]
countries_train[4] = [74, "France", "Limoges", 45.8336, 1.2611, "Train Stration", "Europe"]
countries_train[5] = [75, "Portugal", "Porto", 41.1579, 8.6291, "Train Stration", "Europe"]
countries_train[6] = [76, "Romania", "Bucharest", 44.4268, 26.1025, "Train Stration", "Europe"]
countries_train[7] = [77, "Italy", "Milan", 45.4642, 9.19, "Train Stration", "Europe"]
return countries_train[number]}
function europe_island(number) {
const countries_island = [];
countries_island[1] = [21, "Iceland", "Reykjavik", 64.1466, 21.9426, "Island", "Europe"]
countries_island[2] = [22, "Ireland", "Dublin", 53.3498, 6.2603, "Island", "Europe"]
return countries_island[number]}
export {europe_core, europe_island, europe_uk, train_station, harbour, europe_scandinavia, international}
Thats my function. I have other function but the structure is the same and the js file I want to implement it in is this:
So, I was trying to implement my function in the script.js file from the GitHub link and every time I import a function of mine the script doesn’t
var map = new L.Map('map', {
zoom: 6,
minZoom: 3,
});
var tileUrl = 'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', layer = new L.TileLayer(tileUrl,
{
attribution: 'Maps © OpenStreetMap contributors',
maxZoom: 18
});
map.addLayer(layer);
var parisKievLL = [[48.8567, 2.3508], [50.45, 30.523333]]
var londonParisRomeBerlinBucarest = [[51.507222, -0.1275], [48.8567, 2.3508],
[41.9, 12.5], [52.516667, 13.383333], [44.4166, 26.1]]
var londonBrusselFrankfurtAmsterdamLondon = [[51.507222, -0.1275], [50.85, 4.35],
[50.116667, 8.683333], [52.366667, 4.9], [51.507222, -0.1275]];
var barcelonePerpignanPauBordeauxMarseilleMonaco = [
[41.385064, 2.173403],
[42.698611, 2.895556],
[43.3017, -0.3686],
[44.837912, -0.579541],
[43.296346, 5.369889],
[43.738418, 7.424616]
];
map.fitBounds(londonParisRomeBerlinBucarest);
var marker1 = L.Marker.movingMarker(parisKievLL, [10000]).addTo(map);
L.polyline(parisKievLL).addTo(map);
marker1.once('click', function () {
marker1.start();
marker1.closePopup();
marker1.unbindPopup();
marker1.on('click', function () {
if (marker1.isRunning()) {
marker1.pause();
} else {
marker1.start();
}
});
setTimeout(function () {
marker1.bindPopup('<b>Click me to pause !</b>').openPopup();
}, 2000);
});
marker1.bindPopup('<b>Click me to start !</b>', {closeOnClick: false});
marker1.openPopup();
var marker2 = L.Marker.movingMarker(londonParisRomeBerlinBucarest, [3000, 9000, 9000, 4000], {autostart: true}).addTo(map);
L.polyline(londonParisRomeBerlinBucarest, {color: 'red'}).addTo(map);
marker2.on('end', function () {
marker2.bindPopup(message(), {closeOnClick: false})
.openPopup();
});
var marker3 = L.Marker.movingMarker(londonBrusselFrankfurtAmsterdamLondon,
[2000, 2000, 2000, 2000], {autostart: true, loop: true}).addTo(map);
marker3.loops = 0;
marker3.bindPopup('', {closeOnClick: false});
var marker4 = L.Marker.movingMarker([[45.816667, 15.983333]], []).addTo(map);
marker3.on('loop', function (e) {
marker3.loops++;
if (e.elapsedTime < 50) {
marker3.getPopup().setContent("<b>Loop: " + marker3.loops + "</b>")
marker3.openPopup();
setTimeout(function () {
marker3.closePopup();
if (!marker1.isEnded()) {
marker1.openPopup();
} else {
if (marker4.getLatLng().equals([45.816667, 15.983333])) {
marker4.bindPopup('Click on the map to move me !');
marker4.openPopup();
}
}
}, 2000);
}
});
map.on("click", function (e) {
marker4.moveTo(e.latlng, 2000);
});
var marker5 = L.Marker.movingMarker(barcelonePerpignanPauBordeauxMarseilleMonaco, 10000, {autostart: true}).addTo(map);
marker5.addStation(1, 2000);
marker5.addStation(2, 2000);
marker5.addStation(3, 2000);
marker5.addStation(4, 2000);
L.polyline(barcelonePerpignanPauBordeauxMarseilleMonaco,
{color: 'green'}).addTo(map);
<!DOCTYPE html>
<html>
<head>
<title> Leaflet.MovingMarker Demo Page </title>
<meta charset="UTF-8">
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="description" content="Leaflet plugin to animate marker !">
<meta name="keywords" content="Leaflet MovingMarker marker ewoken github animation">
<meta name="author" content="Ewoken">
<link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.css"/>
<link rel="stylesheet" href="style.css"/>
</head>
<body>
<main>
<h1> Demo of Leaflet.MovingMarker </h1>
<section>
<div id="map">
</div>
</section>
</main>
<script type="text/javascript" src="http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.js"></script>
<script type="text/javascript" src="MovingMarker.js"></script>
<script type="text/javascript" src="script.js">
</script>
</body>
</html>
work anymore.
It shows that "referenceerror L is not defined" and if I do the "Import * as L from 'leaflet'" is says that "referenceerror: window is not defined"
I havent changed the code, it’s just the imports. As soon as I type import the variables in the script turn from purple to grey and dont work anymore.
Im using IntelliJ 2021 IDE Ultimate 2021
I have the type:module in my dependencies so the Imports and exports work.
I change it module on the html file as well
I deleted the folder and reinstalled everything again
Thanks for your time and help guys.

Related

How to make timer not to restart after page refresh in psgTimer library of Jquery?

This is the code snippet of psgTimer Jquery Library, I want not to reload the timer when the page refreshes. I try to save the time diff in local storage. But not able to get the result. Please provide the solution.
(function () {
var callbacks = {
onInit: function () {
},
onStart: function () {
},
onStop: function () {
},
onEnd: function () {
},
onChangeStart: function () {
},
onChangeEnd: function () {
}
};
var base = {
stopped: true,
timezone: 0,
diff: null,
isEnd: false
};
var PsgTimer = function (selector, options) {
var timer = this;
if (selector.nodeType === Node.ELEMENT_NODE) {
timer.container = $(selector);
} else if (typeof selector === 'string') {
timer.selector = selector;
timer.container = $(timer.selector);
} else if (typeof selector === 'object') {
options = selector;
timer.selector = options.selector;
timer.container = $(timer.selector);
}
timer.options = $.extend({}, {
selector: '#psgTimer',
animation: false,
multipleBlocks: false,
endDateTime: undefined,
// currentDateTime: window.serverTime['U'] * 1000 || Date.now(),
currentDateTime: Date.now(),
labels: {
days: timer.container.attr('data-label-days') ? timer.container.attr('data-label-days') : false,
hours: timer.container.attr('data-label-hours') ? timer.container.attr('data-label-hours') : false,
minutes: timer.container.attr('data-label-minutes') ? timer.container.attr('data-label-minutes') : false,
seconds: timer.container.attr('data-label-seconds') ? timer.container.attr('data-label-seconds') : false
}
}, options);
timer.callbacks = timer.options.callbacks = $.extend({}, callbacks, timer.options.callbacks);
timer.base = $.extend({}, base);
if (typeof timer.options.endDateTime === 'string') {
timer.options.endDateTime = setTimerEndFromString(timer, timer.options.endDateTime);
}
timer.container.length ? timer.init() : console.log('No timer element on this page');
};
PsgTimer.prototype.init = function () {
var timer = this,
options = this.options;
var timerEnd = timer.container.attr('data-timer-end');
if (timerEnd !== undefined) {
options.endDateTime = setTimerEndFromString(timer, timerEnd);
}
// options.endDateTime = options.endDateTime + (timer.base.timezone * 1000 * 60 * 60);
timer.countdown = transformCountToArray(getCurrentCountDown(timer), options.multilpeBlocks);
timer.container.addClass('psgTimer').append(createMarkup(timer));
if (options.animation) {
timer.container.addClass('psgTimer_' + options.animation);
}
timer.query = setQueries(timer);
timer.callbacks.onInit();
if (!timer.base.isEnd) {
timer.start();
}
};
PsgTimer.prototype.start = function () {
var timer = this;
if (timer.base.stopped) {
timer.base.stopped = false;
timer.intervalId = setInterval(function () {
updateCounter(timer);
}, 1000);
timer.callbacks.onStart();
}
};
PsgTimer.prototype.restart = function () {
var timer = this;
timer.options.currentDateTime = Date.now();
timer.start();
};
PsgTimer.prototype.stop = function () {
var timer = this;
timer.base.stopped = true;
clearTimeout(timer.intervalId);
timer.callbacks.onStop();
};
var getCurrentCountDown = function (timer) {
var options = timer.options;
var base = timer.base;
options.currentDateTime = options.currentDateTime + 1001;
base.diff = options.endDateTime - options.currentDateTime;
var seconds = 0;
var minutes = 0;
var hours = 0;
var days = 0;
if (base.diff > 0) {
var total = parseFloat(((((base.diff / 1000.0) / 60.0) / 60.0) / 24.0));
days = parseInt(total);
total -= days;
total *= 24.0;
hours = parseInt(total);
total -= hours;
total *= 60.0;
minutes = parseInt(total);
total -= minutes;
total *= 60;
seconds = parseInt(total);
} else {
timer.callbacks.onEnd();
timer.stop();
timer.base.isEnd = true;
}
return {
days: {
amount: days,
max: Infinity,
className: 'days'
},
hours: {
amount: hours,
max: 24,
className: 'hours'
},
minutes: {
amount: minutes,
max: 60,
className: 'minutes'
},
seconds: {
amount: seconds,
max: 60,
className: 'seconds'
}
}
};
var transformCountToArray = function (count, multilpeBlocks) {
if (typeof count === 'object') {
for (var unit in count) {
if (count.hasOwnProperty(unit)) {
count[unit].amount = count[unit].amount.toString();
if (count[unit].amount.length < 2) {
count[unit].amount = '0' + count[unit].amount;
}
if (multilpeBlocks) {
count[unit].amount = count[unit].amount.split('');
} else {
count[unit].amount = [count[unit].amount];
}
}
}
}
return count;
};
var getTimeZone = function (string) {
var hours, minutes;
var number = string.replace(/\D/g, '');
var digit = string.replace(/[^+-]/g, '');
var multiplier = digit === '-' ? (-1) : 1;
if (number.length >= 3) {
hours = Number(number.substr(0, number.length - 2));
minutes = Number(number.substr(number.length - 2, 2));
} else {
hours = Number(number);
minutes = 0;
}
return (hours + minutes/60) * multiplier;
};
var setTimerEndFromString = function (timer, endTimeString) {
var timerDate = {};
var timerEnd = endTimeString.split(' ');
var endTime;
var timeExp = /^([0-1]\d|2[0-3])(:[0-5]\d){1,2}$/;
var dateExp = /(0[1-9]|[12][0-9]|3[01])[- /.](0[1-9]|1[012])[- /.](19|20)\d\d/;
var zoneExp = /(UTC|GMT)[+-](\d{1,2}([:,.]?\d{2})?)/;
for (var i = 0; i < timerEnd.length; i++) {
if (timerEnd[i].match(timeExp)) {
timerDate.time = timerEnd[i].split(':');
} else if (timerEnd[i].match(dateExp)) {
timerDate.date = timerEnd[i].split('.');
} else if (timerEnd[i].match(zoneExp)) {
timer.base.timezone = getTimeZone(timerEnd[i]);
} else {
console.log('Wrong end time.');
}
}
timerDate.year = parseInt(timerDate.date[2]) || 0;
timerDate.month = parseInt(timerDate.date[1]) - 1 || 0;
timerDate.day = parseInt(timerDate.date[0]) || 0;
timerDate.hours = parseInt(timerDate.time[0]) || 0;
timerDate.minutes = parseInt(timerDate.time[1]) || 0;
timerDate.seconds = parseInt(timerDate.time[2]) || 0;
timerDate.miliseconds = parseInt(timerDate.time[3]) || 0;
endTime = Date.UTC(timerDate.year, timerDate.month, timerDate.day, timerDate.hours, timerDate.minutes, timerDate.seconds, timerDate.miliseconds);
return endTime;
};
var createMarkup = function (timer) {
var countdown = timer.countdown;
var markup = {};
for (var unit in countdown) {
if (countdown.hasOwnProperty(unit)) {
var numberBlocks = '';
countdown[unit].amount.forEach(function (num) {
numberBlocks += numberContainer(timer, num);
});
markup.unit += '<div class="' + countdown[unit].className + ' psgTimer_unit">' + numberBlocks + '</div>';
}
}
markup.numbers = '<div class="psgTimer_numbers">' + markup.unit + '</div>';
markup.full = markup.numbers;
if (
timer.options.labels &&
timer.options.labels.days &&
timer.options.labels.hours &&
timer.options.labels.minutes &&
timer.options.labels.seconds
) {
var labels = timer.options.labels;
markup.labels = '<div class="psgTimer_labels">' +
'<div class="days">' + labels.days + '</div>' +
'<div class="hours">' + labels.hours + '</div>' +
'<div class="minutes">' + labels.minutes + '</div>' +
'<div class="seconds">' + labels.seconds + '</div>' +
'</div>';
markup.full = markup.numbers + markup.labels;
} else {
markup.full = markup.numbers;
}
return markup.full;
};
var numberContainer = function (timer, num) {
var markup = '',
data = 'data-number="' + num + '"';
var numberBlock = '<div class="number" ' + data + '>' + num + '</div>';
if (timer.options.animation === 'fade') {
markup = '<div>' + numberBlock + '</div>';
} else {
markup = numberBlock;
}
return markup;
};
var setQueries = function (timer) {
var countdown = timer.countdown,
query = {};
for (var unit in countdown) {
if (countdown.hasOwnProperty(unit)) {
query[unit] = timer.container.find(numberSelector(timer, countdown[unit].className));
}
}
return query;
};
var numberSelector = function (timer, className) {
var selector = '';
if (timer.options.animation === 'fade') {
selector = '.' + className + ' .number';
} else {
selector = '.' + className + ' .number';
}
return selector;
};
var updateCounter = function (timer) {
timer.callbacks.onChangeStart();
timer.countdown = transformCountToArray(getCurrentCountDown(timer), timer.options.multilpeBlocks);
for (var unit in timer.countdown) {
if (timer.countdown.hasOwnProperty(unit)) {
timer.countdown[unit].amount.forEach(function (number, index) {
if (timer.query[unit][index].getAttribute('data-number') !== number) {
aminate(timer.query[unit][index], number, timer.options.animation);
}
});
}
}
timer.callbacks.onChangeEnd();
};
var aminate = function (el, value, animationType) {
var $el = $(el);
$el.attr('data-number', value);
if (animationType === 'fade') {
animation.fade($el, value);
} else {
$el.html(value);
}
};
var animation = {
fade: function ($el, value) {
var animDuration = 350;
$el.css({
'transition': 'opacity ' + animDuration + 'ms',
'opacity': '0'
});
setTimeout(function () {
$el.html(value).css('opacity', 1);
}, animDuration + 10);
}
};
window.PsgTimer = PsgTimer;
})();
.psgTimer{display:table;margin:0 auto 30px auto;font-size:0;font-family:'Roboto', sans-serif}.psgTimer_numbers>div,.psgTimer_labels>div{display:inline-block;font-size:0;width:124px;text-align:center}.psgTimer_numbers>div{position:relative}.psgTimer_numbers>div:after{content:":";line-height:60px;height:60px;display:block;font-weight:bold;font-size:24px;color:#21272C;position:absolute;top:0;right:-4px}.psgTimer_numbers>div:last-child:after{content:none}.psgTimer_numbers>div>div{display:inline-block;vertical-align:top;width:44px;height:60px;line-height:60px;background:#21272C;box-shadow:0px 4px 8px rgba(0,0,0,0.2);border-radius:6px;font-weight:bold;font-size:24px;text-align:center;color:#FFD631}.psgTimer_numbers>div>div:first-child{margin-right:5px}.psgTimer_labels>div{padding-top:5px !important;font-size:12px;line-height:18px;text-transform:uppercase;letter-spacing:1.2px;color:#21272C}#media screen and (max-width: 640px){.psgTimer_numbers>div,.psgTimer_labels>div{width:74px}.psgTimer_numbers>div{position:relative}.psgTimer_numbers>div:after{line-height:40px;height:40px;font-size:16px;right:-2px}.psgTimer_numbers>div div{width:26px;height:40px;line-height:40px;font-size:16px}.psgTimer_numbers>div div:first-child{margin-right:2px}.psgTimer_labels>div{font-size:10px;line-height:16px}}
<!doctype html>
<html lang="en">
<head>
</head>
<body>
<div class="container">
<div id="firstTimer"></div>
</div>
<script>
document.addEventListener('DOMContentLoaded', function () {
var timer = new PsgTimer({
selector: '#firstTimer',
currentDateTime: Date.UTC(2018, 0, 26, 12, 0, 0),
endDateTime: Date.UTC(2018, 0, 26, 12, 5, 0),
multilpeBlocks: true,
animation: 'fade',
labels: {
days: 'Days',
hours: 'Hours',
minutes: 'minutes',
seconds: 'seconds'
},
callbacks: {
onInit: function () {
console.log('Hello world!');
}
}
});
})
</script>
<script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="sha384-nvAa0+6Qg9clwYCGGPpDQLVpLNn0fRaROjHqs13t4Ggj3Ez50XnGQqc/r8MhnRDZ" crossorigin="anonymous"></script>
</body>
</html>
You can take the reference from psgTimer library
https://www.jqueryscript.net/time-clock/psg-countdown-timer.html

Displaying BBOX hash in URL

I think I'm doing something wrong in the variables or syntax... i don't know, help me to correct my code. (I'm using Leaflet for the map show)
Desired Behavior
The user should be able to see the BBOX entering the coordinates into the URL, for example:
.com/#013.0,052.0,013.5,052.5
I only care that the BBOX is shown, I don't care that the URL coordinates change when zooming or moving around the map.
My HTML
<!DOCTYPE html>
<html>
<header>
<link rel="stylesheet" href="style.css" />
<link
rel="stylesheet"
href="https://unpkg.com/leaflet#1.9.3/dist/leaflet.css"
integrity="sha256-kLaT2GOSpHechhsozzB+flnD+zUyjE2LlfWPgU04xyI="
crossorigin=""
/>
<script
src="https://unpkg.com/leaflet#1.9.3/dist/leaflet.js"
integrity="sha256-WBkoXOwTeyKclOHuWtc+i2uENFpDZ9YPdf5Hf+D7ewM="
crossorigin=""
></script>
</header>
<body>
<div id="map"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script src="https://unpkg.com/leaflet#1.0.1/dist/leaflet.js"></script>
<script src="leaflet-hash.js"></script>
<script>
var map = L.map("map").setView([42, 12], 4);
// var hash = new L.hash(map);
var urlhash = window.location.hash.substring(1).split("/");
var boundingBox = "";
L.tileLayer("https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", {
maxZoom: 22,
minZoom: 1,
continuousWorld: false,
noWrap: false,
attribution:
'Data by OpenStreetMap, under ODbL.',
detectRetina: false,
}).addTo(map);
var bboxField = L.control({
position: "bottomleft",
});
bboxField.onAdd = function (map) {
//create div container for control
var div = L.DomUtil.create("div", "myButtonBar");
//prevent mouse events from propagating through to the map
L.DomEvent.disableClickPropagation(div);
//create custom radio buttons
div.innerHTML =
'BBOX (Left (LON) ,Bottom (LAT), Right (LON), Top (LAT), comma separated, with or without decimal point):<br><input type="text" id="bbox_field"/><button id="setDimensions">Display BBOX</button><button id="remove">Remove</button>';
return div;
};
bboxField.addTo(map);
$(".myButtonBar").css("font-weight", "bold");
if (urlhash[0] !== "") {
$("#bbox_field").val(urlhash[0]);
draw_bbox(urlhash[0]);
}
function draw_bbox(box) {
var myarray = box.split(",");
var bounds = [
[myarray[1], myarray[0]],
[myarray[3], myarray[2]],
];
boundingBox = L.rectangle(bounds, { color: "#ff7800", weight: 1 });
map.removeLayer(boundingBox);
boundingBox.addTo(map);
map.fitBounds(boundingBox.getBounds());
map.setZoom(map.getZoom() - 1);
}
$("#setDimensions").click(function () {
draw_bbox($("#bbox_field").val());
});
$("#bbox_field").keyup(function (event) {
if (event.keyCode === 13) {
$("#setDimensions").click();
}
});
// console.log(bbox)
$("#remove").click(function () {
map.removeLayer(boundingBox);
});
</script>
</body>
</html>
Leaflet Hash Plugin Code
(function(window) {
var HAS_HASHCHANGE = (function() {
var doc_mode = window.documentMode;
return ('onhashchange' in window) &&
(doc_mode === undefined || doc_mode > 7);
})();
L.hash = function(map) {
this.onHashChange = L.Util.bind(this.onHashChange, this);
if (map) {
this.init(map);
}
};
L.hash.parseHash = function(hash) {
if(hash.indexOf('#') === 0) {
hash = hash.substr(1);
}
var args = hash.split("/");
if (args.length == 3) {
var zoom = parseInt(args[0], 10),
lat = parseFloat(args[1]),
lon = parseFloat(args[2]);
if (isNaN(zoom) || isNaN(lat) || isNaN(lon)) {
return false;
} else {
return {
center: new L.LatLng(lat, lon),
zoom: zoom
};
}
} else {
return false;
}
};
L.hash.formatHash = function(map) {
var center = map.getCenter(),
zoom = map.getZoom(),
precision = Math.max(0, Math.ceil(Math.log(zoom) / Math.LN2));
return "#" + [zoom,
center.lat.toFixed(precision),
center.lng.toFixed(precision)
].join("/");
},
L.hash.prototype = {
map: null,
lastHash: null,
parseHash: L.hash.parseHash,
formatHash: L.hash.formatHash,
init: function(map) {
this.map = map;
// reset the hash
this.lastHash = null;
this.onHashChange();
if (!this.isListening) {
this.startListening();
}
},
removeFrom: function(map) {
if (this.changeTimeout) {
clearTimeout(this.changeTimeout);
}
if (this.isListening) {
this.stopListening();
}
this.map = null;
},
onMapMove: function() {
// bail if we're moving the map (updating from a hash),
// or if the map is not yet loaded
if (this.movingMap || !this.map._loaded) {
return false;
}
var hash = this.formatHash(this.map);
if (this.lastHash != hash) {
location.replace(hash);
this.lastHash = hash;
}
},
movingMap: false,
update: function() {
var hash = location.hash;
if (hash === this.lastHash) {
return;
}
var parsed = this.parseHash(hash);
if (parsed) {
this.movingMap = true;
this.map.setView(parsed.center, parsed.zoom);
this.movingMap = false;
} else {
this.onMapMove(this.map);
}
},
// defer hash change updates every 100ms
changeDefer: 100,
changeTimeout: null,
onHashChange: function() {
// throttle calls to update() so that they only happen every
// `changeDefer` ms
if (!this.changeTimeout) {
var that = this;
this.changeTimeout = setTimeout(function() {
that.update();
that.changeTimeout = null;
}, this.changeDefer);
}
},
isListening: false,
hashChangeInterval: null,
startListening: function() {
this.map.on("moveend", this.onMapMove, this);
if (HAS_HASHCHANGE) {
L.DomEvent.addListener(window, "hashchange", this.onHashChange);
} else {
clearInterval(this.hashChangeInterval);
this.hashChangeInterval = setInterval(this.onHashChange, 50);
}
this.isListening = true;
},
stopListening: function() {
this.map.off("moveend", this.onMapMove, this);
if (HAS_HASHCHANGE) {
L.DomEvent.removeListener(window, "hashchange", this.onHashChange);
} else {
clearInterval(this.hashChangeInterval);
}
this.isListening = false;
}
};
L.hash = function(map) {
return new L.hash(map);
};
L.map.prototype.addHash = function() {
this._hash = L.hash(this);
};
L.map.prototype.removeHash = function() {
this._hash.removeFrom();
};
})(window);

How to update the markers in real-time using ajax

May I know how do I update the location in real-time, if the location value has been changed. The current code is what I used to retrieve the data from the database. I tried many solutions such as set interval or timeout but that did not help me in solving the problem.
$.ajax({
type: "GET",
url: ')',
success: function (data, status, xhr) {
for (var i = 0; i < data.Table.length; i++) {
if (createdA === false) {
for (var a = 0; a <= 200; a++) {
a1 = data.Table[i].Latitude;
a2 = data.Table[i].Longitude;
a5 = data.Table[i].DeviceImei;
}
createMarkerA([a1, a2]);
shownA = true;
createdA = true;
setInterval(groupOne(), 10000);
}
else if (shownA === false) {
for (var a3 = 0; a3 < 200; a3++) {
showMarker(markersA[a3]);
shownA = true;
}
}
else if (shownA === true) {
for (var a4 = 0; a4 < 200; a4++) {
hideMarker(markersA[a4]);
shownA = false;
}
}
}
},
error: function (xhr) {
alert(xhr.responseText);
}
});
//This is the code to initialize the map
//centers the map at using the 2 points as reference
var center = L.bounds([, ], [, ]).getCenter();
//it sets the map to the pre-defined div container
var map = L.map('test_map').setView([center.x, center.y], 12);
var basemap = L.tileLayer('https://maps-{s}.onemap.sg/v3/Original/{z}/{x}/{y}.png', {
detectRetina: true,
maxZoom: 20,
minZoom: 11
});
basemap.addTo(map);
var markersLayer = new L.LayerGroup(); //layer contain searched elements
map.addLayer(markersLayer);
var controlSearch = new L.Control.Search({
position: 'topright',
layer: markersLayer,
initial: false,
zoom: 18,
marker: false
})
map.addControl(controlSearch);
L.circle([, ], 50, { color: '#DA2E2E', opacity: 2, fillColor: 'blue', fillOpacity: .3 }).bindPopup('').addTo(map);
L.circle([, ], 50, { color: '#DA2E2E', opacity: 2, fillColor: 'blue', fillOpacity: .3 }).bindPopup('').addTo(map);
// The code to initialize the markers
var markers = [];
function pushMarker(marker) {
markers.push(marker);
}
function createMarker(data) {
var marker = new L.marker([data[0], data[1]]);
pushMarker(marker);
showMarker(marker);
}
//General Functions
function hideMarker(marker) {
map.removeLayer(marker);
}
function showMarker(marker) {
map.addLayer(marker);
}
var createdA = false;
var shownA = false;
var markersA = [];
var a1;
var a2;
var a5;
function createMarkerA(data) {
$.ajax({
type: "GET",
url: '',
success: function (data, status, xhr) {
for (var i = 0; i < 4; i++) {
var customPopup = 'Coordinates X: ' + data.Table[i].Latitude + '</br>Coordinates Z: ' + data.Table[i].Longitude + '</br>Station: ' + data.Table[i].Station + ' </br> Box: ' + data.Table[i].Box + '</br > Timestamp: ' + data.Table[i].LocationSend;
var customOptions =
{
'maxWidth': '500',
'className': 'custom'
};
var marker = L.marker(new L.LatLng(data.Table[i].Latitude, data.Table[i].Longitude, data.Table[i].Station));
marker.bindPopup(customPopup, customOptions);
pushMarker(marker);
showMarker(marker);
}
},
error: function (xhr) {
alert(xhr.responseText);
}
});
}
function groupOne() {
$.ajax({
type: "GET",
url: '',
success: function (data, status, xhr) {
for (var i = 0; i < 4; i++) {
if (createdA === false) {
for (var a = 0; a < 200; a++) {
a1 = data.Table[i].Latitude;
a2 = data.Table[i].Longitude;
}
createMarkerA([a1, a2]);
shownA = true;
createdA = true;
}
else if (shownA === false) {
for (var a3 = 0; a3 <= 4; a3++) {
showMarker(markersA[a3]);
shownA = true;
}
}
else if (shownA === true) {
for (var a4 = 0; a4 <= 4; a4++) {
hideMarker(markersA[a4]);
shownA = false;
}
}
}
},
error: function (xhr) {
alert(xhr.responseText);
}
});
Just I am taking some static points to change the point without refresh the page
<html>
<head>
<title>Leaflet geolocate example</title>
<link rel="stylesheet" href="https://npmcdn.com/leaflet#0.7.7/dist/leaflet.css" />
<script src="https://npmcdn.com/leaflet#0.7.7/dist/leaflet.js"></script>
<script language="javascript">
var map;
var markers = [];
var center = L.bounds([40.712, -74.227], [40.774, -74.125]).getCenter();
//alert(center.x);
function init() {
map = new L.Map('map');
L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '© OpenStreetMap contributors',
maxZoom: 18
}).addTo(map);
map.attributionControl.setPrefix(''); // Don't show the 'Powered by Leaflet' text.
var seconds = 0.005;
map.setView(new L.LatLng(center.x, center.y), 12);
setmarkers(seconds);
var myTimer = setInterval(function () {
center.x = center.x + seconds + 0.01;
center.y = center.y + seconds + 0.01;
getmarkers(seconds);
seconds = seconds + 0.01;
}, 2000);
}
function getmarkers(v) {
//alert(v);
for (var i = 0; i < 10; i++) {
var location = new L.LatLng(center.x + i * v, center.y + i * v);
markers[i].setLatLng(location);
markers[i].addTo(map);
}
}
function setmarkers(v) {
alert(v);
var radius = 30;
for (var i = 0; i < 10; i++) {
var location = new L.LatLng(center.x + i * v, center.y + i * v)
var mark = L.marker(location);
markers.push(mark);
}
}
function onLocationFound(e) {
var radius = e.accuracy / 2;
radius = 30;
var location = e.latlng
L.marker(location).addTo(map)
L.circle(location, radius).addTo(map);
alert(location.lat);
alert(location.lng);
addinlocations(location);
}
function onLocationError(e) {
alert(e.message);
}
function getLocationLeaflet() {
map.on('locationfound', onLocationFound);
map.on('locationerror', onLocationError);
map.locate({ setView: true, maxZoom: 16 });
}
function pushMarker(marker) {
markers.push(marker);
}
function addinlocations(pot) {
for (var i = 0; i < 10; i++) {
var nmarker = new L.LatLng(pot.lat + i * 0.5, pot.lng * 0.5);
var radius = 20;
var location = nmarker
L.marker(location).addTo(map)
L.circle(location, radius).addTo(map);
// pushMarker(nmarker);
}
}
</script>
</head>
<body onLoad="javascript:init();">
<div id="map" style="height: 500px"></div>
<input type="button" value="Locate me!" onClick="javascript:getLocationLeaflet();">
</body>
</html>
<html>
<head>
<title>Leaflet geolocate example</title>
<link rel="stylesheet" href="https://npmcdn.com/leaflet#0.7.7/dist/leaflet.css" />
<script src="https://npmcdn.com/leaflet#0.7.7/dist/leaflet.js"></script>
<script language="javascript">
var map;
var markers = [];
var createdA = false;
var shownA = false;
var markersA = [];
var markersA = [];
var a1;
var a2;
var a5;
var center = L.bounds([39.61, -105.02], [39.77, -105.23]).getCenter();
function init() {
map = new L.Map('test_map').setView(new L.LatLng(center.x, center.y), 12);;
var basemap = L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '© OpenStreetMap contributors',
detectRetina: true,
maxZoom: 20,
minZoom: 9
});
basemap.addTo(map);
var data = [];
var d1 = { Table: { Latitude: 39.61, Longitude: -105.02, Station: 'This is Littleton, CO.', Box: 'Box', LocationSend: 'testing1' } };
var d2 = { Table: { Latitude: 39.74, Longitude: -104.99, Station: 'This is Denver, CO.', Box: 'Box', LocationSend: 'testing2' } };
var d3 = { Table: { Latitude: 39.73, Longitude: -104.8, Station: 'This is Aurora, CO.', Box: 'Box', LocationSend: 'testing3' } };
var d4 = { Table: { Latitude: 39.733, Longitude: -104.821, Station: 'This is Littleton, CO.', Box: 'Box', LocationSend: 'testing4' } };
var d5 = { Table: { Latitude: 39.742, Longitude: -105.002, Station: 'This is Denver, CO.', Box: 'Box', LocationSend: 'testing5' } };
var d6 = { Table: { Latitude: 39.734, Longitude: -104.811, Station: 'This is Aurora, CO.', Box: 'Box', LocationSend: 'testing6' } };
data.push(d1);
data.push(d2);
data.push(d3);
data.push(d4);
data.push(d5);
data.push(d6);
markersA.push(L.marker(new L.LatLng(39.61, -105.02)));
markersA.push(L.marker(new L.LatLng(39.74, -104.99)));
markersA.push(L.marker(new L.LatLng(39.73, -104.8)));
map.addLayer(markersA[0]);
map.addLayer(markersA[1]);
map.addLayer(markersA[2]);
var myTimer = setInterval(function () {
groupOne(data);
}, 2000);
var markersLayer = L.layerGroup(markersA);
map.addLayer(markersLayer);
var controlSearch = new L.Control.Search({
position: 'topright',
layer: markersLayer,
initial: false,
zoom: 15,
marker: false
})
map.addControl(controlSearch);
}
function pushMarker(marker) {
markers.push(marker);
}
function createMarker(data) {
var marker = new L.marker([data[0], data[1]]);
pushMarker(marker);
}
function showMarker(marker) {
map.addLayer(marker);
}
function hideMarker(marker, i) {
var locate = marker.getLatLng();
markersA[i].setLatLng(locate);
}
function createMarkerA(data) {
var valid = true;
for (var i = 0; i < data.length; i++) {
var customPopup = 'Coordinates X: ' + data[i].Table.Latitude + '</br>Coordinates Z: ' + data[i].Table.Longitude + '</br>Station: ' + data[i].Table.Station + ' </br> Box: ' + data[i].Table.Box + '</br > Timestamp: ' + data[i].Table.LocationSend;
//var customOptions =
// {
// 'maxWidth': '500',
// 'className': 'custom'
// };
//var marker = L.marker(new L.LatLng(data[i].Table.Latitude, data[i].Table.Longitude, data[i].Table.Station));
var marker = L.marker(new L.LatLng(data[i].Table.Latitude, data[i].Table.Longitude));
marker.bindPopup(customPopup);
pushMarker(marker);
}
}
function groupOne(data) {
//$.ajax({
// type: "GET",
// url: '',
// data:data,
// success: function (data, status, xhr) {
if (createdA == false) {
createMarkerA(data);
shownA = true;
createdA = true;
}
else if (shownA == false) {
for (var a = 0; a <= 2; a++) {
hideMarker(markers[a],a);
}
shownA = true;
}
else if (shownA == true) {
for (var aa = 3;aa<=5;aa++) {
var i = aa - 3;
hideMarker(markers[aa], i);
}
shownA = false;
}
//}
//,
//error: function (xhr) {
// alert(xhr.responseText);
//}
//});
}
</script>
</head>
<body onLoad="javascript:init();">
<div id="test_map" style="height: 500px"></div>
</body>
</html>
<html>
<head>
<title>Leaflet geolocate example</title>
<link rel="stylesheet" href="https://unpkg.com/leaflet#1.3.0/dist/leaflet.css" />
<link rel="stylesheet" href="styles.css">
<script language="javascript">
var markers = [];
var createdA = false;
var shownA = false;
var markersA = [];
var markersA = [];
var a1;
var a2;
var a5;
var data1 = [];
var center = L.bounds([1.56073, 104.11475], [1.16, 103.502]).getCenter();
function init() {
map = new L.Map('test_map').setView(new L.LatLng(center.x, center.y), 12);;
var basemap = L.tileLayer('https://maps-
{s}.onemap.sg/v3/Original/{z}/{x}/{y}.png', {
attribution: '<img src="https://docs.onemap.sg/maps/images/oneMap64-
01.png" style="height:20px;width:20px;"/> New OneMap | Map data © contributors,
Singapore Land Authority',
detectRetina: true,
maxZoom: 20,
minZoom: 9
});
basemap.addTo(map);
$.ajax({
type: "GET",
url: '',
success: function (data, status, xhr) {
for (var i = 0; i < data.Table.length; i++) {
for (var s = 1; s < data.Table.length; s++) {
var d1 = { Table: { Latitude: data.Table[i].Latitude,
Longitude: data.Table[i].Longitude, Station: 'This is Littleton, CO.', Box:
'Box', LocationSend: 'testing1' } };
var d2 = { Table: { Latitude: data.Table[s].Latitude,
Longitude: data.Table[s].Longitude, Station: 'This is Denver, CO.', Box: 'Box',
LocationSend: 'testing2' } };
data1.push(d1);
data1.push(d2);
markersA.push(L.marker(new L.LatLng(data.Table[i].Latitude,
data.Table[i].Longitude)));
markersA.push(L.marker(new L.LatLng(data.Table[s].Latitude,
data.Table[s].Longitude)));
map.addLayer(markersA[0]);
map.addLayer(markersA[1]);
}
}
},
error: function (xhr) {
alert(xhr.responseText);
}
});
var myTimer = setInterval(function () {
groupOne(data1);
}, 2000);
}
function pushMarker(marker) {
markers.push(marker);
}
function createMarker(data1) {
var marker = new L.marker([data1[0], data1[1]]);
pushMarker(marker);
}
function showMarker(marker) {
map.addLayer(marker);
}
function hideMarker(marker, i) {
var locate = marker.getLatLng();
markersA[i].setLatLng(locate);
}
function createMarkerA(data1) {
var valid = true;
for (var i = 0; i < data1.length; i++) {
var customPopup = 'Coordinates X: ' + data1[i].Table.Latitude +
'</br>Coordinates Z: ' + data1[i].Table.Longitude + '</br>Station: ' +
data1[i].Table.Station + ' </br> Box: ' + data1[i].Table.Box + '</br >
Timestamp: ' + data1[i].Table.LocationSend;
//var customOptions =
// {
// 'maxWidth': '500',
// 'className': 'custom'
// };
//var marker = L.marker(new L.LatLng(data[i].Table.Latitude,
data[i].Table.Longitude, data[i].Table.Station));
var marker = L.marker(new L.LatLng(data1[i].Table.Latitude,
data1[i].Table.Longitude));
marker.bindPopup(customPopup);
pushMarker(marker);
}
}
function groupOne(data) {
//$.ajax({
// type: "GET",
// url: '',
// data:data,
// success: function (data, status, xhr) {
if (createdA == false) {
createMarkerA(data);
shownA = true;
createdA = true;
}
else if (shownA == false) {
for (var a = 0; a <= 2; a++) {
hideMarker(markers[a], a);
}
shownA = true;
}
else if (shownA == true) {
for (var aa = 3; aa <= 5; aa++) {
var i = aa - 3;
hideMarker(markers[aa], i);
}
shownA = false;
}
//}
//,
//error: function (xhr) {
// alert(xhr.responseText);
//}
//});
}
</script>
</head>
<body onLoad="javascript:init();">
<div id='test_map' style=" height: 800px; "></div>

Tiled Map Editor using Phaser to make a Maze

I'm trying to create a Maze game using the Tiled map editor and Phaser. I am using this tutorial as a base: http://phaser.io/tutorials/coding-tips-005
But my map is not showing in my browser. I have created a tilemap and exported it as a json file. And there is an error in the code saying Uncaught ReferenceError: Phaser is not defined". What am I missing or doing incorrectly?
This is the code:
<!DOCTYPE HTML>
<html>
<head>
<title>Maze Game</title>
<meta charset="utf-8">
<script src="//cdn.jsdelivr.net/phaser/2.2.2/phaser.min.js"></script>
</head>
<body>
<div id="game"></div>
<script type="text/javascript">
var game = new Phaser.Game(640, 480, Phaser.AUTO, 'game');
var PhaserGame = function (game) {
this.map = null;
this.layer = null;
this.car = null;
this.safetile = 1;
this.gridsize = 32;
this.speed = 150;
this.threshold = 3;
this.turnSpeed = 150;
this.marker = new Phaser.Point();
this.turnPoint = new Phaser.Point();
this.directions = [ null, null, null, null, null ];
this.opposites = [ Phaser.NONE, Phaser.RIGHT, Phaser.LEFT, Phaser.DOWN, Phaser.UP ];
this.current = Phaser.UP;
this.turning = Phaser.NONE;
};
PhaserGame.prototype = {
init: function () {
this.physics.startSystem(Phaser.Physics.ARCADE);
},
preload: function () {
// We need this because the assets are on Amazon S3
// Remove the next 2 lines if running locally
this.load.baseURL = 'http://files.phaser.io.s3.amazonaws.com/codingtips/issue005/';
this.load.crossOrigin = 'anonymous';
this.load.tilemap('map', 'assets/samplemaze.json', null, Phaser.Tilemap.TILED_JSON);
this.load.image('tiles', 'assets/tiles.png');
this.load.image('car', 'assets/car.png');
// Note: Graphics are Copyright 2015 Photon Storm Ltd.
},
create: function () {
this.map = this.add.tilemap('map');
this.map.addTilesetImage('tiles', 'tiles');
this.layer = this.map.createLayer('Tile Layer 1');
this.map.setCollision(20, true, this.layer);
this.car = this.add.sprite(48, 48, 'car');
this.car.anchor.set(0.5);
this.physics.arcade.enable(this.car);
this.cursors = this.input.keyboard.createCursorKeys();
this.move(Phaser.DOWN);
},
checkKeys: function () {
if (this.cursors.left.isDown && this.current !== Phaser.LEFT)
{
this.checkDirection(Phaser.LEFT);
}
else if (this.cursors.right.isDown && this.current !== Phaser.RIGHT)
{
this.checkDirection(Phaser.RIGHT);
}
else if (this.cursors.up.isDown && this.current !== Phaser.UP)
{
this.checkDirection(Phaser.UP);
}
else if (this.cursors.down.isDown && this.current !== Phaser.DOWN)
{
this.checkDirection(Phaser.DOWN);
}
else
{
// This forces them to hold the key down to turn the corner
this.turning = Phaser.NONE;
}
},
checkDirection: function (turnTo) {
if (this.turning === turnTo || this.directions[turnTo] === null || this.directions[turnTo].index !== this.safetile)
{
// Invalid direction if they're already set to turn that way
// Or there is no tile there, or the tile isn't index a floor tile
return;
}
// Check if they want to turn around and can
if (this.current === this.opposites[turnTo])
{
this.move(turnTo);
}
else
{
this.turning = turnTo;
this.turnPoint.x = (this.marker.x * this.gridsize) + (this.gridsize / 2);
this.turnPoint.y = (this.marker.y * this.gridsize) + (this.gridsize / 2);
}
},
turn: function () {
var cx = Math.floor(this.car.x);
var cy = Math.floor(this.car.y);
// This needs a threshold, because at high speeds you can't turn because the coordinates skip past
if (!this.math.fuzzyEqual(cx, this.turnPoint.x, this.threshold) || !this.math.fuzzyEqual(cy, this.turnPoint.y, this.threshold))
{
return false;
}
this.car.x = this.turnPoint.x;
this.car.y = this.turnPoint.y;
this.car.body.reset(this.turnPoint.x, this.turnPoint.y);
this.move(this.turning);
this.turning = Phaser.NONE;
return true;
},
move: function (direction) {
var speed = this.speed;
if (direction === Phaser.LEFT || direction === Phaser.UP)
{
speed = -speed;
}
if (direction === Phaser.LEFT || direction === Phaser.RIGHT)
{
this.car.body.velocity.x = speed;
}
else
{
this.car.body.velocity.y = speed;
}
this.add.tween(this.car).to( { angle: this.getAngle(direction) }, this.turnSpeed, "Linear", true);
this.current = direction;
},
getAngle: function (to) {
// About-face?
if (this.current === this.opposites[to])
{
return "180";
}
if ((this.current === Phaser.UP && to === Phaser.LEFT) ||
(this.current === Phaser.DOWN && to === Phaser.RIGHT) ||
(this.current === Phaser.LEFT && to === Phaser.DOWN) ||
(this.current === Phaser.RIGHT && to === Phaser.UP))
{
return "-90";
}
return "90";
},
update: function () {
this.physics.arcade.collide(this.car, this.layer);
this.marker.x = this.math.snapToFloor(Math.floor(this.car.x), this.gridsize) / this.gridsize;
this.marker.y = this.math.snapToFloor(Math.floor(this.car.y), this.gridsize) / this.gridsize;
// Update our grid sensors
this.directions[1] = this.map.getTileLeft(this.layer.index, this.marker.x, this.marker.y);
this.directions[2] = this.map.getTileRight(this.layer.index, this.marker.x, this.marker.y);
this.directions[3] = this.map.getTileAbove(this.layer.index, this.marker.x, this.marker.y);
this.directions[4] = this.map.getTileBelow(this.layer.index, this.marker.x, this.marker.y);
this.checkKeys();
if (this.turning !== Phaser.NONE)
{
this.turn();
}
},
render: function () {
// Un-comment this to see the debug drawing
for (var t = 1; t < 5; t++)
{
if (this.directions[t] === null)
{
continue;
}
var color = 'rgba(0,255,0,0.3)';
if (this.directions[t].index !== this.safetile)
{
color = 'rgba(255,0,0,0.3)';
}
if (t === this.current)
{
color = 'rgba(255,255,255,0.3)';
}
this.game.debug.geom(new Phaser.Rectangle(this.directions[t].worldX, this.directions[t].worldY, 32, 32), color, true);
}
this.game.debug.geom(this.turnPoint, '#ffff00');
}
};
game.state.add('Game', PhaserGame, true);
</script>
<img src="http://files.phaser.io.s3.amazonaws.com/codingtips/issue005/phaser-tips-header1.png" title="Phaser Coding Tips Weekly" style="margin-top: 8px" />
</body>
</html>
Thank you so much! I'm pretty new to programming so any feedback would be very useful!
You might be missing "http:" or "https:" in your script tag's src attribute. If so, then the phaser.min.js file isn't being included in your page and could result in undefined references.

Cocos2d html5 cannot set property src of null

Getting the subject error when going through: http://www.cocos2d-x.org/reference/html5-js/symbols/cc.html
Note that I am using the 2.1.2 beta release, so I know there will be differences in the tutorial. Here's the code i have so far:
(function() {
var AppLayer = cc.LayerColor.extend({
init: function() {
this._super(new cc.Color4B(0, 0, 0, 255));
var size = cc.Director.getInstance().getWinSize();
this._jetSprite = new JetSprite();
this.setTouchEnabled(true);
this.setKeyboardEnabled(true);
this.setPosition(new cc.Point(0, 0));
this.addChild(this._jetSprite);
this._jetSprite.setPosition(new cc.Point(size.width / 2, size.height / 2));
this._jetSprite.scheduleUpdate();
this.schedule(this.update);
return true;
},
_jetSprite: null,
onEnter: function() {
this._super();
},
onKeyDown: function(e) {
this._jetSprite.handleKey(e);
},
onKeyUp: function() {
},
onTouchesEnded: function(pTouch, pEvent) {
this._jetSprite.handleTouch(pTouch[0].getLocation());
},
onTouchesMoved: function(pTouch, pEvent) {
this._jetSprite.handleTouchMove(pTouch[0].getLocation());
},
update: function(dt) {
}
});
window.AppScene = cc.Scene.extend({
onEnter: function() {
this._super();
var layer = new AppLayer();
layer.init();
this.addChild(layer);
}
});
})();
var JetSprite = cc.Sprite.extend({
_currentRotation:0,
ctor: function() {
this.initWithFile("images/jet.png");
},
handleKey: function(e) {
if(e == cc.KEY.left) {
this._currentRotation--;
}
else if(e == cc.KEY.right) {
this._currentRotation++;
}
if(this._currentRotation < 0) {
this._currentRotation = 360;
}
if(this._currentRotation > 360) {
this._currentRotation = 0;
}
},
handleTouch: function(touchLocation) {
if(touchLocation.x < 300) {
this._currentRotation = 0;
}
else {
this._currentRotation = 180;
}
},
handleTouchMove: function(touchLocation) {
var angle = Math.atan2(touchLocation.x - 300, touchLocation.y - 300);
angle = angle * (180/Math.PI);
this._currentRotation = angle;
},
update: function(dt) {
this.setRotation(this._currentRotation);
}
});
Here's the error in more detail:
Uncaught TypeError: Cannot set property 'src' of null CCSprite.js:2209
cc.SpriteWebGL.cc.Node.extend.initWithTexture CCSprite.js:2209
(anonymous function) CCSprite.js:2161
Looks like the tutorial i was following was missing a line. The ctor function requires a this._super() so everything gets initialized correctly.
var JetSprite = cc.Sprite.extend({
_currentRotation:0,
ctor: function() {
this._super();
this.initWithFile("images/jet.png");
},

Categories