Want to get region name from drill down map of jvectormap - jvectormap

I am unable to get region name from code of region. My region click event work fine and I also get code properly. My code is:
<div id="map" style="width: 600px; height: 400px"></div>
<script type="text/javascript">
$(function () {
new jvm.MultiMap({
container: $('#map'),
maxLevel: 1,
main: {
map: 'us_lcc_en'
},
mapUrlByCode: function (code, multiMap) {
return 'js/counties/jquery-jvectormap-data-' +
code.toLowerCase() + '-' +
multiMap.defaultProjection + '-en.js';
}
});
$('#map').bind('regionClick.jvectormap', function (event, code) {
var map = $('#map').vectorMap('get', 'mapObject');
alert(map.getRegionName(code));
});
});
</script>

HTML CODE
<div id="map2" style="width: 100%; height: 400px"></div>
Jquery Code
$('#map2').vectorMap({
map: 'world_mill_en',
series: {
regions: [{
scale: ['#C8EEFF', '#0071A4'],
normalizeFunction: 'polynomial',
values: gdpData
}]
},
onRegionClick: function (event, code) {
******* Code To Show Region Name *******
/* Here We are getting Map Object */
var map=$('#map2').vectorMap('get', 'mapObject');
/* Here Using Map Object we are using Inbuilt GetRegionName
function TO Get Regionname for a region Code */
var regionName = map.getRegionName(code);
console.log("Code: "+code+"<br/>");
console.log("Region Name: "+regionName+"<br/>");
******* Code To Show Region Name *******
}
});

I could not figure out how to get the region name from the onRegionClick for a multi map. This is my hack to get what is needed.
var drillDownUSMap;
var stateCode;
var countyName;
$(document).ready(function () {
drillDownUSMap = new jvm.MultiMap({
container: $('#map'),
maxLevel: 1,
main: {
map: 'us_lcc_en',
onRegionClick: function (e, code) {
var map = $('#map div').vectorMap('get', 'mapObject');
var regionName = map.getRegionName(code);
stateCode = code.toLowerCase();
console.log(regionName)
}
},
mapUrlByCode: function (code, multiMap) {
return 'js/counties/jquery-jvectormap-data-' +
code.toLowerCase() + '-' +
multiMap.defaultProjection + '-en.js';
},
mapNameByCode: function (code, multiMap) {
return code.toLowerCase() + '_' +
multiMap.defaultProjection + '_en';
}
});
$(document).on('click', '.jvectormap-region.jvectormap-element', function (evt) {
var regionElem = $(this);
var stateJSFileName = stateCode + "_" + drillDownUSMap.defaultProjection + "_en";
var regionCode = regionElem.attr('data-code');
if (drillDownUSMap.maps[stateJSFileName]) {
countyName = drillDownUSMap.maps[stateJSFileName].regions[regionCode].config.name;
if (regionElem.hasClass("selected-region")) {
regionElem.removeClass("selected-region");
} else {
regionElem.addClass("selected-region");
}
}
});
});

Add this code
onRegionClick:function(event, code) {
var name = (code);
alert(name);
}
All Script Like This
<div id="map" style="width: 600px; height: 400px"></div>
<script type="text/javascript">
$(function () {
new jvm.MultiMap({
container: $('#map'),
maxLevel: 1,
main: {
map: 'us_lcc_en'
},
mapUrlByCode: function (code, multiMap) {
return 'js/counties/jquery-jvectormap-data-' +
code.toLowerCase() + '-' +
multiMap.defaultProjection + '-en.js';
}
});
onRegionClick:function(event, code) {
var name = (code);
alert(name);
}
});
</script>

Related

Summernote custom button with dialog

