Signal R Chat application on IIS not working - asp.net

I am trying to build a SignalR application in Visual Studio 2012. My problem is that it works well under Visual Studio debug (using Visual Studio 2012 on Windows 7), but when I try to deploy the application on IIS 7.5 , the app does nothing more than displaying the index.html page.
my Index.html page is like :
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<link type="text/css" rel="stylesheet" href="Css/ChatStyle.css" />
<link rel="stylesheet" href="/Css/JQueryUI/themes/base/jquery.ui.all.css">
<!--Script references. -->
<!--Reference the jQuery library. -->
<script src="/Scripts/jquery-1.8.2.min.js"></script>
<script src="/Scripts/ui/jquery.ui.core.js"></script>
<script src="/Scripts/ui/jquery.ui.widget.js"></script>
<script src="/Scripts/ui/jquery.ui.mouse.js"></script>
<script src="/Scripts/ui/jquery.ui.draggable.js"></script>
<script src="/Scripts/ui/jquery.ui.resizable.js"></script>
<!--Reference the SignalR library. -->
<script src="/Scripts/jquery.signalR-1.0.0.js"></script>
<!--Reference the autogenerated SignalR hub script. -->
<script src="/signalr/hubs"></script>
<script type="text/javascript">
$(function () {
setScreen(false);
// Declare a proxy to reference the hub.
var chatHub = $.connection.chatHub;
registerClientMethods(chatHub);
// Start Hub
$.connection.hub.start().done(function () {
registerEvents(chatHub)
});
});
function setScreen(isLogin) {
if (!isLogin) {
$("#divChat").hide();
$("#divLogin").show();
}
else {
$("#divChat").show();
$("#divLogin").hide();
}
}
function registerEvents(chatHub) {
$("#btnStartChat").click(function () {
var name = $("#txtNickName").val();
if (name.length > 0) {
chatHub.server.connect(name);
}
else {
alert("Please enter name");
}
});
$('#btnSendMsg').click(function () {
var msg = $("#txtMessage").val();
if (msg.length > 0) {
var userName = $('#hdUserName').val();
chatHub.server.sendMessageToAll(userName, msg);
$("#txtMessage").val('');
}
});
$("#txtNickName").keypress(function (e) {
if (e.which == 13) {
$("#btnStartChat").click();
}
});
$("#txtMessage").keypress(function (e) {
if (e.which == 13) {
$('#btnSendMsg').click();
}
});
}
function registerClientMethods(chatHub) {
// Calls when user successfully logged in
chatHub.client.onConnected = function (id, userName, allUsers, messages) {
setScreen(true);
$('#hdId').val(id);
$('#hdUserName').val(userName);
$('#spanUser').html(userName);
// Add All Users
for (i = 0; i < allUsers.length; i++) {
AddUser(chatHub, allUsers[i].ConnectionId, allUsers[i].UserName);
}
// Add Existing Messages
for (i = 0; i < messages.length; i++) {
AddMessage(messages[i].UserName, messages[i].Message);
}
}
// On New User Connected
chatHub.client.onNewUserConnected = function (id, name) {
AddUser(chatHub, id, name);
}
// On User Disconnected
chatHub.client.onUserDisconnected = function (id, userName) {
$('#' + id).remove();
var ctrId = 'private_' + id;
$('#' + ctrId).remove();
var disc = $('<div class="disconnect">"' + userName + '" logged off.</div>');
$(disc).hide();
$('#divusers').prepend(disc);
$(disc).fadeIn(200).delay(2000).fadeOut(200);
}
chatHub.client.messageReceived = function (userName, message) {
AddMessage(userName, message);
}
chatHub.client.sendPrivateMessage = function (windowId, fromUserName, message) {
var ctrId = 'private_' + windowId;
if ($('#' + ctrId).length == 0) {
createPrivateChatWindow(chatHub, windowId, ctrId, fromUserName);
}
$('#' + ctrId).find('#divMessage').append('<div class="message"><span class="userName">' + fromUserName + '</span>: ' + message + '</div>');
// set scrollbar
var height = $('#' + ctrId).find('#divMessage')[0].scrollHeight;
$('#' + ctrId).find('#divMessage').scrollTop(height);
}
}
function AddUser(chatHub, id, name) {
var userId = $('#hdId').val();
var code = "";
if (userId == id) {
code = $('<div class="loginUser">' + name + "</div>");
}
else {
code = $('<a id="' + id + '" class="user" >' + name + '<a>');
$(code).dblclick(function () {
var id = $(this).attr('id');
if (userId != id)
OpenPrivateChatWindow(chatHub, id, name);
});
}
$("#divusers").append(code);
}
function AddMessage(userName, message) {
$('#divChatWindow').append('<div class="message"><span class="userName">' + userName + '</span>: ' + message + '</div>');
var height = $('#divChatWindow')[0].scrollHeight;
$('#divChatWindow').scrollTop(height);
}
function OpenPrivateChatWindow(chatHub, id, userName) {
var ctrId = 'private_' + id;
if ($('#' + ctrId).length > 0) return;
createPrivateChatWindow(chatHub, id, ctrId, userName);
}
function createPrivateChatWindow(chatHub, userId, ctrId, userName) {
var div = '<div id="' + ctrId + '" class="ui-widget-content draggable" rel="0">' +
'<div class="header">' +
'<div style="float:right;">' +
'<img id="imgDelete" style="cursor:pointer;" src="/Images/delete.png"/>' +
'</div>' +
'<span class="selText" rel="0">' + userName + '</span>' +
'</div>' +
'<div id="divMessage" class="messageArea">' +
'</div>' +
'<div class="buttonBar">' +
'<input id="txtPrivateMessage" class="msgText" type="text" />' +
'<input id="btnSendMessage" class="submitButton button" type="button" value="Send" />' +
'</div>' +
'</div>';
var $div = $(div);
// DELETE BUTTON IMAGE
$div.find('#imgDelete').click(function () {
$('#' + ctrId).remove();
});
// Send Button event
$div.find("#btnSendMessage").click(function () {
$textBox = $div.find("#txtPrivateMessage");
var msg = $textBox.val();
if (msg.length > 0) {
chatHub.server.sendPrivateMessage(userId, msg);
$textBox.val('');
}
});
// Text Box event
$div.find("#txtPrivateMessage").keypress(function (e) {
if (e.which == 13) {
$div.find("#btnSendMessage").click();
}
});
AddDivToContainer($div);
}
function AddDivToContainer($div) {
$('#divContainer').prepend($div);
$div.draggable({
handle: ".header",
stop: function () {
}
});
////$div.resizable({
//// stop: function () {
//// }
////});
}
</script>
</head>
<body>
<div id="header">
ABC BANK CHAT ROOM
</div>
<br />
<br />
<br />
<div id="divContainer">
<div id="divLogin" class="login">
<div>
Your Name:<br />
<input id="txtNickName" type="text" class="textBox" />
</div>
<div id="divButton">
<input id="btnStartChat" type="button" class="submitButton" value="Start Chat" />
</div>
</div>
<div id="divChat" class="chatRoom">
<div class="title">
Welcome to Chat Room [<span id='spanUser'></span>]
</div>
<div class="content">
<div id="divChatWindow" class="chatWindow">
</div>
<div id="divusers" class="users">
</div>
</div>
<div class="messageBar">
<input class="textbox" type="text" id="txtMessage" />
<input id="btnSendMsg" type="button" value="Send" class="submitButton" />
</div>
</div>
<input id="hdId" type="hidden" />
<input id="hdUserName" type="hidden" />
</div>
</body>
</html>
I have tried some of the methods listed here: Signalr/Hub not loading in IIS 7 but working correctly in Visual Studio, but none of them seem to work. Any help would be greatly appreciated. Thanks, chiranjit

