Is there an way to make loading progress bar run again in visjs? - vis.js

I have created a new network visualization using visjs and I follow the example here: http://visjs.org/examples/network/exampleApplications/loadingBar.html to implement a loading progress bar and it worked perfectly.
I can switch to other 2 visualizations using a radio button. When I load the other visualizations the loading bar doesn't appear again.
I would like to know how to call the loading bar again.
Thanks in advance.
...
<input type="radio" name="op" onclick="net1()" checked>
<input type="radio" name="op" onclick="net2()">
<div id="wrapper">
<div id="network1"></div>
<div id="network2" style="display: none;"></div>
<div id="loadingBar">
<div class="outerBorder" style="left: 100%;">
<div id="text">0%</div>
<div id="border">
<div id="bar"></div>
</div>
</div>
</div>
</div>
<script>
function function1(){
...//create network
network.on("stabilizationProgress", function (params) {
var maxWidth = 496;
var minWidth = 20;
var widthFactor = params.iterations / params.total;
var width = Math.max(minWidth, maxWidth * widthFactor);
document.getElementById('bar').style.width = width + 'px';
document.getElementById('text').innerHTML = Math.round(widthFactor * 100) + '%';
});
network.once("stabilizationIterationsDone", function () {
document.getElementById('text').innerHTML = '100%';
document.getElementById('bar').style.width = '496px';
document.getElementById('loadingBar').style.opacity = 0;
setTimeout(function () {
document.getElementById('loadingBar').style.display = 'none';
}, 500);
});
}
function function2(){
...//create onther network
network.on("stabilizationProgress", function (params) {
var maxWidth = 496;
var minWidth = 20;
var widthFactor = params.iterations / params.total;
var width = Math.max(minWidth, maxWidth * widthFactor);
document.getElementById('bar').style.width = width + 'px';
document.getElementById('text').innerHTML = Math.round(widthFactor * 100) + '%';
});
network.once("stabilizationIterationsDone", function () {
document.getElementById('text').innerHTML = '100%';
document.getElementById('bar').style.width = '496px';
document.getElementById('loadingBar').style.opacity = 0;
setTimeout(function () {
document.getElementById('loadingBar').style.display = 'none';
}, 500);
});
}
</script>
<script>
function net1() {
function1();
document.getElementById('network1').style.display = "block";
document.getElementById('network2').style.display = "none";
}
function net2() {
document.getElementById('network1').style.display = "none";
function2();
document.getElementById('network2').style.display = "block";
}
</script>

I solved it changing the methods stabilizationProgress and stabilizationIterationsDone to:
network.on("stabilizationProgress", function (params) {
document.getElementById('loadingBar').style.opacity = 1;
var maxWidth = 496;
var minWidth = 20;
var widthFactor = params.iterations / params.total;
var width = Math.max(minWidth, maxWidth * widthFactor);
document.getElementById('bar').style.width = width + 'px';
document.getElementById('text').innerHTML = Math.round(widthFactor * 100) + '%';
});
network.on("stabilizationIterationsDone", function () {
document.getElementById('text').innerHTML = '100%';
document.getElementById('bar').style.width = '496px';
document.getElementById('loadingBar').style.opacity = 0;
});

Related

Google Place Search using SearchBox - Restrict for UK only