I want to add a custom button to the Summernote toolbar that opens up a dialog that has a textbox for a URL and several checkboxes for settings. I then want to use the info from the dialog to scrape web pages and do processing on the content. The ultimate goal is to place the scraped content into the editor starting where the cursor is. I've searched and found some code on creating a custom button, but not any solid examples of implementing a dialog. I went through the summernote.js code to see how the Insert Image dialog works and that left me really confused. The test code I've got so far is in the code block, below. Thanks in advance to anyone who can help get me sorted out.
var showModalDialog = function(){
alert("Not Implemented");
};
var AddWiki = function(context) {
var ui = $.summernote.ui;
var button = ui.button({
contents: '<i class="fa fa-plus"/> Add Wiki',
tooltip: "Set a New Wiki",
class: "btn-primary",
click: function() {
showModalDialog();
}
});
return button.render();
};
$(".tw-summernote-instance textarea").summernote({
airMode: false,
dialogsInBody: false,
toolbar: [["mybutton", ["customButton"]]],
buttons: {
customButton: AddWiki
},
callbacks: {
onInit: function(e) {
var o = e.toolbar[0];
jQuery(o)
.find("button:first")
.addClass("btn-primary");
}
}
});
I found a good, simple example of what I wanted to do. Here's the code:
(function(factory) {
/* global define */
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(['jquery'], factory);
} else if (typeof module === 'object' && module.exports) {
// Node/CommonJS
module.exports = factory(require('jquery'));
} else {
// Browser globals
factory(window.jQuery);
}
}(function($) {
$.extend($.summernote.plugins, {
'synonym': function(context) {
var self = this;
var ui = $.summernote.ui;
var $editor = context.layoutInfo.editor;
var options = context.options;
context.memo('button.synonym', function() {
return ui.button({
contents: '<i class="fa fa-snowflake-o">',
tooltip: 'Create Synonym',
click: context.createInvokeHandler('synonym.showDialog')
}).render();
});
self.initialize = function() {
var $container = options.dialogsInBody ? $(document.body) : $editor;
var body = '<div class="form-group">' +
'<label>Add Synonyms (comma - , - seperated</label>' +
'<input id="input-synonym" class="form-control" type="text" placeholder="Insert your synonym" />'
'</div>'
var footer = '<button href="#" class="btn btn-primary ext-synonym-btn">OK</button>';
self.$dialog = ui.dialog({
title: 'Create Synonym',
fade: options.dialogsFade,
body: body,
footer: footer
}).render().appendTo($container);
};
// You should remove elements on `initialize`.
self.destroy = function() {
self.$dialog.remove();
self.$dialog = null;
};
self.showDialog = function() {
self
.openDialog()
.then(function(data) {
ui.hideDialog(self.$dialog);
context.invoke('editor.restoreRange');
self.insertToEditor(data);
console.log("dialog returned: ", data)
})
.fail(function() {
context.invoke('editor.restoreRange');
});
};
self.openDialog = function() {
return $.Deferred(function(deferred) {
var $dialogBtn = self.$dialog.find('.ext-synonym-btn');
var $synonymInput = self.$dialog.find('#input-synonym')[0];
ui.onDialogShown(self.$dialog, function() {
context.triggerEvent('dialog.shown');
$dialogBtn
.click(function(event) {
event.preventDefault();
deferred.resolve({
synonym: $synonymInput.value
});
});
});
ui.onDialogHidden(self.$dialog, function() {
$dialogBtn.off('click');
if (deferred.state() === 'pending') {
deferred.reject();
}
});
ui.showDialog(self.$dialog);
});
};
this.insertToEditor = function(data) {
console.log("synonym: " + data.synonym)
var dataArr = data.synonym.split(',');
var restArr = dataArr.slice(1);
var $elem = $('<span>', {
'data-function': "addSynonym",
'data-options': '[' + restArr.join(',').trim() + ']',
'html': $('<span>', {
'text': dataArr[0],
'css': {
backgroundColor: 'yellow'
}
})
});
context.invoke('editor.insertNode', $elem[0]);
};
}
});
}));

How to pass in HTML latitude and longitude into google reverse geocode to generate JSON data?