I think you have to remove all the leading slashes "/"
(Ans maybe also upgrade to at least jquery-1.9.1)
<link type="text/css" rel="stylesheet" href="Css/ChatStyle.css" />
<link rel="stylesheet" href="Css/JQueryUI/themes/base/jquery.ui.all.css" />
<!--Script references. -->
<!--Reference the jQuery library. -->
<script src="Scripts/jquery-1.9.1.min.js"></script>
<script src="Scripts/ui/jquery.ui.core.js"></script>
<script src="Scripts/ui/jquery.ui.widget.js"></script>
<script src="Scripts/ui/jquery.ui.mouse.js"></script>
<script src="Scripts/ui/jquery.ui.draggable.js"></script>
<script src="Scripts/ui/jquery.ui.resizable.js"></script>
<!--Reference the SignalR library. -->
<script src="Scripts/jquery.signalR-1.0.0.js"></script>
<!--Reference the autogenerated SignalR hub script. -->
<script src="signalr/hubs"></script>

Related

When I type something long with no spaces, it goes off screen

I have some issues with making a chatroom. For some reason whenever I type a long letter or something without spaces, it goes off screen. If I were to add some spaces, it would work.
As you can see here
, the first message has spaces and it worked fine, but the second message had no spaces and it went off the screen, how would I fix this?
server.js
var PORT = process.env.PORT || 3000;
var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var moment = require('moment');
var connectedUsers = {};
app.use(express.static(__dirname + '/public'));
io.on('connection', function(socket) {
/*var socketId = socket.id;
var clientIp = socket.request.connection.remoteAddress;
console.log('A user is connected. - IP: ' + clientIp + " | ID: " + socketId);*/
console.log('A user is connected.')
socket.on('disconnect', function() {
var userData = connectedUsers[socket.id];
if (typeof userData !== 'undefined') {
socket.leave(connectedUsers[socket.id]);
io.to(userData.room).emit('message', {
username: 'System',
text: userData.username + ' has left!',
timestamp: moment().valueOf()
});
delete connectedUsers[socket.id];
}
});
socket.on('joinRoom', function(req, callback) {
if (req.room.replace(/\s/g, "").length > 0 && req.username.replace(/\s/g, "").length > 0) {
var nameTaken = false;
Object.keys(connectedUsers).forEach(function(socketId) {
var userInfo = connectedUsers[socketId];
if (userInfo.username.toUpperCase() === req.username.toUpperCase()) {
nameTaken = true;
}
});
if (nameTaken) {
callback({
nameAvailable: false,
error: 'This username is taken, please choose another one.'
});
} else {
connectedUsers[socket.id] = req;
socket.join(req.room);
socket.broadcast.to(req.room).emit('message', {
username: 'System',
text: req.username + ' has joined!',
timestamp: moment().valueOf()
});
callback({
nameAvailable: true
});
}
} else {
callback({
nameAvailable: false,
error: 'Please complete the forum.'
});
}
});
socket.on('message', function(message) {
message.timestamp = moment().valueOf();
io.to(connectedUsers[socket.id].room).emit('message', message);
});
socket.emit('message', {
username: 'System',
text: 'Ask someone to join this chat room to start talking.',
timestamp: moment().valueOf()
});
});
http.listen(PORT, function() {
console.log('Server started on port ' + PORT);
});
index.html body:
<body>
<div class="container">
<div id="login-area">
<div class="row">
<div class="large-7 medium-7 small-12 columns small-centered">
<form id="login-form">
<h2>Twintails🎀 Bot Chatroom</h2>
<p id="error-msg"></p>
<input
type="text"
name="username"
placeholder="Enter your username"
/>
<input
type="text"
name="room"
placeholder="Enter a chat room name"
/>
<input type="submit" value="Join Chat" />
</form>
</div>
</div>
</div>
<div class="row" id="message-area">
<div class="large-8 columns small-centered">
<h2>Twintails🎀 Bot Chatroom</h2>
<div class="chat-wrap">
<div class="top">
<h5 class="room-title"></h5>
</div>
<div id="messages"></div>
<form id="message-form">
<div class="input-group">
<input
type="text"
placeholder="Type message here"
class="input-group-field"
name="message"
/>
<div class="input-group-button">
<input type="submit" value="Send" />
</div>
</div>
</form>
</div>
</div>
</div>
<footer>
<p>
Add the
<a href="https://twintails-bot-dashboard.glitch.me/" target="_blank"
>Twintails🎀 bot!</a
>
</p>
<p>
Use the 'Mod' room to talk to mods!
</p>
</footer>
</div>
<script src="/js/jquery.js"></script>
<script src="/js/socket.io-1.7.3.min.js"></script>
<script src="/js/moment.min.js"></script>
<script src="/js/app.js"></script>
<script src="/js/foundation.min.js"></script>
<script type="text/javascript">
$(document).foundation();
</script>
</body>
If you need some info on the css, just comment and I'll edit this post.