I am using google place SearchBox ( not AutoComplete ) for place search. My objective is I want to restrict the search for a particular country (UK).
I know the same thing can be achieved easily by using AutoComplete. But I can't use this because my map will populate on enter key as well as against a search button.
I am using code to select the first option on search button click.
I have tried with google.maps.LatLngBounds but that only sets the priority of result, not restricting anything.
Html:
<ul class="list-unstyled search-branch">
<li>Search branches:</li>
<li><input type="text" placeholder="City, town or postcode" id="txtbranch" value="Eurochange" />
<input type="button" class="button gold" id="getbranch" value="Search" />
<div style="clear:both;"></div>
<div class="error-message-summary" id="locationnotfound" style="padding: 0;top:-30px; position:relative; font-size:16px;display:none">
No search results found.
</div>
</li>
</ul>
js:
var input = document.getElementById('txtbranch');
var defaultBounds = new google.maps.LatLngBounds(
new google.maps.LatLng(-33.8902, 151.1759),
new google.maps.LatLng(-33.8474, 1512631)
);
var options = {
bounds: defaultBounds
}
var searchBox = new google.maps.places.SearchBox(input, {
bounds: defaultBounds
});
$('#getbranch').click(function () {
var input = document.getElementById('txtbranch');
if (BranchAddressSelector.val() == "") {
return;
}
google.maps.event.trigger(input, 'focus');
google.maps.event.trigger(input, 'keydown', { keyCode: 13 });
return false;
})
searchBox.addListener('places_changed', function () {
var places = searchBox.getPlaces()[0];
if (typeof (places) === "undefined") {
locationNotFoundSelector.css("display", "block");
return false;
}
if (BranchAddressSelector.val() == "") {
return false;
}
var address = places.formatted_address;
if (typeof (address) === "undefined") {
locationNotFoundSelector.css("display", "block");
return false;
}
var latitude = places.geometry.location.lat();
var longitude = places.geometry.location.lng();
$.ajax({
type: "GET",
url: BranchLocatorUrl.GetBranches,
data: { Latitude: latitude, longitude: longitude },
success: function (data) {
if (data.length > 0) {
markers = data;
LoadMap(0, 0);
BranchListSelector.html(CreateSearchHtml(markers));
goToByScroll("dvMap");
BranchListSelector.css("display", "none");
paginationSelector.css("display", "none");
$('.map-distance').css("display", "block");
locationNotFoundSelector.css("display", "none");
var show_per_page = 6;
var number_of_items = BranchListSelector.children('.BranchItem').size();
var number_of_pages = Math.ceil(number_of_items / show_per_page);
totalPages = number_of_pages;
$('#current_page').val(0);
$('#show_per_page').val(show_per_page);
var navigation_html = '<a class="previous_link" style="color: #007ea0;" href="javascript:previous();">Prev</a> ';
var current_link = 0;
while (number_of_pages > current_link) {
navigation_html += '<a class="page_link" style="color: #007ea0;" href="javascript:go_to_page(' + current_link + ')" longdesc="' + current_link + '">' + (current_link + 1) + '</a> ';
current_link++;
}
navigation_html += '<a class="next_link" style="color: #007ea0;" href="javascript:next();"> Next</a>';
$('#page_navigation').html(navigation_html).css("float", "right").css("display", "none");
$('#page_navigation .page_link:first').addClass('active_page');
BranchListSelector.children('.BranchItem').css('display', 'none');
BranchListSelector.children('.BranchItem').slice(0, show_per_page).css('display', 'block');
BranchListSelector.css("display", "block");
// paginationSelector.css("display", "block");
$('.map-distance').css("display", "none");
$('#moreBranch').css("display", "block");
}
else {
alert("Data not found.");
}
},
error: function (e) {
alert("Some Problem occurs.Try after some time");
return;
}
});
});

Lightbox2 rotate not working