I'm trying to generate geolocation data (Readable address) based on HTML lat/long data.
I'm not able to request for a JSON output from google maps api with the following. Nothing is returned in the console window. I'm mainly trying to pass the HTML lat/long params into ajax block. Is it a syntax error having just the "pos" within the url line? Any suggestion would be appreciated.
<body>
<div>
<p>Click the button to get your coordinates.</p>
<button onclick="getLocation()">Show Location</button>
<p id="demo"></p>
</div>
<script>
var x = document.getElementById("demo");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
x.innerHTML = "Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
}
</script>
// Try HTML5 geolocation.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
<div id="map"></div>
<script>
var map, infoWindow;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -34.397, lng: 150.644},
zoom: 12
});
infoWindow = new google.maps.InfoWindow;
// Try HTML5 geolocation.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
infoWindow.setPosition(pos);
infoWindow.setContent('Location found.');
infoWindow.open(map);
map.setCenter(pos);
}, function() {
handleLocationError(true, infoWindow, map.getCenter());
});
} else {
// Browser doesn't support Geolocation
handleLocationError(false, infoWindow, map.getCenter());
}
}
function handleLocationError(browserHasGeolocation, infoWindow, pos) {
infoWindow.setPosition(pos);
infoWindow.setContent(browserHasGeolocation ?
'Error: The Geolocation service failed.' :
'Error: Your browser doesn\'t support geolocation.');
infoWindow.open(map);
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=************&callback=initMap">
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
$.ajax({
url: "https://maps.googleapis.com/maps/api/geocode/json?latlng="+pos+"&key=*********",
type: "GET",
success: function (data) {
console.log(data)
}
})
</script>
Update****Added all codes within *****

KendoUI grid with draggable only works when I have developer tools open

I've created a nice little KendoUI grid with drag and drop. It works great... as long as I have the developer tools open. Any idea why this would work with the dev tools open, but doesn't work at all with just using the browser?
Edit to add the code:
my cshtml page:
<div id="DisplayOrderGridContainer">
<div class="validation-error-box" id="errorMessages" style="display:none">
<span>Error!</span>
<ul id="message">
<li>The Record you attempted to edit was modified by another user after you got the original value. The edit operation was canceled.</li>
</ul>
</div>
<div style="padding-bottom: 15px;">
#Html.ActionLink("Back", Model.BackActionName, Model.ControllerName, Model.BackRouteValues, new { id = Model.ControllerName + "_Back", #class = "k-button" })
#if (Model.AllowClearingDisplayOrder)
{
#Html.ActionLink("Clear Order", Model.ClearActionName, Model.ControllerName, Model.BackRouteValues, new { #id = "clear-button", #class = "k-button float-right" })
}
</div>
<div id="KendoGridContainer">
<div id="ChangeDisplayOrderGrid"
class="grid"
data-role="grid"
data-bind="source:data, events:{dataBound:onDataBound,columnHide:OnColumnHide,columnShow:OnColumnShow}"
data-filterable="false"
data-sortable="false"
data-column-menu="true"
data-row-template="rowTemplate"
#*data-toolbar='[{ "template": kendo.template($("#toolbarTemplate").html()) }]'*#
data-columns='[{title:"Short Name", field:"NameField", width: 80, headerAttributes:{id: "#Model.ControllerName" + "_ShortName"}},
{title:"Description", field:"DescriptionField", width:300, headerAttributes:{id: "#Model.ControllerName" + "_Description"}},
{title:"Display Order", field:"Display", width:140, headerAttributes:{id: "#Model.ControllerName" + "_Display"}},
{title:"Value", field:"Value", hidden: true, headerAttributes:{id: "#Model.ControllerName" + "_Value"}}]'>
</div>
<script id="rowTemplate" type="text/x-kendo-tmpl">
<tr class="k-master-row" data-uid="#:uid#">
<td class="text-right">#=NameField#</td>
<td class="text-right">#=DescriptionField#</td>
<td class="text-right">#=Display#</td>
<td class="text-right" style="display:none;">#=Value#</td>
</tr>
</script>
<div id="grid" data-grid-url="#(Url.Action(Model.ActionName, Model.ControllerName))" data-grid-viewdataid="#ViewData.ID()"></div>
</div>
<input type="hidden" id="displayOrderId" />
<input type="hidden" id="Id" />
my js page:
$(document).ready(function () {
UnsavedWarningsModule.ClearUnsavedChanges();
var newData = new kendo.data.DataSource({
transport: {
read: {
url: $('#grid').attr('data-grid-url'),
dataType: "json"
}
},
schema: {
model: {
id: "Id"
}
}
})
var viewModel = new kendo.observable({
data: newData,
onDataBound: function (e) {
pfsKendoGridEvents.SetSelectedRow_MVVMGrid("KendoGridContainer", e.sender, $('#grid').attr('data-grid-viewdataId'))
},
OnColumnHide: function (e) {
pfsKendoGridEvents.OnHideShowColumns(e);
},
OnColumnShow: function (e) {
pfsKendoGridEvents.OnHideShowColumns(e);
}
});
kendo.bind($("#DisplayOrderGridContainer"), viewModel);
kendo.addDragAndDropToGrid = function (gridId, rowClass, viewModel) {
if (!gridId) { throw "Parameter [gridId] is not set."; }
if (!rowClass) { throw "Parameter [rowClass] is not set."; }
$(rowClass).kendoDraggable({
hint: function (element) {
var shortName = element[0].cells[0].firstChild.data;
var desc = element[0].cells[1].firstChild.data;
var dispOrder = element[0].cells[2].firstChild.data;
element[0].innerHTML = "<td class=\"text-right dragOver\" style=\"width:95px\">" + shortName + "</td><td class=\"text-right dragOver\" style=\"width:382px\">" + desc + "</td><td class=\"text-right dragOver\" style=\"width:173px\">" + dispOrder + "</td>";
return element;
},
axis: "y",
container: $(gridId)
});
$(gridId).kendoDropTargetArea({
filter: rowClass,
drop: function (e) {
var srcUid = e.draggable.element.data("uid");
var tgtUid = e.dropTarget.data("uid");
var ds = $(gridId).data("kendoGrid").dataSource;
var srcItem = ds.getByUid(srcUid);
var tgtItem = ds.getByUid(tgtUid);
var dstIdx = ds.indexOf(tgtItem);
ds.remove(srcItem);
ds.insert(dstIdx, srcItem);
e.draggable.destroy();
UnsavedWarningsModule.SetUnsavedChanges();
kendo.addDragAndDropToGrid(gridId, rowClass, viewModel);
},
dragenter: function (e) {
e.draggable.hint.css("opacity", 0.3);
},
dragleave: function (e) {
e.draggable.hint.css("opacity", 1);
var srcUid = e.draggable.element.data("uid");
var tgtUid = e.dropTarget.data("uid");
var ds = $(gridId).data("kendoGrid").dataSource;
var srcItem = ds.getByUid(srcUid);
var srcDispOrd = srcItem.Display;
var tgtItem = ds.getByUid(tgtUid);
var tgtDispOrd = tgtItem.Display;
var dstIdx = ds.indexOf(tgtItem);
//--update display orders after dropping
ds._data.forEach(function (data) {
//if dragging it to a spot with higher dispOrder
if (tgtDispOrd > srcDispOrd) {
if (data.Display <= tgtDispOrd && data.Display > srcDispOrd) {
data.Display -= 1;
}
}
//if dragging it to a spot with lower dispOrder
if (srcDispOrd > tgtDispOrd) {
if (data.Display >= tgtDispOrd && data.Display < srcDispOrd) {
data.Display += 1;
}
}
});
srcItem.Display = tgtDispOrd;
//--end
ds.remove(srcItem);
ds.insert(dstIdx, srcItem);
}
});
};
var dataService = (function () {
"use strict";
var self = {};
self.getAddresses = function () {
var data = new kendo.data.ObservableArray([newData]);
// Manual create a promise, so this function mimicks an Ajax call.
var dfd = new $.Deferred();
dfd.resolve(data);
return dfd.promise();
};
return self;
})(kendo);
var controller = (function (dataService, viewModel) {
"use strict";
var _dataService = dataService;
var _vm = viewModel;
var self = {};
self.handleAddressesRefresh = function (data) {
_vm.set("addresses", new kendo.data.DataSource({ data: data }));
kendo.bind($("#KendoGridContainer"), _vm);
kendo.addDragAndDropToGrid("#ChangeDisplayOrderGrid", ".k-master-row", _vm);
};
self.show = function () {
$.when(_dataService.getAddresses())
.then(self.handleAddressesRefresh);
};
return self;
})(dataService, viewModel);
controller.show();});
I think it's something to do with the timing of the loading of the page, possibly with the promise I'm using?
Thanks!