Blueimp File Upload: How to delete file? (MVC)

I'm attempting to tie Blueimp File Uploader into my MVC 5 solution. I have the uploads working as follows:
<span class="btn btn-success fileinput-button">
<i class="glyphicon glyphicon-plus"></i>
<span>Add files...</span>
<input id="fileupload" type="file" name="files[]" multiple>
</span>
<br />
<div class="progress">
<div class="progress-bar" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width: 0%;">
<span class="sr-only">0% complete</span>
</div>
</div>
<br />
<div class="file_name"></div>
<br />
<div class="file_type"></div>
<br />
<div class="file_size"></div>
<!-- The container for the uploaded files -->
<div id="files" class="files"></div>
and the javascript
$(document).ready(function () {
var Url = "#Url.Content("~/Advertise/UploadFiles")";
$('#fileupload').fileupload({
dataType: 'json',
url: Url,
autoUpload: true,
done: function (e, data) {
// $('.file_name').html(data.result.name);
// $('.file_type').html(data.result.type);
// $('.file_size').html(data.result.size);
}
}).on('fileuploadadd', function (e, data) {
data.context = $('<div/>').appendTo('#files');
$.each(data.files, function (index, file) {
var node = $('<p/>')
.append('<img src="' + URL.createObjectURL(data.files[0]) + '" height="50" width="50"/>').append($('<span/>').text(file.name));
if (!index) {
node
.append('<br>')
//.append(uploadButton.clone(true).data(data));
}
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);
} 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) {
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');
});
I've not tested a lot of the jQuery above. But I'm looking in to how I can delete an uploaded file? I could probably do it by calling a jQuery ajax post, but I think Blueimp has a native way to do it. But I can't find any documentation on it?? Any help appreciated.

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>

Add 'See on Map' Link in Fusion Tables Map List View

I am using the wonderful Fusion Tables Map Template by Derek Eder. I have activated the results list as instructed by him here.
I would like to have a 'See on Map' link on each listing so that when i click on the link the page scrolls up to the map and opens an infowindow for that particular listing. You can see an example on the geo places theme.
Below is my code
HTML
<!DOCTYPE html>
<html lang='en'>
<head>
<link rel="stylesheet" href="bootstrap.spacelab.min.css"/>
<link rel="stylesheet" href="bootstrap-responsive.min.css"/>
<link rel="stylesheet" href="custom.css"/>
<!-- HTML5 shim, for IE6-8 support of HTML5 elements -->
</head>
<body>
<div class='navbar'>
<div class='navbar-inner'>
<div class='container'>
<a class='brand' href='/'>Worldwide Stores</a>
</div>
</div>
</div>
<div class='container-fluid'>
<div class='row-fluid'>
<div class='span4'>
<div class='well'>
<h4>
Address <small>(<a id='find_me' href='#'>find me</a>)</small>
</h4>
<input class='input-block-level' id='search_address' placeholder='Enter an address or an intersection' type='text' />
<label>
show companies within
<select class='input-small' id='search_radius'>
<option value='400'>2 blocks</option>
<option value='805'>1/2 mile</option>
<option value='1610'>1 mile</option>
<option value='3220'>2 miles</option>
<option value='8050'>5 miles</option>
<option value='16100'>10 miles</option>
<option value='40250'>25 miles</option>
<option value='80500'>50 miles</option>
<option value='161000'>100 miles</option>
<option value='402500'>250 miles</option>
<option value='805000'>500 miles</option>
<option value='1610000'>1000 miles</option>
</select>
</label>
<h5> Refine Your Search By:</h5>
<label>
<select id='select_type'>
<option value=''>All Categories</option>
<option value='Hotels'>Hotels</option>
<option value='Restaurants'>Restaurants</option>
<option value='Shopping Malls'>Shopping Malls</option>
<option value='Travel Agents'>Travel Agents</option>
</select>
</label>
<label>
<select disabled id='select_type1'>
<option value=''>Select Two</option>
<option value='male'>Male</option>
<option value='female'>Female</option>
</select>
</label>
<label>
<select disabled id='select_type2'>
<option value=''>Select Three</option>
<option value='Advanced Materials/Prd'>Advanced Materials/Prd</option>
<option value='Advertising Agencies'>Advertising Agencies</option>
<option value='Advertising Sales'>Advertising Sales</option>
<option value='Advertising Services'>Advertising Services</option>
</select>
</label>
<input class='btn btn-primary' id='search' type='button' value='Search' />
<button class='btn' id='reset'>Reset</button>
</div>
<p class='alert alert-info lead' id='result_count'></p>
</p> </p>
</p> </p>
</p> </p>
</div>
<div class='span8'>
<div id='map_canvas'></div>
<div class='well'>
<div id='results_list'></div>
</div>
</div>
</div>
</div>
<script type="text/javascript" src="source/jquery.js"></script>
<script type="text/javascript" src="source/bootstrap.js"></script>
<script type="text/javascript" src="source/jquery.address.min.js"></script>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false&libraries=places"></script>
<script type="text/javascript" src="source/jquery.geocomplete.min.js"></script>
<script type="text/javascript" src="maps_lib.js"></script>
<script type='text/javascript'>
//<![CDATA[
$(window).resize(function () {
var h = $(window).height(),
offsetTop = 90; // Calculate the top offset
$('#map_canvas').css('height', (h - offsetTop));
}).resize();
$(function() {
MapsLib.initialize();
$("#search_address").geocomplete();
$(':checkbox').click(function(){
MapsLib.doSearch();
});
$(':radio').click(function(){
MapsLib.doSearch();
});
$('#search_radius').change(function(){
MapsLib.doSearch();
});
$('#select_type').change(function(){
MapsLib.doSearch();
});
$('#select_type1').change(function(){
MapsLib.doSearch();
});
$('#select_type2').change(function(){
MapsLib.doSearch();
});
$('#search').click(function(){
MapsLib.doSearch();
});
$('#find_me').click(function(){
MapsLib.findMe();
return false;
});
$('#reset').click(function(){
$.address.parameter('address','');
MapsLib.initialize();
return false;
});
$(":text").keydown(function(e){
var key = e.keyCode ? e.keyCode : e.which;
if(key == 13) {
$('#search').click();
return false;
}
});
});
//]]>
</script>
</body>
</html>
maps_lib.js
/*!
* Searchable Map Template with Google Fusion Tables
* http://derekeder.com/searchable_map_template/
*
* Copyright 2012, Derek Eder
* Licensed under the MIT license.
* https://github.com/derekeder/FusionTable-Map-Template/wiki/License
*
* Date: 12/10/2012
*
*/
var MapsLib = MapsLib || {};
var MapsLib = {
//Setup section - put your Fusion Table details here
//Using the v1 Fusion Tables API. See https://developers.google.com/fusiontables/docs/v1/migration_guide for more info
//the encrypted Table ID of your Fusion Table (found under File => About)
//NOTE: numeric IDs will be deprecated soon
fusionTableId: "1f8rnajgS2iSVwwBR1NwXwImUuFB7VCpOg1-IfCs",
//*New Fusion Tables Requirement* API key. found at https://code.google.com/apis/console/
//*Important* this key is for demonstration purposes. please register your own.
googleApiKey: "API KEY",
//name of the location column in your Fusion Table.
//NOTE: if your location column name has spaces in it, surround it with single quotes
//example: locationColumn: "'my location'",
locationColumn: "Address",
map_centroid: new google.maps.LatLng(17,15), //center that your map defaults to
locationScope: "", //geographical area appended to all address searches
recordName: "Store", //for showing number of results
recordNamePlural: "Stores",
searchRadius: 805, //in meters ~ 1/2 mile
defaultZoom: 2, //zoom level when map is loaded (bigger is more zoomed in)
addrMarkerImage: 'http://derekeder.com/images/icons/blue-pushpin.png',
currentPinpoint: null,
initialize: function() {
$( "#result_count" ).html("");
geocoder = new google.maps.Geocoder();
var myOptions = {
zoom: MapsLib.defaultZoom,
center: MapsLib.map_centroid,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map($("#map_canvas")[0],myOptions);
// maintains map centerpoint for responsive design
google.maps.event.addDomListener(map, 'idle', function() {
MapsLib.calculateCenter();
});
google.maps.event.addDomListener(window, 'resize', function() {
map.setCenter(MapsLib.map_centroid);
});
MapsLib.searchrecords = null;
//reset filters
$("#search_address").val(MapsLib.convertToPlainString($.address.parameter('address')));
var loadRadius = MapsLib.convertToPlainString($.address.parameter('radius'));
if (loadRadius != "") $("#search_radius").val(loadRadius);
else $("#search_radius").val(MapsLib.searchRadius);
$(":checkbox").attr("checked", "checked");
$("#result_count").hide();
//-----custom initializers-------
//run the default search
MapsLib.doSearch();
},
doSearch: function(location) {
MapsLib.clearSearch();
var address = $("#search_address").val();
MapsLib.searchRadius = $("#search_radius").val();
var whereClause = MapsLib.locationColumn + " not equal to ''";
//-----custom filters-------
if ( $("#select_type").val() != "") {
whereClause += " AND 'Category' = '" + $("#select_type").val() + "'";
}
if ( $("#select_type1").val() != "") {
whereClause += " AND 'sex' = '" + $("#select_type1").val() + "'";
}
if ( $("#select_type2").val() != "") {
whereClause += " AND 'Subindustry' = '" + $("#select_type2").val() + "'";
}
//-------end of custom filters--------
if (address != "") {
if (address.toLowerCase().indexOf(MapsLib.locationScope) == -1)
address = address + " " + MapsLib.locationScope;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
MapsLib.currentPinpoint = results[0].geometry.location;
$.address.parameter('address', encodeURIComponent(address));
$.address.parameter('radius', encodeURIComponent(MapsLib.searchRadius));
map.setCenter(MapsLib.currentPinpoint);
map.setZoom(14);
if (MapsLib.searchRadius == "400")
map.setZoom(16);
else if (MapsLib.searchRadius == "805")
map.setZoom(15);
else if (MapsLib.searchRadius == "1610")
map.setZoom(14);
else if (MapsLib.searchRadius == "3220")
map.setZoom(13);
else if (MapsLib.searchRadius == "8050")
map.setZoom(12);
else if (MapsLib.searchRadius == "16100")
map.setZoom(11);
else if (MapsLib.searchRadius == "40250")
map.setZoom(09);
else if (MapsLib.searchRadius == "80500")
map.setZoom(08);
else if (MapsLib.searchRadius == "161000")
map.setZoom(07);
else if (MapsLib.searchRadius == "402500")
map.setZoom(06);
else if (MapsLib.searchRadius == "805000")
map.setZoom(05);
else if (MapsLib.searchRadius == "1610000")
map.setZoom(04);
else
map.setZoom(14);
MapsLib.addrMarker = new google.maps.Marker({
position: MapsLib.currentPinpoint,
map: map,
icon: MapsLib.addrMarkerImage,
animation: google.maps.Animation.DROP,
title:address
});
whereClause += " AND ST_INTERSECTS(" + MapsLib.locationColumn + ", CIRCLE(LATLNG" + MapsLib.currentPinpoint.toString() + "," + MapsLib.searchRadius + "))";
MapsLib.drawSearchRadiusCircle(MapsLib.currentPinpoint);
MapsLib.submitSearch(whereClause, map, MapsLib.currentPinpoint);
}
else {
alert("We could not find your address: " + status);
}
});
}
else { //search without geocoding callback
MapsLib.submitSearch(whereClause, map);
}
},
submitSearch: function(whereClause, map, location) {
//get using all filters
//NOTE: styleId and templateId are recently added attributes to load custom marker styles and info windows
//you can find your Ids inside the link generated by the 'Publish' option in Fusion Tables
//for more details, see https://developers.google.com/fusiontables/docs/v1/using#WorkingStyles
MapsLib.searchrecords = new google.maps.FusionTablesLayer({
query: {
from: MapsLib.fusionTableId,
select: MapsLib.locationColumn,
where: whereClause
},
styleId: 2,
templateId: 2
});
MapsLib.searchrecords.setMap(map);
MapsLib.getCount(whereClause);
MapsLib.getList(whereClause);
},
clearSearch: function() {
if (MapsLib.searchrecords != null)
MapsLib.searchrecords.setMap(null);
if (MapsLib.addrMarker != null)
MapsLib.addrMarker.setMap(null);
if (MapsLib.searchRadiusCircle != null)
MapsLib.searchRadiusCircle.setMap(null);
},
findMe: function() {
// Try W3C Geolocation (Preferred)
var foundLocation;
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
foundLocation = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
MapsLib.addrFromLatLng(foundLocation);
}, null);
}
else {
alert("Sorry, we could not find your location.");
}
},
addrFromLatLng: function(latLngPoint) {
geocoder.geocode({'latLng': latLngPoint}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
$('#search_address').val(results[1].formatted_address);
$('.hint').focus();
MapsLib.doSearch();
}
} else {
alert("Geocoder failed due to: " + status);
}
});
},
drawSearchRadiusCircle: function(point) {
var circleOptions = {
strokeColor: "#4b58a6",
strokeOpacity: 0.3,
strokeWeight: 1,
fillColor: "#4b58a6",
fillOpacity: 0.05,
map: map,
center: point,
clickable: false,
zIndex: -1,
radius: parseInt(MapsLib.searchRadius)
};
MapsLib.searchRadiusCircle = new google.maps.Circle(circleOptions);
},
query: function(selectColumns, whereClause, callback) {
var queryStr = [];
queryStr.push("SELECT " + selectColumns);
queryStr.push(" FROM " + MapsLib.fusionTableId);
queryStr.push(" WHERE " + whereClause);
var sql = encodeURIComponent(queryStr.join(" "));
$.ajax({url: "https://www.googleapis.com/fusiontables/v1/query?sql="+sql+"&callback="+callback+"&key="+MapsLib.googleApiKey, dataType: "jsonp"});
},
handleError: function(json) {
if (json["error"] != undefined) {
var error = json["error"]["errors"]
console.log("Error in Fusion Table call!");
for (var row in error) {
console.log(" Domain: " + error[row]["domain"]);
console.log(" Reason: " + error[row]["reason"]);
console.log(" Message: " + error[row]["message"]);
}
}
},
getCount: function(whereClause) {
var selectColumns = "Count()";
MapsLib.query(selectColumns, whereClause,"MapsLib.displaySearchCount");
},
displaySearchCount: function(json) {
MapsLib.handleError(json);
var numRows = 0;
if (json["rows"] != null)
numRows = json["rows"][0];
var name = MapsLib.recordNamePlural;
if (numRows == 1)
name = MapsLib.recordName;
$( "#result_count" ).fadeOut(function() {
$( "#result_count" ).html(MapsLib.addCommas(numRows) + " " + name + " found");
});
$( "#result_count" ).fadeIn();
},
getList: function(whereClause) {
var selectColumns = "StoreName, Address, Contact, Website";
MapsLib.query(selectColumns, whereClause, "MapsLib.displayList");
},
displayList: function(json) {
MapsLib.handleError(json);
var data = json["rows"];
var template = "";
var results = $("#results_list");
results.hide().empty(); //hide the existing list and empty it out first
if (data == null) {
//clear results list
results.append("<li><span class='lead'>No results found</span></li>");
}
else {
for (var row in data) {
template = "\
<div class='row-fluid item-list'>\
<div class='span12'>\
<span class='lead'>" + data[row][0] + "\</span>\
<br />\
" + data[row][4] + "\
<br />\
" + data[row][5] + "\
<br />\
<a href='" + data[row][6] + "'>\
<span>" + data[row][7] + "\</span>\
</a>\
<br />\
<a onClick=''>\
<span style='color: red;'>See on Map</span>\
</a>\
</div>\
</div>"
results.append(template);
}
}
results.fadeIn();
},
addCommas: function(nStr) {
nStr += '';
x = nStr.split('.');
x1 = x[0];
x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
return x1 + x2;
},
// maintains map centerpoint for responsive design
calculateCenter: function() {
center = map.getCenter();
},
//converts a slug or query string in to readable text
convertToPlainString: function(text) {
if (text == undefined) return '';
return decodeURIComponent(text);
}
//-----custom functions-------
// NOTE: if you add custom functions, make sure to append each one with a comma, except for the last one.
// This also applies to the convertToPlainString function above
//-----end of custom functions-------
}
it's not as easy as it seems.
The location of a feature(e.g. marker) on a FusionTableLayer isn't available until you really click on it(this click can't be simulated).
You can't get the LatLng of the feature with the query, because you've stored addresses and not LatLng's inside the FusionTable.
Although the API knows the LatLng's of the addresses, there is no way to access them.
So the only thing you may do is:
Take the address of the row
use google.maps.Geocoder to geocode this address
open a custom InfoWindow(content populated by the properties of the row) at the LatLng returned by the geocoder.
I'd rather add a comment to Dr.Molle's answer, but thanks to Stack Overflow's point system, I have to add an answer even though I don't think this will be truly useful because I can't be very specific. I'm assuming that's because the goal is to get me to answer questions, not just talk about answers ;)
Dr.Molle was on the right track, but invoking the geocoder on every click is not only painfully slow, but every IP only gets so many geocoder requests per day. So:
Create a column that has a unique identifier. Add a listener to the marker so that when clicked, it will query your table for that ID. When the results come in, create an InfoWindow (sorry, no help here) with the returned data.
Here's a sample that does exactly what you're asking for:
https://developers.google.com/fusiontables/docs/samples/change_infowindow_content