Does anyone have a sample project for lightbox2 rotate? I have applied all the javascript and css for this example http://jsfiddle.net/pootie/EBLc7/
and the rotate button never seems to show. What am I missing please help me
HTML CODE:
<img src="http://grgichtran.com/code/img/car-seat.jpg" class="img-polaroid" style="width: 100px;"/>
JS CODE:
(function () {
var $, Lightbox, LightboxOptions;
$ = jQuery;
LightboxOptions = (function () {
function LightboxOptions() {
this.fadeDuration = 500;
this.fitImagesInViewport = true;
this.resizeDuration = 700;
this.showImageNumberLabel = true;
this.wrapAround = false;
}
LightboxOptions.prototype.albumLabel = function (curImageNum, albumSize) {
return "Image " + curImageNum + " of " + albumSize;
};
return LightboxOptions;
})();
Lightbox = (function () {
function Lightbox(options) {
this.options = options;
this.album = [];
this.currentImageIndex = void 0;
this.init();
}
Lightbox.prototype.init = function () {
this.enable();
return this.build();
};
Lightbox.prototype.enable = function () {
var _this = this;
return $('body').on('click', 'a[rel^=lightbox], area[rel^=lightbox], a[data-lightbox], area[data-lightbox]', function (e) {
_this.start($(e.currentTarget));
return false;
});
};
Lightbox.prototype.build = function () {
var _this = this;
$("<div id='lightboxOverlay' class='lightboxOverlay'></div><div id='lightbox' class='lightbox'><div class='lb-outerContainer'><div class='lb-container'><img class='lb-image' src='' /><div class='lb-nav'><a class='lb-prev' href='' ></a><a class='lb-next' href='' ></a></div><div class='lb-loader'><a class='lb-cancel'></a></div></div></div><div class='lb-dataContainer'><div class='lb-data'><div class='lb-details'><span class='lb-caption'></span><span class='lb-number'></span></div><div class='lb-closeContainer'><a class='lb-close'></a><a class='lb-rotate'></a></div></div></div></div>").appendTo($('body'));
this.$lightbox = $('#lightbox');
this.$overlay = $('#lightboxOverlay');
this.$outerContainer = this.$lightbox.find('.lb-outerContainer');
this.$container = this.$lightbox.find('.lb-container');
this.containerTopPadding = parseInt(this.$container.css('padding-top'), 10);
this.containerRightPadding = parseInt(this.$container.css('padding-right'), 10);
this.containerBottomPadding = parseInt(this.$container.css('padding-bottom'), 10);
this.containerLeftPadding = parseInt(this.$container.css('padding-left'), 10);
this.$overlay.hide().on('click', function () {
_this.end();
return false;
});
this.$lightbox.hide().on('click', function (e) {
if ($(e.target).attr('id') === 'lightbox') {
_this.end();
}
return false;
});
this.$outerContainer.on('click', function (e) {
if ($(e.target).attr('id') === 'lightbox') {
_this.end();
}
return false;
});
this.$lightbox.find('.lb-prev').on('click', function () {
if (_this.currentImageIndex === 0) {
_this.changeImage(_this.album.length - 1);
} else {
_this.changeImage(_this.currentImageIndex - 1);
}
return false;
});
this.$lightbox.find('.lb-next').on('click', function () {
if (_this.currentImageIndex === _this.album.length - 1) {
_this.changeImage(0);
} else {
_this.changeImage(_this.currentImageIndex + 1);
}
return false;
});
this.$lightbox.find('.lb-rotate').on('click', function () {
$cont = _this.$lightbox.find('.lb-outerContainer');
$image = _this.$lightbox.find('.lb-image');
if ($($cont).attr('angle') == null) {
$($cont).attr('angle', 0);
}
var value = Number($($cont).attr('angle'));
value += 90;
$($cont).rotate({
animateTo: value
});
$($cont).attr('angle', value);
return false;
});
return this.$lightbox.find('.lb-loader, .lb-close').on('click', function () {
_this.end();
return false;
});
};
Lightbox.prototype.start = function ($link) {
var $window, a, dataLightboxValue, i, imageNumber, left, top, _i, _j, _len, _len1, _ref, _ref1;
$(window).on("resize", this.sizeOverlay);
$('select, object, embed').css({
visibility: "hidden"
});
this.$overlay.width($(document).width()).height($(document).height()).fadeIn(this.options.fadeDuration);
this.album = [];
imageNumber = 0;
dataLightboxValue = $link.attr('data-lightbox');
if (dataLightboxValue) {
_ref = $($link.prop("tagName") + '[data-lightbox="' + dataLightboxValue + '"]');
for (i = _i = 0, _len = _ref.length; _i < _len; i = ++_i) {
a = _ref[i];
this.album.push({
link: $(a).attr('href'),
title: $(a).attr('title')
});
if ($(a).attr('href') === $link.attr('href')) {
imageNumber = i;
}
}
} else {
if ($link.attr('rel') === 'lightbox') {
this.album.push({
link: $link.attr('href'),
title: $link.attr('title')
});
} else {
_ref1 = $($link.prop("tagName") + '[rel="' + $link.attr('rel') + '"]');
for (i = _j = 0, _len1 = _ref1.length; _j < _len1; i = ++_j) {
a = _ref1[i];
this.album.push({
link: $(a).attr('href'),
title: $(a).attr('title')
});
if ($(a).attr('href') === $link.attr('href')) {
imageNumber = i;
}
}
}
}
$window = $(window);
top = $window.scrollTop() + $window.height() / 10;
left = $window.scrollLeft();
this.$lightbox.css({
top: top + 'px',
left: left + 'px'
}).fadeIn(this.options.fadeDuration);
this.changeImage(imageNumber);
};
Lightbox.prototype.changeImage = function (imageNumber) {
var $image, preloader,
_this = this;
this.disableKeyboardNav();
$image = this.$lightbox.find('.lb-image');
this.sizeOverlay();
this.$overlay.fadeIn(this.options.fadeDuration);
$('.lb-loader').fadeIn('slow');
this.$lightbox.find('.lb-image, .lb-nav, .lb-prev, .lb-next, .lb-dataContainer, .lb-numbers, .lb-caption').hide();
this.$outerContainer.addClass('animating');
preloader = new Image();
preloader.onload = function () {
var $preloader, imageHeight, imageWidth, maxImageHeight, maxImageWidth, windowHeight, windowWidth;
$image.attr('src', _this.album[imageNumber].link);
$preloader = $(preloader);
$image.width(preloader.width);
$image.height(preloader.height);
if (_this.options.fitImagesInViewport) {
windowWidth = $(window).width();
windowHeight = $(window).height();
maxImageWidth = windowWidth - _this.containerLeftPadding - _this.containerRightPadding - 20;
maxImageHeight = windowHeight - _this.containerTopPadding - _this.containerBottomPadding - 110;
if ((preloader.width > maxImageWidth) || (preloader.height > maxImageHeight)) {
if ((preloader.width / maxImageWidth) > (preloader.height / maxImageHeight)) {
imageWidth = maxImageWidth;
imageHeight = parseInt(preloader.height / (preloader.width / imageWidth), 10);
$image.width(imageWidth);
$image.height(imageHeight);
} else {
imageHeight = maxImageHeight;
imageWidth = parseInt(preloader.width / (preloader.height / imageHeight), 10);
$image.width(imageWidth);
$image.height(imageHeight);
}
}
}
return _this.sizeContainer($image.width(), $image.height());
};
preloader.src = this.album[imageNumber].link;
this.currentImageIndex = imageNumber;
};
Lightbox.prototype.sizeOverlay = function () {
return $('#lightboxOverlay').width($(document).width()).height($(document).height());
};
Lightbox.prototype.sizeContainer = function (imageWidth, imageHeight) {
var newHeight, newWidth, oldHeight, oldWidth,
_this = this;
oldWidth = this.$outerContainer.outerWidth();
oldHeight = this.$outerContainer.outerHeight();
newWidth = imageWidth + this.containerLeftPadding + this.containerRightPadding;
newHeight = imageHeight + this.containerTopPadding + this.containerBottomPadding;
this.$outerContainer.animate({
width: newWidth,
height: newHeight
}, this.options.resizeDuration, 'swing');
setTimeout(function () {
_this.$lightbox.find('.lb-dataContainer').width(newWidth);
_this.$lightbox.find('.lb-prevLink').height(newHeight);
_this.$lightbox.find('.lb-nextLink').height(newHeight);
_this.showImage();
}, this.options.resizeDuration);
};
Lightbox.prototype.showImage = function () {
this.$lightbox.find('.lb-loader').hide();
this.$lightbox.find('.lb-image').fadeIn('slow');
this.updateNav();
this.updateDetails();
this.preloadNeighboringImages();
this.enableKeyboardNav();
};
Lightbox.prototype.updateNav = function () {
this.$lightbox.find('.lb-nav').show();
if (this.album.length > 1) {
if (this.options.wrapAround) {
this.$lightbox.find('.lb-prev, .lb-next').show();
} else {
if (this.currentImageIndex > 0) {
this.$lightbox.find('.lb-prev').show();
}
if (this.currentImageIndex < this.album.length - 1) {
this.$lightbox.find('.lb-next').show();
}
}
}
};
Lightbox.prototype.updateDetails = function () {
var _this = this;
if (typeof this.album[this.currentImageIndex].title !== 'undefined' && this.album[this.currentImageIndex].title !== "") {
this.$lightbox.find('.lb-caption').html(this.album[this.currentImageIndex].title).fadeIn('fast');
}
if (this.album.length > 1 && this.options.showImageNumberLabel) {
this.$lightbox.find('.lb-number').text(this.options.albumLabel(this.currentImageIndex + 1, this.album.length)).fadeIn('fast');
} else {
this.$lightbox.find('.lb-number').hide();
}
this.$outerContainer.removeClass('animating');
this.$lightbox.find('.lb-dataContainer').fadeIn(this.resizeDuration, function () {
return _this.sizeOverlay();
});
};
Lightbox.prototype.preloadNeighboringImages = function () {
var preloadNext, preloadPrev;
if (this.album.length > this.currentImageIndex + 1) {
preloadNext = new Image();
preloadNext.src = this.album[this.currentImageIndex + 1].link;
}
if (this.currentImageIndex > 0) {
preloadPrev = new Image();
preloadPrev.src = this.album[this.currentImageIndex - 1].link;
}
};
Lightbox.prototype.enableKeyboardNav = function () {
$(document).on('keyup.keyboard', $.proxy(this.keyboardAction, this));
};
Lightbox.prototype.disableKeyboardNav = function () {
$(document).off('.keyboard');
};
Lightbox.prototype.keyboardAction = function (event) {
var KEYCODE_ESC, KEYCODE_LEFTARROW, KEYCODE_RIGHTARROW, key, keycode;
KEYCODE_ESC = 27;
KEYCODE_LEFTARROW = 37;
KEYCODE_RIGHTARROW = 39;
keycode = event.keyCode;
key = String.fromCharCode(keycode).toLowerCase();
if (keycode === KEYCODE_ESC || key.match(/x|o|c/)) {
this.end();
} else if (key === 'p' || keycode === KEYCODE_LEFTARROW) {
if (this.currentImageIndex !== 0) {
this.changeImage(this.currentImageIndex - 1);
}
} else if (key === 'n' || keycode === KEYCODE_RIGHTARROW) {
if (this.currentImageIndex !== this.album.length - 1) {
this.changeImage(this.currentImageIndex + 1);
}
}
};
Lightbox.prototype.end = function () {
this.disableKeyboardNav();
$(window).off("resize", this.sizeOverlay);
this.$lightbox.fadeOut(this.options.fadeDuration);
this.$overlay.fadeOut(this.options.fadeDuration);
return $('select, object, embed').css({
visibility: "visible"
});
};
return Lightbox;
})();
$(function () {
var lightbox, options;
options = new LightboxOptions();
return lightbox = new Lightbox(options);
});
}).call(this);
I'm not sure what your question is; please allow me to confirm that after applying the code in your project,
the lightbox shows up properly, but rotate button doesn't
nothing special shows up. Neither lightbox, nor rotate button show up.
If your question is the first one, please check if the rotate button image (rotate.png) is placed in proper path. From the css file, this image should be put in img/ folder.
From this sample's css, rotate.png should be here:
background: url(../img/rotate.png) top right no-repeat;
On the other hand, if your question is second one, please check all files (js/css/images) exist and are in correct path, especially css and images.