How to use Jasmine/Javascript for anonymous functions

I've spent a lot of time trying to figure out how to go inside anonymous functions in jasmine.
Sample of method:
numerateColumns: function (rows) {
rows.each(function () {
var $row = $(this);
$row.children().each(function (index) {
var $cell = $(this);
$cell.addClass('column-' + (index + 1));
});
});
}
Try to test with:
it("[TEST] Should call each method.", function () {
// setup
var rows = {
each: function () {
return {
children: function () {
return {
replaceWith: function () {
return null;
}
};
}
};
}
};
spyOn(rows, 'each').and.callThrough();
// method under test
module.numerateColumns(rows);
// expectations
expect(rows.each).toHaveBeenCalled();
});
But coverage test shows me that code of method is read only in first line (rows.each).
How to force it to read all the code inside (function() {}) ?
Why you want to test jQuery? It works perfectly, if not - some tests probably it will catch before new version publication.
function numerateColumns($rows) {
$rows.each(function() {
var $row = $(this);
$row.children().each(function(index) {
var $cell = $(this);
$cell.addClass('column-' + (index + 1));
});
});
}
describe('Iterate over columns`', function() {
var mockRows
beforeEach(function() {
mockRows = $('<div><div></div></div>')
})
it("calls .each() on passed jQuery collection", function() {
spyOn($, 'each').and.callThrough();
expect($.each).not.toHaveBeenCalled();
numerateColumns(mockRows);
expect($.each).toHaveBeenCalled();
});
it("adds CSS class to each child", function() {
var column = $(mockRows[0]).find('div');
expect(column.hasClass('column-1')).toBeFalsy()
numerateColumns(mockRows);
expect(column.hasClass('column-1')).toBeTruthy()
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="//safjanowski.github.io/jasmine-jsfiddle-pack/pack/jasmine.css" rel="stylesheet" />
<script src="//safjanowski.github.io/jasmine-jsfiddle-pack/pack/jasmine-2.0.3-concated.js"></script>
What you can test - it is extracted business logic that is independent to jQuery itself.

Blueimp jQuery File Upload Audio/Video Preview

After some googling, I cant find an example of using the audio & video preview extensions of the jQuery file upload plugin.
http://blueimp.github.io/jQuery-File-Upload/
Has anyone used these who can provide a minimal example?
you just have to add the jquery.fileupload-video file when you use the plugin for upload your videos. This is how I use it
$(function () {
'use strict';
var url = YourURL+"public/server/php/";
$('#fileupload').fileupload({
url: url,
method: 'POST',
dataType: 'json',
autoUpload: true,
acceptFileTypes: /(\.|\/)(mp4)$/i,
maxFileSize: 40000000, // 40 MB
disableImageResize: /Android(?!.*Chrome)|Opera/
.test(window.navigator.userAgent),
previewMaxWidth: 300,
previewMaxHeight: 200,
previewCrop: true,
}).on('fileuploadadd', function (e, data) {
data.context = $('<div class="col-md-3 videopreview" />').appendTo('#files');
$.each(data.files, function (index, file) {
var node = $('<p/>');
if (!index) {
node
.append('<br>')
}
node.appendTo(data.context);
});
}).on('fileuploadprocessalways', function (e, data) {
var index = data.index,
file = data.files[index],
node = $(data.context.children()[index]);
if (file.preview) {
node
.prepend('<br>')
.prepend(file.preview);
}
if (file.error) {
node
.append('<br>')
.append($('<span class="text-danger"/>').text(file.error));
}
if (index + 1 === data.files.length) {
data.context.find('button')
.text('Upload')
.prop('disabled', !!data.files.error);
}
}).on('fileuploadprogressall', function (e, data) {
var progress = parseInt(data.loaded / data.total * 100, 10);
$('#progress .progress-bar').css(
'width',
progress + '%'
);
}).on('fileuploaddone', function (e, data) {
$.each(data.result.files, function (index, file) {
if (file.url) {
var link = $('<a>')
.attr('target', '_blank')
.prop('href', file.url);
$(data.context.children()[index])
.wrap(link).append($('<span/>').text(file.name));
$( "#filesHidden" ).append( '<input type="hidden" name="images[]" value="' + file.name + '">' );
} else if (file.error) {
var error = $('<span class="text-danger"/>').text(file.error);
$(data.context.children()[index])
.append('<br>')
.append(error);
}
});
}).on('fileuploadfail', function (e, data) {
$.each(data.files, function (index, file) {
var error = $('<span class="text-danger"/>').text('File upload failed.');
$(data.context.children()[index])
.append('<br>')
.append(error);
});
}).prop('disabled', !$.support.fileInput)
.parent().addClass($.support.fileInput ? undefined : 'disabled');
});
Also remember to add the following
jquery.ui.widget.js
load-image.min.js
jquery.iframe-transport.js
jquery.fileupload.js
jquery.fileupload-validate-es_ES.js //This is just for the language
jquery.fileupload.css

Resources