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>
Related
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
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);
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.
I am working on a visualisation that utilises a mapbox choropleth map and leafletjs markers. At the moment, I am struggling on getting the markers to merge together on zoom out at country level. I have tried reading the my code through but I have not been able to find a way to solve this issue.
Attached is my code for my map.
(function() {
window.petMap = {
map: '',
mapCenter: [36.19109202182454, -95.99853515625001],
tileUrl: 'https://api.mapbox.com/styles/v1/sourcetop/ck3yaryi60z7z1co7p7ttw4kf/tiles/256/{z}/{x}/{y}#2x?access_token=pk.eyJ1Ijoic291cmNldG9wIiwiYSI6ImNrM3lhYXMyazA2ZmczZ3FsbDM0aThhYnIifQ.eyPqNH3WmEFy8D1aw2vn6w',
mapAttribution: 'Map data © OpenStreetMap contributors',
bounds: [],
zoom: 5,
zoomLevel: 'country',
callbackUrl: URL.com
locationCallbackUrl: URL.com
dmaJsonUrl: URL.com
markers: {
profile: {},
conditions: {}
},
dataLevel: 'profile',
locationMarkes: {},
dmaMarkers: [],
dmaPoly: [],
progress: 0,
progressTimer: '',
initMap: function() {
this.mapZoomClass();
this.map = L.map('map', {
center: this.mapCenter,
zoom: 5,
zoomControl: false,
zoomDelta: 2,
trackResize: true,
wheelPxPerZoomLevel: 25,
scrollEnable: true
});
L.control.zoom({
position: 'bottomright'
}).addTo(this.map);
L.tileLayer(this.tileUrl, {
attribution: this.mapAttribution,
minZoom: 2,
maxZoom: 13
}).addTo(this.map);
this.getBounds();
this.getZoomLevel();
this.mapAction();
},
plotMap: function(dataLevel) {
this.progressBarInit();
this.dataLevel = dataLevel;
this.dataLevelFixer();
this.requestDataFromServer();
},
requestDataParams: function() {
return {
bounds: this.bounds,
zoom: this.zoom,
level: this.zoomLevel,
year: petMapFilters.year,
animal: Object.keys(window.petMapFilters.animal),
age: Object.keys(window.petMapFilters.age),
breeds: Object.keys(window.petMapFilters.breeds),
ailments: Object.keys(window.petMapFilters.ailments)
};
},
requestDataFromServer: function() {
$.ajax({
url : this.callbackUrl,
data: this.requestDataParams(),
})
.done(function(response) {
petMap.progressBarReset();
if(petMap.dataLevel == 'conditions') {
petMap.dataLevel = 'profile';
petMap.plotMarkers(response);
petMap.dataLevel = 'conditions';
}
petMap.plotMarkers(response);
})
.fail(function(jqXHR, textStatus) {
console.log('Request failed: ' + textStatus);
});
},
// Plot markers.
plotMarkers: function(response) {
this.clearmarkerLayer();
var color = window.petMapFilters.colors[this.dataLevel];
if(this.zoomLevel != 'state') {
this.initClusterMarker(color, this.dataLevel);
} else {
this.markers[petMap.dataLevel] = L.featureGroup();
}
var markerList = [];
response.forEach(function(data){
var count = petMap.getResultCount(data);
if(data.location != null && count) {
var icon = L.divIcon({
html: petMap.getMarkerHtml(count, color)
});
var marker = L.marker(
new L.LatLng(data.location[1], data.location[0]),
{icon: icon, zIndexOffset: 2000}
);
marker.count = count;
if(petMap.zoomLevel == 'state') {
marker.on('click', function(e) {
petMap.map.setView(e.latlng, 1);
});
petMap.markers[petMap.dataLevel].addLayer(marker);
} else {
markerList.push(marker);
}
}
});
if(this.zoomLevel != 'state') {
this.markers[this.dataLevel].addLayers(markerList);
}
this.map.addLayer(this.markers[this.dataLevel]);
},
// init cluster markers.
initClusterMarker: function(color, type) {
this.markers[type] = L.markerClusterGroup({
chunkedLoading: true,
spiderfyOnMaxZoom: true,
showCoverageOnHover: false,
iconCreateFunction: function(cluster) {
var markers = cluster.getAllChildMarkers();
var markerCount = 0;
markers.forEach(function(m){
markerCount = markerCount + m.count;
});
return new L.DivIcon({
html: petMap.getMarkerHtml(markerCount, color),
className: 'marker-type-cluster-' + (petMapFilters.colors.profile == color ? 'profile' : 'condition')
});
}
});
},
clearmarkerLayer: function() {
if(Object.keys(this.markers.profile).length && this.dataLevel == 'profile') {
this.markers.profile.clearLayers();
}
if(Object.keys(this.markers.conditions).length) {
this.markers.conditions.clearLayers();
}
},
/**********************************************************/
plotLocations: function() {
if(Object.keys(petMapFilters.locationSelected).length) {
for(var i in petMapFilters.locationSelected) {
if(typeof this.locationMarkes[i] == 'undefined') {
this.plotLocation(i);
}
}
}
},
removeLocationMarker: function(id) {
if(typeof this.locationMarkes[id] != 'undefined' && Object.keys(this.locationMarkes[id]).length) {
this.locationMarkes[id].clearLayers();
delete this.locationMarkes[id];
}
},
plotLocation: function(id) {
this.progressBarInit();
$.ajax({
url: this.locationCallbackUrl,
data: {
// bounds: this.bounds,
collection: id
}
})
.done(function(response) {
petMap.progressBarReset();
petMap.plotLocationMarkers(id, response);
})
.fail(function(jqXHR, textStatus) {
console.log('Request failed: ' + textStatus);
});
},
plotLocationMarkers: function(id, response) {
if(typeof this.locationMarkes[id] != 'undefined' && Object.keys(this.locationMarkes[id]).length) {
this.locationMarkes[id].clearLayers();
this.locationMarkes[id] = [];
}
this.initLocationClusterMarker(id);
var markerList = [];
response.forEach(function(data){
if(data.location != null) {
var marker = L.marker(new L.LatLng(data.location.coordinates[1], data.location.coordinates[0]), {icon: petMap.getLocationIcon(id, 'marker'), zIndexOffset: 1000}).bindPopup(petMap.getLocationPopup(data));
markerList.push(marker);
}
});
this.locationMarkes[id].addLayers(markerList);
},
initLocationClusterMarker: function(id) {
this.locationMarkes[id] = L.markerClusterGroup({
chunkedLoading: true,
spiderfyOnMaxZoom: true,
showCoverageOnHover: false,
iconCreateFunction: function(cluster) {
return petMap.getLocationIcon(id, 'cluster', cluster.getAllChildMarkers().length);
}
});
this.map.addLayer(this.locationMarkes[id]);
},
getLocationIcon: function(id, type, count) {
var sizeMap = {
'shop-marker': [16, 19],
'shop-cluster': [35, 40],
'clinic-marker': [18, 17],
'clinic-cluster': [38, 35],
};
var dt = id.split(':');
var icon = dt[0] == 'shop' ? 'shop-' + type + '.svg' : 'hospital-' + type + '.svg';
var anchor = dt[0] == 'shop' ? [-1, -10] : [0, -8];
if(type == 'cluster') {
return new L.DivIcon({
html: '<div class="location-marker location-type-' + dt[0] + '" tabindex="0">' + count + '</div>',
className: 'marker-type-cluster-location'
});
} else {
return L.icon({
iconUrl: 'images/' + icon,
iconSize: sizeMap[dt[0] + '-' + type],
popupAnchor: anchor,
className: 'location-single-marker'
});
}
},
getLocationPopup: function(data) {
var details = [];
if(typeof data.street != 'undefined') { details.push(data.street); }
if(typeof data.city != 'undefined') { details.push(data.city); }
if(typeof data.state != 'undefined') { details.push(data.state); }
if(typeof data.contact != 'undefined') { details.push(data.contact); }
details = details.join('<br/>');
if(details.length) {
details = '<div class="location">' + details + '</div>';
}
return '<div class="hospital-popup"><div class="color-red">' + data.name + '</div>' + details + '</div>';
},
/**********************************************************/
plotDmaData: function(op) {
if(op == 'add') {
if(!Object.keys(this.dmaMarkers).length) {
this.getDmaData();
} else {
this.map.addLayer(this.dmaMarkers);
this.map.addLayer(this.dmaPoly);
}
} else {
if(Object.keys(this.dmaMarkers).length) {
this.map.removeLayer(this.dmaMarkers);
this.map.removeLayer(this.dmaPoly);
}
}
},
getDmaData: function() {
$.getJSON(this.dmaJsonUrl, function(response) {
petMap.plotDmaMarkers(response);
});
},
plotDmaMarkers: function(response) {
this.dmaMarkers = L.featureGroup();
this.dmaPoly = L.geoJson(response, {
style: {
opacity: 0,
fillOpacity: 0
},
onEachFeature: function(feature, layer) {
var latlng = new L.LatLng(feature.properties.latitude, feature.properties.longitude);
var icon = petMap.getDmaMarkerIcon(feature.properties);
var marker = L.marker(latlng, {icon: icon, riseOnHover: true, riseOffset: 3000});
marker.data = feature.properties;
marker.layer = layer;
marker.on('click', function(e) {
petMapDmaPopup.init(e.target.data);
});
marker.on('mouseover', function(e) {
var layer = e.target.layer;
layer.setStyle({
weight: 1,
color: '#8A8D8F',
dashArray: '',
fillOpacity: 0.5
});
if(!L.Browser.ie && !L.Browser.opera && !L.Browser.edge) {
layer.bringToFront();
}
});
marker.on('mouseout', function(e) {
petMap.dmaPoly.resetStyle(e.target.layer);
});
petMap.dmaMarkers.addLayer(marker);
}
});
this.map.addLayer(this.dmaMarkers);
this.map.addLayer(this.dmaPoly);
},
getDmaMarkerIcon: function(data) {
var cluster_classes = [
'dma-marker-icon',
'leaflet-marker-icon',
'leaflet-zoom-animated',
'leaflet-clickable'
];
return L.divIcon({
html: '<div class="' + cluster_classes.join(' ') + '" tabindex="0">' + data.dma_name + '</div>'
});
},
/**********************************************************/
mapAction: function() {
this.map.on('zoomend dragend',function(e) {
petMap.getBounds();
petMap.getZoomLevel();
petMap.progressBarInit();
petMap.requestDataFromServer();
});
},
resetMap: function() {
this.dataLevel = 'profile';
this.clearmarkerLayer();
if(Object.keys(this.locationMarkes).length) {
for(var id in this.locationMarkes) {
this.locationMarkes[id].clearLayers();
delete this.locationMarkes[id];
}
}
this.map.removeLayer(this.dmaMarkers);
this.map.setView(new L.LatLng(this.mapCenter[0], this.mapCenter[1]), 5);
},
getBounds: function() {
var bounds = this.map.getBounds();
this.bounds = {
tr: {
lat: bounds.getNorthEast().lat,
lng: bounds.getNorthEast().lng
},
bl: {
lat: bounds.getSouthWest().lat,
lng: bounds.getSouthWest().lng
}
};
},
getZoomLevel: function() {
this.zoom = this.map.getZoom();
this.zoomLevel = 'state';
if(this.zoom > 6) {
this.zoomLevel = 'city';
}
if(this.zoom > 8) {
this.zoomLevel = 'zip';
}
// dma data.
if(this.zoom > 6) {
this.plotDmaData('add');
} else {
this.plotDmaData('remove');
}
},
mapZoomClass: function() {
L.Map.mergeOptions({
zoomCss: true
});
L.Map.ZoomCSS = L.Handler.extend({
addHooks: function() {
this._zoomCSS();
this._map.on('zoomend', this._zoomCSS, this);
},
removeHooks: function() {
this._map.off('zoomend', this._zoomCSS, this);
},
_zoomCSS: function(e) {
var map = this._map,
zoom = map.getZoom(),
container = map.getContainer();
container.className = container.className.replace( /\smap-zoom-[0-9]{1,2}/g, '' ) + ' map-zoom-' + zoom;
}
});
L.Map.addInitHook('addHandler', 'zoomCss', L.Map.ZoomCSS);
},
/**********************************************************/
progressBarInit: function() {
clearTimeout(petMap.progressTimer);
$('.progress-bar .progress').css('width', '0%');
$('.progress-bar').removeClass('hide');
this.progressBarProress();
},
progressBarProress: function() {
this.progressTimer = setTimeout(function() {
petMap.progress += 0.5;
$('.progress-bar .progress').css('width', petMap.progress + '%');
if(petMap.progress != 100) {
petMap.progressBarProress();
}
}, 25);
},
progressBarReset: function() {
$('.progress-bar').addClass('hide');
$('.progress-bar .progress').css('width', '0%');
clearTimeout(petMap.progressTimer);
petMap.progress = 0;
},
/**********************************************************/
formatCount: function(count) {
if(count > 1000) {
count = Math.floor(count / 1000) + 'K' + (count % 1000 !== 0 ? '+' : '');
}
return count;
},
getMarkerSize: function(count) {
size = 30;
if(count > 100) {
size = 35;
}
if(count > 500) {
size = 40;
}
if(count > 1000) {
size = 45;
}
if(count > 5000) {
size = 50;
}
if(count > 10000) {
size = 55;
}
if(count > 20000) {
size = 60;
}
if(count > 30000) {
size = 65;
}
if(count > 50000) {
size = 70;
}
if(count > 70000) {
size = 75;
}
if(count > 90000) {
size = 80;
}
if(count > 120000) {
size = 85;
}
if(count > 140000) {
size = 90;
}
if(count > 160000) {
size = 95;
}
if(count > 180000) {
size = 100;
}
if(count > 200000) {
size = 105;
}
if(count > 220000) {
size = 110;
}
if(count > 240000) {
size = 115;
}
if(count > 260000) {
size = 120;
}
if(count > 280000) {
size = 125;
}
if(count > 300000) {
size = 130;
}
if(count > 320000) {
size = 135;
}
if(count > 340000) {
size = 140;
}
if(count > 360000) {
size = 145;
}
if(count > 380000) {
size = 150;
}
if(count > 400000) {
size = 155;
}
if(count > 500000) {
size = 160;
}
if(count > 600000) {
size = 165;
}
if(count > 700000) {
size = 170;
}
if(count > 800000) {
size = 175;
}
return size;
},
getMarkerHtml: function(count, color) {
var size = this.getMarkerSize(count);
var hsize = (size / 2) - 6;
var font = count < 1000 ? Math.ceil(size / 3) : Math.ceil(size / 4);
if(count < 100) {
font = font + 3;
}
var cluster_classes = [
'map-marker',
'marker-bg-' + (petMapFilters.colors.profile === color ? 'profile' : 'condition')
];
if(this.zoomLevel !== 'zip') {
size = size * 1.5;
if(petMapFilters.colors.profile !== color) {
hsize = size / 2;
}
}
var cluster_styles = [
'margin-left: -' + hsize + 'px;',
'margin-top: -' + hsize + 'px;',
'width: ' + size + 'px;',
'height: ' + size + 'px;',
'font-size: ' + font + 'px;'
];
var div_style = [
'line-height: ' + (size - (size * 0.3)) + 'px;'
];
count = this.formatCount(count);
return '<div class="' + cluster_classes.join(' ') + '" tabindex="0" style="' + cluster_styles.join(' ') + '"><div style="' + div_style.join(' ') + '">' + count + '</div></div>';
},
getResultCount: function(data) {
if(this.dataLevel === 'conditions') {
if(typeof data.total_ailments != 'undefined') {
return data.total_ailments;
}
return 0;
}
return data.total;
},
dataLevelFixer: function() {
this.dataLevel = 'profile';
if(Object.keys(petMapFilters.ailments).length) {
this.dataLevel = 'conditions';
}
}
};
})(jQuery);
If I understand correctly, you build 1 MarkerClusterGroup per State. But at lowest zoom level, you would like only a single cluster to be displayed, so that it shows the count for the whole country?
In that case, unfortunately there is no built-in way to achieve this. However, the easy workaround is simply to build an extra MarkerClusterGroup where you add all of your individual Markers as well, and add it to map only at lowest zoom level, while you remove all the other State MCG's. Use the map "zoomend" event to read map zoom and and add / remove the appropriate Layer Groups. If your country level MCG is not totally clustered, simply increase the maxClusterRadius option.
The plot markers sections was preventing me from initialising the markers due to the original zoom level.
plotMarkers: function(response) {
this.clearmarkerLayer();
var color = window.petMapFilters.colors[this.dataLevel];
this.initClusterMarker(color, this.dataLevel);
Worked fine.
I am using Gantt Chart extension from PTC Marketplace. When I configured and run the mashup it's giving error as "TypeError: Cannot read property 'ActualDataRows' of undefined at resize". (Please refer the below code and the attached image file).
I this.resize function throwing an error as thisWidget.lastData is undefined. As I am new to JavaScript I am unable to solve this error. Could you guys please help me.
Thanks
(function () {
TW.Runtime.Widgets.ganttChart = function () {
var thisWidget = this;
var currentlySelectedRow = undefined;
this.runtimeProperties = function () {
return {
'needsDataLoadingAndError': true,
'supportsAutoResize': true,
'propertyAttributes': {
}
};
};
this.renderHtml = function () {
if (this.properties.ResponsiveLayout === true ) {
widgetWidth = '100%';
widgetHeight = '100%';
} else {
widgetWidth = this.getProperty("Width");
widgetHeight = this.getProperty("Height");
}
var html = '<div class="widget-content widget-ganttChart"><div id = "chart_div" width=' + widgetWidth + ' height=' + widgetHeight + '> </div></div>';
return html;
};
this.loadChart = function (rows, taskId, taskName, startDate, endDate, resource, relationships, duration, percentage) {
google.charts.load('current', {'packages':['gantt']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Task ID');
data.addColumn('string', 'Task Name');
data.addColumn('string', 'Resource');
data.addColumn('date', 'Start Date');
data.addColumn('date', 'End Date');
data.addColumn('number', 'Duration');
data.addColumn('number', 'Percent Complete');
data.addColumn('string', 'Dependencies');
var trackStyle = TW.getStyleFromStyleDefinition(thisWidget.getProperty('TrackStyle', 'DefaultGanttTrackStyle'));
var altTrackStyle = TW.getStyleFromStyleDefinition(thisWidget.getProperty('AlternativeTrackStyle', 'DefaultAlternativeGanttTrackStyle'));
var arrowStyle = TW.getStyleFromStyleDefinition(thisWidget.getProperty('ArrowStyle', 'DefaultGanttArrowStyle'));
var trackFill = trackStyle.backgroundColor;
var altTrackFill = altTrackStyle.backgroundColor;
var arrowColor = arrowStyle.lineColor;
var arrowWidth = arrowStyle.lineThickness;
for (var i = 0; i < rows.length; i++) {
var row = rows[i];
data.addRows([
[row[taskId], row[taskName], row[resource],
new Date(row[startDate]), new Date(row[endDate]), row[duration], row[percentage], row[relationships]]
]);
}
var barHeight = thisWidget.getProperty('ItemHeight');
var chartHeight = rows.length * barHeight + 50;
var itemHeight = barHeight - 5;
var cornerRadius = thisWidget.getProperty('BarCornerRadius');
var percentEnabled = thisWidget.getProperty('ShowPercentCompletion');
var arrowRadius = thisWidget.getProperty('ArrowRadius');
var arrowAngle = thisWidget.getProperty('ArrowAngle');
var options = {
width: "100%",
height: chartHeight,
gantt: {
barHeight: itemHeight,
trackHeight: barHeight,
barCornerRadius: cornerRadius,
arrow: { angle:arrowAngle, length: 5, spaceAfter: 5, radius: arrowRadius, color: arrowColor, width: arrowWidth},
innerGridTrack: {fill: trackFill },
innerGridDarkTrack: {fill: altTrackFill},
percentEnabled : percentEnabled
}
};
var chart = new google.visualization.Gantt(document.getElementById('chart_div'));
chart.draw(data, options);
google.visualization.events.addListener(chart, 'select', function(e) {
var selection = chart.getSelection();
if (selection[0] != undefined && selection[0] != null)
thisWidget.handleRowSelection (selection[0].row);
});
}
};
this.afterRender = function () { };
this.handleSelectionUpdate = function (propertyName, selectedRows, selectedRowIndices) {
var domElementId = this.jqElementId;
var widgetElement = this.jqElement;
var widgetProperties = this.properties;
if (propertyName == "Data") {
var widgetProperties = this.properties;
var idField = widgetProperties['TaskID'];
thisWidget.ignoreSelectionEvent = true;
var nSelectedRows = selectedRows.length;
if (nSelectedRows > 0) {
for (var x = 0; x < nSelectedRows; x++) {
if (selectedRows[x]._isSelected === true) {
thisWidget.handleRowSelection(selectedRows[x]["_row_"]);
thisWidget.ignoreSelectionEvent = false;
break;
}
}
} else
thisWidget.handleRowSelection(undefined);
thisWidget.ignoreSelectionEvent = false;
}
};
this.handleRowSelection = function (selectedRowNo) {
if (selectedRowNo !== undefined) {
var selectedRows = [selectedRowNo];
if (!thisWidget.ignoreSelectionEvent) {
thisWidget.updateSelection('Data', selectedRows);
}
}
thisWidget.currentlySelectedRow = selectedRowNo;
};
this.handleItemClick = function (d) {
thisWidget.handleRowSelection(d["_row_"]);
};
this.assignRowNumbers = function (rows) {
var rowid;
for (rowid in rows) {
var row = rows[rowid];
row["_row_"] = rowid;
}
};
this.updateProperty = function (updatePropertyInfo) {
var widgetProperties = this.properties;
if (updatePropertyInfo.TargetProperty === "Data") {
thisWidget.lastData = updatePropertyInfo;
var rows = updatePropertyInfo.ActualDataRows;
this.assignRowNumbers(rows);
var taskName = widgetProperties['TaskName'];
var taskId = widgetProperties['TaskID'];
var startDate = widgetProperties['StartDate'];
var endDate = widgetProperties['EndDate'];
var resource = widgetProperties['Resource'];
var relationships = widgetProperties['Relationships'];
var duration = widgetProperties['Duration'];
var percentage = widgetProperties['Percentage'];
this.loadChart(rows, taskId, taskName, startDate, endDate, resource, relationships, duration, percentage);
var selectedRowIndices = updatePropertyInfo.SelectedRowIndices;
if (selectedRowIndices !== undefined) {
if (selectedRowIndices.length > 0) {
var selectedRows = new Array();
selectedRows.push(rows[selectedRowIndices[0]]);
setTimeout(function () {
thisWidget.handleSelectionUpdate("Data", selectedRows, selectedRowIndices);
}, 100);
} else {
setTimeout(function () {
thisWidget.handleSelectionUpdate("Data", [], []);
}, 100);
}
} else {
setTimeout(function () {
thisWidget.handleSelectionUpdate("Data", [], []);
}, 100);
}
if (this.SelectedValuePending !== undefined) {
this.selectItem(this.SelectedValuePending);
this.SelectedValuePending = undefined;
}
} else if (updatePropertyInfo.TargetProperty === "SelectedValue") {
var selectedItem = updatePropertyInfo.SinglePropertyValue;
var dataPropertyInfo = thisWidget.lastData;
if (dataPropertyInfo != undefined) {
this.selectItem(selectedItem);
} else {
this.SelectedValuePending = selectedItem;
}
}
};
this.beforeDestroy = function () {
};
this.resize = function () {
var taskName = thisWidget.getProperty('TaskName');
var taskId = thisWidget.getProperty('TaskID');
var startDate = thisWidget.getProperty('StartDate');
var endDate = thisWidget.getProperty('EndDate');
var resource = thisWidget.getProperty('Resource');
var relationships = thisWidget.getProperty('Relationships');
var duration = thisWidget.getProperty('Duration');
var itemHeight = thisWidget.getProperty("ItemHeight");
var percentage = thisWidget.getProperty("Percentage");
var rows = thisWidget.lastData.ActualDataRows; //here throwing error
thisWidget.loadChart(rows, taskId, taskName, startDate, endDate, resource, relationships, duration, percentage);
};
window.addEventListener("resize", this.resize);
};} ());
This problem caused because I haven't assigned Trigger Event to data service used for a Gantt Chart. In this case assign 'Mashup Loaded' Trigger Event to data service.
Thanks