label near icon in fusion tables map

I created a map showing some restaurant in a particular area. I used fusion tables as data entry and the code generated to display this map:
here is the link
I tried with no luck to add a text label with the name of the restaurant near the placemark ( icon ) .
Any ideas on how I can do?
I searched a lot in the forums, but I didn't find a solution.
Thank you very much
JT
(here is the code )
<!DOCTYPE html>
<html>
<head>
<meta name="viewport"></meta>
<title>Locali in zona Fiume e Quarnero - Google Fusion Tables</title>
<style type="text/css">
html, body, #googft-mapCanvas { height:100%; margin: 0; padding: 0;}
</style>
<script type="text/javascript" src="https://maps.google.com/maps/api/js? sensor=false&v=3"></script>
<script type="text/javascript">
function initialize() {
google.maps.visualRefresh = true;
var isMobile = (navigator.userAgent.toLowerCase().indexOf('android') > -1) ||
(navigator.userAgent.match(/(iPod|iPhone|iPad|BlackBerry|Windows Phone|iemobile)/));
if (isMobile) {
var viewport = document.querySelector("meta[name=viewport]");
viewport.setAttribute('content', 'initial-scale=1.0, user-scalable=no');
}
var mapDiv = document.getElementById('googft-mapCanvas');
mapDiv.style.width = isMobile ? '500px':'100%' ;
mapDiv.style.height = isMobile ? '300px':'100%' ;
var map = new google.maps.Map(mapDiv, {
center: new google.maps.LatLng(45.19975321105807, 14.824613028515614),
zoom: 10,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
map.controls[google.maps.ControlPosition.RIGHT_BOTTOM].push(document.getElementById('googft-legend-open'));
map.controls[google.maps.ControlPosition.RIGHT_BOTTOM].push(document.getElementById('googft-legend'));
layer = new google.maps.FusionTablesLayer({
map: map,
heatmap: { enabled: false },
query: {
select: "col6",
from: "1e8PEAUCopFkL9XqgVp1gJAv6Hh6ttGkMViOGhSZx",
where: ""
},
options: {
styleId: 2,
templateId: 2
}
});
if (isMobile) {
var legend = document.getElementById('googft-legend');
var legendOpenButton = document.getElementById('googft-legend-open');
var legendCloseButton = document.getElementById('googft-legend-close');
legend.style.display = 'none';
legendOpenButton.style.display = 'block';
legendCloseButton.style.display = 'block';
legendOpenButton.onclick = function() {
legend.style.display = 'block';
legendOpenButton.style.display = 'none';
}
legendCloseButton.onclick = function() {
legend.style.display = 'none';
legendOpenButton.style.display = 'block';
}
}
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="googft-mapCanvas"></div>
</body>
</html>
One option (for tables with less than a couple hundred rows) would be to query the table for the data using GViz and use that to add labels to the map.
proof of concept fiddle
google.load('visualization', '1', {'packages':['corechart', 'table', 'geomap']});
var tableid ="1e8PEAUCopFkL9XqgVp1gJAv6Hh6ttGkMViOGhSZx"
var map;
var labels = [];
function displayLabels() {
//set the query using the current bounds
var queryStr = "SELECT Posizione, Nome FROM "+ tableid;
var queryText = encodeURIComponent(queryStr);
var query = new google.visualization.Query('http://www.google.com/fusiontables/gvizdata?tq=' + queryText);
// alert(queryStr);
//set the callback function
query.send(displayLabelText);
}
function displayLabelText(response) {
if (!response) {
alert('no response');
return;
}
if (response.isError()) {
alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}
FTresponse = response;
//for more information on the response object, see the documentation
//http://code.google.com/apis/visualization/documentation/reference.html#QueryResponse
numRows = response.getDataTable().getNumberOfRows();
numCols = response.getDataTable().getNumberOfColumns();
// alert(numRows);
// var bounds = new google.maps.LatLngBounds();
for(i = 0; i < numRows; i++) {
var label = response.getDataTable().getValue(i, 1);
var labelStr = label.toString()
var positionStr = response.getDataTable().getValue(i, 0);
var position = positionStr.split(',');
var point = new google.maps.LatLng(
parseFloat(position[0]),
parseFloat(position[1]));
// bounds.extend(point);
labels.push(new InfoBox({
content: labelStr
,boxStyle: {
border: "1px solid black"
,textAlign: "center"
,backgroundColor:"white"
,fontSize: "8pt"
,width: "50px"
}
,disableAutoPan: true
,pixelOffset: new google.maps.Size(-25, 0)
,position: point
,closeBoxURL: ""
,isHidden: false
,enableEventPropagation: true
}));
labels[labels.length-1].open(map);
}
// zoom to the bounds
// map.fitBounds(bounds);
}
google.setOnLoadCallback(displayLabels);
code snippet:
google.load('visualization', '1', {
'packages': ['corechart', 'table', 'geomap']
});
var tableid = "1e8PEAUCopFkL9XqgVp1gJAv6Hh6ttGkMViOGhSZx"
var map;
var labels = [];
function displayLabels() {
//set the query using the current bounds
var queryStr = "SELECT Posizione, Nome FROM " + tableid;
var queryText = encodeURIComponent(queryStr);
var query = new google.visualization.Query('http://www.google.com/fusiontables/gvizdata?tq=' + queryText);
// alert(queryStr);
//set the callback function
query.send(displayLabelText);
}
function displayLabelText(response) {
if (!response) {
alert('no response');
return;
}
if (response.isError()) {
alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}
FTresponse = response;
//for more information on the response object, see the documentation
//http://code.google.com/apis/visualization/documentation/reference.html#QueryResponse
numRows = response.getDataTable().getNumberOfRows();
numCols = response.getDataTable().getNumberOfColumns();
// alert(numRows);
// var bounds = new google.maps.LatLngBounds();
for (i = 0; i < numRows; i++) {
var label = response.getDataTable().getValue(i, 1);
var labelStr = label.toString()
var positionStr = response.getDataTable().getValue(i, 0);
var position = positionStr.split(',');
var point = new google.maps.LatLng(
parseFloat(position[0]),
parseFloat(position[1]));
// bounds.extend(point);
labels.push(new InfoBox({
content: labelStr,
boxStyle: {
border: "1px solid black",
textAlign: "center",
backgroundColor: "white",
fontSize: "8pt",
width: "50px"
},
disableAutoPan: true,
pixelOffset: new google.maps.Size(-25, 0),
position: point,
closeBoxURL: "",
isHidden: false,
enableEventPropagation: true
}));
labels[labels.length - 1].open(map);
}
// zoom to the bounds
// map.fitBounds(bounds);
}
google.setOnLoadCallback(displayLabels);
function initialize() {
google.maps.visualRefresh = true;
var isMobile = (navigator.userAgent.toLowerCase().indexOf('android') > -1) || (navigator.userAgent.match(/(iPod|iPhone|iPad|BlackBerry|Windows Phone|iemobile)/));
if (isMobile) {
var viewport = document.querySelector("meta[name=viewport]");
viewport.setAttribute('content', 'initial-scale=1.0, user-scalable=no');
}
var mapDiv = document.getElementById('googft-mapCanvas');
mapDiv.style.width = isMobile ? '500px' : '100%';
mapDiv.style.height = isMobile ? '300px' : '100%';
map = new google.maps.Map(mapDiv, {
center: new google.maps.LatLng(45.19975321105807, 14.824613028515614),
zoom: 10,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
map.controls[google.maps.ControlPosition.RIGHT_BOTTOM].push(document.getElementById('googft-legend-open'));
map.controls[google.maps.ControlPosition.RIGHT_BOTTOM].push(document.getElementById('googft-legend'));
layer = new google.maps.FusionTablesLayer({
map: map,
heatmap: {
enabled: false
},
query: {
select: "col6",
from: "1e8PEAUCopFkL9XqgVp1gJAv6Hh6ttGkMViOGhSZx",
where: ""
},
options: {
styleId: 2,
templateId: 2
}
});
google.maps.event.addListenerOnce(map, 'bounds_changed', displayLabels);
if (isMobile) {
var legend = document.getElementById('googft-legend');
var legendOpenButton = document.getElementById('googft-legend-open');
var legendCloseButton = document.getElementById('googft-legend-close');
legend.style.display = 'none';
legendOpenButton.style.display = 'block';
legendCloseButton.style.display = 'block';
legendOpenButton.onclick = function() {
legend.style.display = 'block';
legendOpenButton.style.display = 'none';
}
legendCloseButton.onclick = function() {
legend.style.display = 'none';
legendOpenButton.style.display = 'block';
}
}
}
google.maps.event.addDomListener(window, 'load', initialize);
html,
body,
#googft-mapCanvas {
height: 100%;
margin: 0;
padding: 0;
}
<script src="https://maps.googleapis.com/maps/api/js?sensor=false&libraries=geometry,places&ext=.js"></script>
<script src="http://google-maps-utility-library-v3.googlecode.com/svn/trunk/infobox/src/infobox.js"></script>
<script src="http://www.google.com/jsapi"></script>
<div id="googft-mapCanvas"></div>

$.ajaxFileUpload used with canvas

How can I use the $.ajaxFileUpload to upload the image rendered in a canvas so that it will be part of the HttpContext.Current.Request.Files?
Works fine with normal file upload:
$.ajaxFileUpload({
url: "<%=AppRoot %>" + "upload",
secureuri: false,
fileElementId: "fld_image",
dataType: "json",
success: function (data, status) {
if (typeof (data.error) != "undefined") {
if (data.error) {
//print error
alert(data.error);
}
}
else {
$("#fld_image_hidden").remove();
$(".heading").css("background-image", "url(<%= AppRoot %>" + data.Url + ")");
var imagehidden = $("<input type=\"hidden\" id=\"fld_image_hidden\" name=\"fld_image_hidden\" value=\"" + data.Url + "|" + data.Name + "\" />");
$("#Template_ID").after(imagehidden);
}
$("#fld_image").remove();
},
error: function (data, status, e) {
alert(e);
}});
But cannot get it to work using canvas:
var upload = $("<input type=\"file\" id=\"fld_image\" name=\"fld_image\" />");
upload.on("change", function () {
if ($(this)[0].files[0].size > 5000000) {
alert("The file size may not exceed 5 MB.");
return;
}
var filesToUpload = $(this)[0].files;
var file = filesToUpload[0];
var img = document.createElement("img");
var reader = new FileReader();
reader.onload = function (e) {
console.log(e);
img.src = e.target.result;
var canvas = $("#canvasImage")[0];
var MAX_WIDTH = 500;
var MAX_HEIGHT = 500;
var width = img.width;
var height = img.height;
if (width > height) {
if (width > MAX_WIDTH) {
height *= MAX_WIDTH / width;
width = MAX_WIDTH;
}
} else {
if (height > MAX_HEIGHT) {
width *= MAX_HEIGHT / height;
height = MAX_HEIGHT;
}
}
canvas.width = width;
canvas.height = height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0, width, height);
var dataurl = canvas.toDataURL();
console.log(dataurl);
//Do ajaxFileUpload here
$.ajaxFileUpload({
url: "<%=AppRoot %>" + "upload",
secureuri: false,
fileElementId: "canvasImage",
dataType: "json",
success: function (data, status) {
},
error: function (data, status, e) {
alert(e);
}
});
});
The canvas is used to make the image smaller before uploading it to the server.
In the end I went this way, with guidance from this post, Canvas Upload:
var dataurl = canvas.toDataURL("image/png");
dataurl = dataurl.replace('data:image/png;base64,', '');
var ajax = new XMLHttpRequest();
ajax.open("POST", "<%=AppRoot %>" + "upload", false);
ajax.setRequestHeader("Content-Type", 'application/upload');
ajax.send(dataurl);
And on the server:
File.WriteAllBytes

jquery dialog result not updating the control

I'm updating the value of a textbox when the jqueryui.dialog is closed. It displays the value in the textbox but when the textbox gets focus the value disappears. I just can't figure out the reason. There is no onfocus/onblur event on the textbox.
I'm updating the textbox value like this
$("#mycontrol").val(displayresult);
$(html).dialog({
modal: true,
height: 300,
overflow: scroll,
buttons: {
"Select": function () {
$(this).dialog("close");
var value, splitPosition, itemValues, displayValues;
var displayresult = "";
var itemresult = "";
var septex = "";
var sepval = "";
$("input:checkbox" && "[id^=" + controlName + "_selectionBoxCheckBox]").each(function () {
var $this = $(this);
if ($this.is(":checked")) {
value = $this.val();
splitPosition = value.indexOf("-");
itemValues = $this.val().substr(0, splitPosition);
displayValues = $this.val().substr(splitPosition + 1);
itemresult += sepval + itemValues;
displayresult += septex + displayValues;
sepval = ",";
septex = ", ";
}
});
$("#mycontrol").val(displayresult);
$(this).dialog('destroy').remove();
},
Cancel: function () {
$(this).dialog("close");
}
},
close: function () {
//alert('close');
},
beforeClose: function (event, ui) {
//alert("before close");
}
});
I wrapped this with some HTML code and it works fine. There must be some other code causing the problem.
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script>
</head>
<body>
<form>
<input type="text" id="mycontrol" />
</form>
<div id="dialog" title="Dialog Title">
one <input type="checkbox" id="cb_selectionBoxCheckBox1" value="1-one" /><br />
two <input type="checkbox" id="cb_selectionBoxCheckBox2" value="2-two" /><br />
three <input type="checkbox" id="cb_selectionBoxCheckBox3" value="3-three" /><br />
</div>
<script type="text/javascript">
var displayresult="initial";
var controlName="cb";
var html='#dialog';
$().ready(function(){
$("#mycontrol").val(displayresult);
$(html).dialog({
modal: true,
height: 300,
overflow: scroll,
buttons: {
"Select": function () {
$(this).dialog("close");
var value, splitPosition, itemValues, displayValues;
var displayresult = "";
var itemresult = "";
var septex = "";
var sepval = "";
$("input:checkbox" && "[id^=" + controlName + "_selectionBoxCheckBox]").each(function () {
var $this = $(this);
if ($this.is(":checked")) {
value = $this.val();
splitPosition = value.indexOf("-");
itemValues = $this.val().substr(0, splitPosition);
displayValues = $this.val().substr(splitPosition + 1);
itemresult += sepval + itemValues;
displayresult += septex + displayValues;
sepval = ",";
septex = ", ";
}
});
$("#mycontrol").val(displayresult);
$(this).dialog('destroy').remove();
},
Cancel: function () {
$(this).dialog("close");
}
},
close: function () {
//alert('close');
},
beforeClose: function (event, ui) {
//alert("before close");
}
});
});
</script>
</body>
</html>

Resources