jVectorMap active marker on page load - jvectormap

i have custom colors for regions and custom images for marker icons. Hovering, clicking on markers changes everytjing like i want but... How to make one marker, marked after loading a map, i cant find solution. I've been trying to click the marker icon with jquery, finding by element attribute, the click worked (according to the console log), but nothing changed on the map.
https://jsfiddle.net/6ss2eahr/7/
$(document).ready(function () {
var markers = [
{ latLng: [54.5039433, 18.3233958], name: 'Gdynia', region: 'PL-PM' },
{ latLng: [51.7472675, 18.0070145], name: 'Kalisz', region: 'PL-WP' },
{ latLng: [50.2138079, 18.8671087], name: 'Katowice', region: 'PL-SL' },
{ latLng: [50.8541274, 20.5456014], name: 'Kielce', region: 'PL-SK' }
];
var last_poi;
$('#map-pl').vectorMap({
map: 'pl_merc',
backgroundColor: '#fff',
zoomButtons: false,
zoomOnScroll: false,
regionsSelectable: false,
regionsSelectableOne: true,
markersSelectable: true,
markersSelectableOne: true,
markers: markers,
markerStyle: {
initial: {
image: 'https://www.royalparks.org.uk/_media/images/map_icons/find-my-location-icon.png'
},
hover: {
image: 'http://tiltedkilt.com/wp-content/themes/base/library/images/pin-small-icon.png',
cursor: 'pointer'
},
selected: {
image: 'http://tiltedkilt.com/wp-content/themes/base/library/images/pin-small-icon.png'
},
selectedHover: {
image: 'http://tiltedkilt.com/wp-content/themes/base/library/images/pin-small-icon.png'
}
},
regionStyle: {
hover: { fill: '#fdefc9' },
initial: { stroke: "white", "stroke-width": 1, fill: "#fcf8ed" },
selected: { fill: "#ffcc39" }
},
onMarkerClick: function (event, id) {
var mapObject = $('#map-pl').vectorMap('get', 'mapObject');
mapObject.clearSelectedRegions();
mapObject.setSelectedRegions(markers[id].region);
last_poi = id;
},
onMarkerOver: function (event, id) {
var mapObject = $('#map-pl').vectorMap('get', 'mapObject');
mapObject.clearSelectedRegions();
if (last_poi) {
mapObject.setSelectedRegions(markers[last_poi].region);
}
mapObject.setSelectedRegions(markers[id].region);
},
onMarkerOut: function (event, id) {
var mapObject = $('#map-pl').vectorMap('get', 'mapObject');
mapObject.clearSelectedRegions();
if (last_poi) {
mapObject.setSelectedRegions(markers[last_poi].region);
}
},
onRegionTipShow: function (e, label, code) {
e.preventDefault();
}
});
});

All the functions getSelectedMarkers, setSelectedRegions, and so on can handle array of values, so the solution is pretty easy to dynamically select one or more Marker and the corresponding Region:
var mapObject = $('#map-pl').vectorMap('get', 'mapObject');
// select Gdynia by index
var selectedMarkers = [0],
selectedRegions = [];
selectedMarkers.forEach(function(item) {
selectedRegions.push(mapObject.markers[item].config.region);
});
mapObject.setSelectedMarkers(selectedMarkers);
mapObject.setSelectedRegions(selectedRegions);
Your can remove the whole logic to keep track of the marker index using last_poi, which is causing the deselection in onMarkerOut and replace with the above function to get the selected Region directly from the mapObject.

Related

Chartjs convert toBase64 not working in an iframe