How to add dynamic textbox in MVC3 razor on button click

I want to create the textbox dynamically on button click and remove it on another button click.
I have made it with jquery which is working fine.
$(document).ready(function () {
var counter = 2;
$("#addButton").click(function () {
if (counter > 10) {
alert("Only 10 textboxes allow");
return false;
}
var newTextBoxDiv = $(document.createElement('div'))
.attr("id", 'TextBoxDiv' + counter);
newTextBoxDiv.after().html('<input type="text" name="textbox' + counter +
'" id="textbox' + counter + '" value="" >');
newTextBoxDiv.appendTo("#TextBoxesGroup");
counter++;
});
$("#removeButton").click(function () {
if (counter == 1) {
alert("No more textbox to remove");
return false;
}
counter--;
$("#TextBoxDiv" + counter).remove();
});
$("#getButtonValue").click(function () {
var msg = '';
for (i = 1; i < counter; i++) {
msg += "\n Textbox #" + i + " : " + $('#textbox' + i).val();
}
alert(msg);
});
});
</script>
<div id='TextBoxesGroup'>
<div id="TextBoxDiv1">
<input type="textbox" id="textbox1" />
</div></div><input type='button' value='Add Button' id='addButton' /><input type='button' value='Remove Button' id='removeButton' /><input type='button' value='Get TextBox Value' id='getButtonValue' />
But i want this functionality with mvc3 razor.

Resources