I have a problem when i am trying to generate the Base64 of my chartjs line.
The console.log of my base64 string is : "data:," (attachment)
i am launching this code in an iframe, not in the parent page. On this chart, there are 30000 lines of data.
**When i directly launched the page, i have no problem, everything is OK.
**
Here is my code :
`
function generateTrend2(data){
var line = document.getElementById('chartContainer').getContext('2d')
var dataY = []
var dataX = []
data.forEach(function (item) {
dataY.push(item.y)
dataX.push(item.x)
})
var lineChart = new Chart(line, {
type: 'line',
data: {
labels: dataX,
datasets: [{
data: dataY,
label: "Sample Coverage",
borderColor: "#3e95cd",
fill: false,
borderWidth: 1
}]
},
options: {
animation: {
duration: 0,
},
hover: {
animationDuration: 0,
},
responsiveAnimationDuration: 0,
onAnimationComplete: done(),
elements: {
point:{
radius: 0
}
}
}
});
function done(){
setTimeout(function(){
var image = lineChart.toBase64Image();
console.log(image)
$("body").append("<input type='hidden' value='" + image + "' id='img-chart' >")
},1000)
}
}
`
I tried to put a delay of 200,500,1000,5000,10000, but the result is the same in my var image...
I have generated an other base64 with an other chart with similar code, the same system, in an iframe and i have no problem.

Show/Hide Columns in Boot grid when onclick - Externally

i couldn't hide a show/hide a boot grid column after onclick boot grid re-load.
The issue is it works when the page is loaded first time, but i couldn't make it work after click event. Any help is appreciated.
<th id="th_state" data-identifier="true" data-column-id="state" data-visible="false">State</th>
$('#filter_group').change(function () {
$("#employee_grid").bootgrid("reload")
$("#th_state").attr("data-visible", "true") ; // Not working....
});
$("#employee_grid").bootgrid({
ajax: true,
rowCount: [50, 100, 200, 300, 500],
columnSelection: true,
requestHandler: function (request) {
request.type = 'grid';
var citiesGroup = [];
$("#cities_group").find("option:selected").each(function (index, value) {
if ($(this).is(':selected')) {
citiesGroup.push({
state: $(this).parent().attr("label"),
city: $(this).val()
});
}
});
if (request.sort) {
request.sortBy = Object.keys(request.sort)[0];
request.sortOrder = request.sort[request.sortBy];
request.chartType = $("#chartType").val();
request.date_from = $("#date_from").val();
request.date_to = $("#date_to").val();
request.citiesGroup = citiesGroup ;
delete request.sort
}
return request;
},
responseHandler: function (response) {
$("#txt_total_connects").html(response);
return response;
},
post: function ()
{
/* To accumulate custom parameter with the request object */
return {
id: "b0df282a-0d67-40e5-8558-c9e93b7befed"
};
},
url: "response.php",
formatters: {
},
labels: {
noResults: "<b>No data found</b>",
all: "",
loading: '<b>Loading Please wait....</b>'
},
templates: {
search: "",
//header: "",
}
});

Can we add event listeners to "Vega-Lite" specification?

I am new to Vega and Vega-Lite. I am creating a simple bar chart using Vega-Lite but I am not able to add any event listeners e.g. "hover".
I want to hover a bar and change the color of the bar.
If you're using Vega-Embed, it returns a promise with a reference to the view which allows you to use addEventListener - explained in the docs here.
Here is an example:
const width = 600
const color = blue
embed(element, {
$schema: 'https://vega.github.io/schema/vega-lite/3.0.0-rc6.json',
data: { 'values': data },
mark: {
type: 'line',
color,
point: {
color,
}
},
width,
height: width / 2,
encoding: {
'x': {
field: 'label',
type: 'temporal',
},
'y': {
field: 'value',
type: 'quantitative',
},
}
}).then(({spec, view}) => {
view.addEventListener('mouseover', function (event, item) {
console.log(item.datum)
})
})

A marker can only be added to a layer of type "group" error even though type "group" is defined

I am having trouble with an error that seems obvious but I've tried everything. I must be missing something. I'm running a rails app with Angularjs and angular-leaflet-directives. I am trying to add markers to a specific group. No matter what I do, I keep getting this error:
[AngularJS - Leaflet] A marker can only be added to a layer of type "group"
I know that this error comes up when the overlays type isn't group. The issue is that in my case, it is!
EDIT: here is a plunkr where I recreated the bug: http://plnkr.co/edit/DLCN5RYVr0BheYzTuqkQ?p=preview
Here is my code:
assets/javascript/angular/services/service.js
app.factory('Markers', ["$http", "$q", function($http, $q) {
var Markers = []
var events_markers = []
var stories_markers = []
var defaultIcon = L.icon({
iconUrl: 'assets/dot-grey.png',
iconSize: [15, 15],
iconAnchor: [15, 15],
popupAnchor: [-7, -20]
})
// Getting events + stories from rails API
var event_data = $http.get("/api/v1/events.json"),
story_data = $http.get("/api/v1/stories.json")
// Setting event markers and stories markers
$q.all([event_data, story_data]).then(function(results) {
var data_stories = results[1].data.stories
var data_events = results[0].data.event
for (i=0 ; i < data_stories.length; i++){
for (j=0; j < data_stories[i].locations.length; j++){
var lat = data_stories[i].locations[j].latitude
var lng = data_stories[i].locations[j].longitude
var title = data_stories[i].title
var layer = "stories"
Markers.push({layer: layer, lat:lat, lng:lng, message: title, icon: defaultIcon})
}
}
for (e=0 ; e < data_events.length; e++){
if (data_events[e].latitude != null){
var lat = data_events[e].latitude
var lng = data_events[e].longitude
var title = data_events[e].name
var layer = "events"
Markers.push({layer: layer, lat:lat, lng: lng, message: title, icon: defaultIcon})
}
}
return Markers
});
return {
markers: Markers
}
}]);
assets/javascript/angular/controllers/MapCtrl.js
app.controller("MapCtrl", ['$scope', "$timeout", "leafletData", "Markers", function($scope,
$timeout, leafletData, Markers ){
$scope.isVisible = true;
$scope.markers = Markers.markers;
var bounds = {
northEast:{
lat: 37.86862005954327,
lng: -122.12230682373048
},
southWest:{
lat: 37.68436373334184,
lng: -122.55901336669923
}
}
function setMap($scope, markers, bounds) {
angular.extend($scope, {
maxbounds: bounds,
defaults: {
scrollWheelZoom: false,
maxZoom: 14,
minZoom: 10
},
layers: {
baselayers: {
mapbox:{
name: 'Mapbox Litography',
url: 'http://api.tiles.mapbox.com/v4/{mapid}/{z}/{x}/{y}.png?access_token={apikey}',
type: 'xyz',
layerParams: {
apikey: 'pk.eyJ1IjoibGF1cmVuYmVuaWNob3UiLCJhIjoiQ1BlZGczRSJ9.EVMieITn7lHNi6Ato9wFwg',
mapid: 'laurenbenichou.jm96meb6'
}
}
}
},
overlays: {
stories: {
type: 'group', //Note here that the type is indeed 'group'
name: 'stories',
visible: true
},
events: {
type: 'group',
name: 'events',
visible: false
}
},
markers: markers
});
}
setMap($scope, $scope.markers, bounds)
angular.element(document).ready(function () {
function toggle(){$scope.isVisible = !$scope.isVisible;}
$timeout(toggle, 1000);
});
}])
assets/javascript/templates/map.html
<leaflet ng-hide="isVisible" defaults="defaults" markers="markers" layers="layers" height="100%" width="100%" maxbounds="maxbounds" ></leaflet>
assets/javascript/angular/app.js
var app = angular.module("litography", ['ngAnimate','ui.router','ngResource', 'templates', 'leaflet-directive', 'cn.offCanvas', 'ui.bootstrap', 'angular-flexslider'])
.config(['$stateProvider', '$urlRouterProvider', '$locationProvider', function($stateProvider, $urlRouterProvider, $locationProvider) {
/**
* Routes and States
*/
$stateProvider
.state('home', {
url: "/",
views:{
"splash": {
templateUrl: "splash.html",
controller: "SplashCtrl"
},
"map":{
templateUrl: "map.html",
controller: "MapCtrl",
resolve:{
Markers: function(Markers){
return Markers
}
}
},
"menu":{
templateUrl: "menu.html",
controller: "MenuCtrl"
}
}
})
// default fall back route
$urlRouterProvider.otherwise('/');
// enable HTML5 Mode for SEO
$locationProvider.html5Mode(true);
}]);
It can happen if you forgot to add the file: leaflet.markercluster.js
Ok, from the reduced plunker it was easier to play around and find the bug.
You need to put overlays inside (i.e. as a property of) layers:
layers: {
baselayers: {
mapbox: {
name: 'mapbox',
url: 'http://api.tiles.mapbox.com/v4/{mapid}/{z}/{x}/{y}.png?access_token={apikey}',
type: 'xyz',
layerParams: {
apikey: 'pk.eyJ1IjoibGF1cmVuYmVuaWNob3UiLCJhIjoiQ1BlZGczRSJ9.EVMieITn7lHNi6Ato9wFwg',
mapid: 'laurenbenichou.jm96meb6',
name: "stories"
}
}
},
overlays: {
stories: {
type: 'group',
name: 'stories',
visible: true,
},
events: {
type: 'group',
name: 'events',
visible: false
}
}
}

Kendo Treeview Expand Node

I have this treeview wich can have a variable number of children (some nodes can have up to 3 generations of children, some may have only one etc)
What I'm trying to do is expand a certain node when the treeview is loaded. And I have 2 problems:
1) I can't find an event/callback so that I know when the treeview is ready
2) The expand function doesn't always work ( I'll explain )
This is my treeview:
function InitializeTreeview() {
var Children_Merchants = {
transport: {
read: {
url: function (options) {
return kendo.format(websiteRootUrl + '/Merchants/Merchants/?hasParents={0}', hasParent);
}
}
},
schema: {
model: {
model: {
id: "ID",
hasChildren: true,
children: Children_Merchants
}
}
}
};
var Brandowners = new kendo.data.HierarchicalDataSource({
transport: {
read: {
url: kendo.format(websiteRootUrl + '/Merchants/GetBrandowners?databaseID={0}', selectedDatabaseID)
}
},
//change: ExpandNode, - if I call expand node like this, it works.
schema: {
model: {
id: "ID",
hasChildren: true,
children: Children_Merchants
}
}
});
$('#treeview').kendoTreeView({
dataSource: Brandowners,
animation: {
collapse: {
duration: 200,
effects: "fadeOut"
},
expand: {
duration: 200,
effects: "fadeIn"
}
},
dataTextField: "Name",
complete: function () { alert('ok'); },
//dataBound : ExpandNode,
select: OnSelect,
expand: CheckIfHasParent
}).data('kendoTreeView');
}
function ExpandNode() {
var treeview;
treeview = $("#treeview").data("kendoTreeView");
var nodeToExpand = treeview.findByText('Adam'); //dummy txt, will have from parameter
treeview.expand(nodeToExpand);
}
The databind works ok, my controllers get called, everything's fine.
So what I tried is hook up the ExpandNode function to a click of a button. The function gets called but nothing happens. BUT if I hook it up to the change event of the parents datasource, it works. Another interesting thing is that the select works so if I replace treeview.expand(...) with treeview.select(...), it works on the click.
So my questions are:
1) What event should I use for loadEnd ( or smth like that ) - so I won't have to bind the function to button click (it's still ok but I preffer on load ended) - P.S. I tried all the ones I found on the kendo forums,like: change, requestEnd, success, dataBound and they don't work. I tried sending the JSON with the property "expanded" set to TRUE, for the node in question, but that only modifies the arrow to show like it's opened, but it doesn't call the controller and load the children.
2) Do you know why ExpandNode works only when binded to the change event? - the most important question to me.
3) If you have suggestions, or have I done something wrong in the initialiation of the treeview, please tell me.
I've copied your code with some free interpretations and the answer your questions is:
What event should I use for loadEnd => dataBound
Do you know why ExpandNode works only when binded to the change event? => No, it works without binding it to change event. If it does not then there is something else in your code.
Suggestions => There is some information missing about your code that might make the difference with what I've implemented.
What is CheckIfHasParent? => I have implemented it as a function that actually does nothing.
What is hasParent? => I've ignored it.
The code as I write it:
$(document).ready(function () {
function InitializeTreeview() {
var Children_Merchants = {
transport: {
read: function (op) {
var id = op.data.ID;
var data = [];
for (var i = 0; i < 10; i++) {
var aux = id * 100 + i;
data.push({ Name: "Name-" + aux, ID: aux});
}
op.success(data);
}
},
schema : {
model: {
model: {
id : "ID",
hasChildren: true,
children : Children_Merchants
}
}
}
};
var Brandowners = new kendo.data.HierarchicalDataSource({
transport: {
read: function (op) {
op.success([
{"Name": "Adam", "ID": 1},
{"Name": "Benjamin", "ID": 2},
{"Name": "Caleb", "ID": 3},
{"Name": "Daniel", "ID": 4},
{"Name": "Ephraim", "ID": 5},
{"Name": "Frank", "ID": 6},
{"Name": "Gideon", "ID": 7}
])
}
},
//change: ExpandNode, - if I call expand node like this, it works.
schema : {
model: {
id : "ID",
hasChildren: true,
children : Children_Merchants
}
}
});
$('#treeview').kendoTreeView({
dataSource : Brandowners,
animation : {
collapse: {
duration: 200,
effects : "fadeOut"
},
expand : {
duration: 200,
effects : "fadeIn"
}
},
dataTextField: "Name",
dataBound : ExpandNode,
expand : CheckIfHasParent
}).data('kendoTreeView');
}
function ExpandNode() {
var treeview;
treeview = $("#treeview").data("kendoTreeView");
var nodeToExpand = treeview.findByText('Adam'); //dummy txt, will have from parameter
treeview.expand(nodeToExpand);
}
function CheckIfHasParent(e) {
}
InitializeTreeview();
});
and you can play with it here : http://jsfiddle.net/OnaBai/dSt2h/
$("#treeview").kendoTreeView({
animation: {
expand: true
},
dataSource: dataSource,
dataBound: function (e) {
var tv = $("#treeview").data("kendoTreeView");
if (tv != null) {
tv.expand(".k-item");
}
},
dataTextField: "test",
dataValueField: "id"
});
For anyone who may be interested:
function ExpandNode() {
var treeview;
var node1;
treeview = $("#treeview").data("kendoTreeView");
var node2;
var myURL = kendo.format(websiteRootUrl + '/Merchants/GetPathForSelectedNode?databaseID={0}&merchantID={1}&brandownerID={2}', selectedDatabaseID,MerID,BowID);
node1 = treeview.dataSource.get(BowID);
node = treeview.findByUid(node1.uid);
var uid = node1.uid;
node.find('span:first-child').trigger('click'); //expand 1st level
$.ajax( {
url: myURL,
dataType: "json",
contentType: 'application/json; charset=utf-8',
success: function(result)
{
var length = result.length;
var lastVal = 1;
for (var i = 1; i < length-1; i++) {
$("#treeview li[data-uid=\'" + uid + "\'] ul.k-group").waitUntilExists (function
() {
i = lastVal; // have to reinitialize i because waitUntilExist's callback will find the i incermented, over the needed value
lastVal++;
node2 = node1.children.get(result[i]);
node = treeview.findByUid(node2.uid);
uid = node2.uid;
node1 = node2;
if(lastVal <= length-1)
node.find('span:first-child').trigger('click'); // keep expanding
else
{
treeview.select(node); // just select last node
currentSelectedNode = node;
}
});
}
if(length == 2) //select 1st child
{
$("#treeview li[data-uid=\'" + uid + "\'] ul.k-group").waitUntilExists (function
() {
node2 = node1.children.get(result[i]);
node = treeview.findByUid(node2.uid);
uid = node2.uid;
node1 = node2;
treeview.select(node); // just select last node
currentSelectedNode = node;
});
}
}
});
}
This is my method. The for loop starts at 1 because the 1st element in my array is the 1st node ID - wich I've already expanded. the .waitUntilExists is Ryan Lester's method (I put a link in the comments above). Many thanks to my colleague, to you OnaBai and, of courese, to Ryan Lester. I hope this helps someone. Cheers
ypu can easily find the treeview is ready for expand by following code which are expanding all the treeview nodes you can also find it by checking perticular id or text
hopw, following example will help you
Ex:
$("#treeview").kendoTreeView({
animation: {
expand: true
},
dataSource: dataSource,
dataBound: function (e) {
var tv = $("#treeview").data("kendoTreeView");
if (tv != null) {
tv.expand(".k-item");
}
},
dataTextField: "test",
dataValueField: "id"
});

Resources