Related
I want to check unchecked checkbox in based on data-id.
On drop down change i want to check unchecked checkbox in jstree.
I am Providing MY controller and Ajax Method bellow.
This is my jstree view.
Here is My Controller :
[HttpPost]
public ActionResult GetSingleUser(int id)
{
MachineShopDBEntities DB = new MachineShopDBEntities();
var SPresult = DB.GetSingleUser(id).FirstOrDefault();
return Json(SPresult);
}
Here is my Script:
$("#UserSelect").change(function () {
$.post("/MenuMaster/GetSingleUser?id=" + $(this).val(),
function (data, status) {
var databaseString = data.MenuEnable;
for (i = 0; i <= databaseString.length; i++) {
if (databaseString.substring(i, i + 1) == "1") {
$('.jstree-container-ul li[data-id=' + (i + 1) + ']').find('.jstree-anchor').addClass('jstree-clicked');
}
}
});
});
Here I created demo for you.
Make changes according to code snippet below
jQuery(function ($) {
$('.menux').jstree({
"core": { "check_callback": false },
"checkbox": { "keep_selected_style": false, "three_state": false, "tie_selection": false, "whole_node": false, },
"plugins": ["checkbox"]
}).bind("ready.jstree", function (event, data) {
$(this).jstree("open_all");
}).on("check_node.jstree uncheck_node.jstree", function (e, data) {
var currentNode = data.node;
var parent_node = $(".menux").jstree().get_node(currentNode).parents;
if (data.node.state.checked)
$(".menux").jstree().check_node(parent_node[0]);
else
$(".menux").jstree().uncheck_node(parent_node[0]);
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="http://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/2.3.1/css/bootstrap.css" rel="stylesheet" />
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.3.5/jstree.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.2.1/themes/default/style.min.css" />
<div class="menux">
<ul>
<li>
Root node 1
<ul>
<li data-id="1"><a href="#" >Child node 1</a> </li>
<li data-id="2"><a href="#" >Child node 2</a></li>
<li data-id="3"><a href="#" >Child node 3</a></li>
<li data-id="4"><a href="#" >Child node 4</a></li>
<li data-id="24"><a href="#" >Child node 24</a></li>
</ul>
</li>
</ul>
</div>
Edit:
First make sure you have disable three-state while initializing jsTree as mentioned in above code snippet.
Try to implement above $('.menux li').each function in your code.
The below code is only sample to where you have to put this $('.menux li').each.
$("#UserSelect").change(function () {
$.post("/MenuMaster/GetSingleUser?id=" + $(this).val(),
function (data, status) {
var databaseString = data.MenuEnable;
$('.menux li').each(function (index, value) {
var node = $(".menux").jstree().get_node(this.id);
var id = node.data.id;
for (i = 0; i <= databaseString.length; i++) {
if (databaseString.substring(i, i + 1) == "1") {
if ((i + 1) == id) {
$(".menux").jstree().check_node(this.id);
}
}
}
});
});
});
If you got any error like jsTree is not a function then you can replace above $('.menux li').each function with this
$('.menux li').each(function (index, value) {
for (i = 0; i <= databaseString.length; i++) {
if (databaseString.substring(i, i + 1) == "1") {
var dataid = $('#' + this.id).data('id');
if ((i + 1) == dataid) {
$('#' + this.id).find('.jstree-anchor').addClass('jstree-clicked');
}
}
}
});
I want to sent a line chart in the body of the E-mail using ASP.Net and C#. I have written a code to show the chart in a div tag. I want to sent the line chart in mail. How to do this?
My Code: jQuery
var chartData;
google.load("visualization", "1", { packages: ["corechart"] });
function Chart() {
$.ajax({
url: "HHT_Tracking.aspx/GetData",
data: "",
dataType: "json",
type: "POST",
contentType: "application/json; chartset=utf-8",
success: function (data) {
chartData = data.d;
},
error: function () {
alert("Error loading data! Please try again.");
}
}).done(function () {
//google.setOnLoadCallback(drawChart);
drawChart();
});
};
function drawChart() {
var data = google.visualization.arrayToDataTable(chartData);
var options = {
title: "Server Monitoring Date Wise",
pointSize: 5,
vAxis: { slantedText: true, slantedTextAngle: 90, title: 'MINUTES' }
};
var lineChart = new google.visualization.LineChart(document.getElementById('chartDiv'));
lineChart.draw(data, options);
}
Source Code:
<tr>
<td>
<div id="chartDiv" style="width: 100%; height: 700px"></div>
</td>
</tr>
Assuming that you are using System.Web.UI.DataVisualization for your charting, the chart class has a method SaveImage that you can use for saving that chart as a graphic (e.g. png) into a memory stream. Use that stream to spit out data-uri which you can then use in your HTML formatted email body.
For example:
Charting.Chart myChart = new Charting.Chart();
System.IO.MemoryStream imgStream = new System.IO.MemoryStream();
myChart.SaveImage(imgStream, Charting.ChartImageFormat.Png);
return "<img class='chartImage' src='data:image/png;base64, " + System.Convert.ToBase64String(imgStream.ToArray()) + "' />";
This code will return an img tag with data-uri as its src which you can then use in your HTML body of email.
Flow code:
The head tag:
<head runat="server">
<title></title>
<script type="text/javascript"
src="https://www.google.com/jsapi?autoload={
'modules':[{
'name':'visualization',
'version':'1',
'packages':['corechart']
}]
}"></script>
<script type="text/javascript">
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Year', 'Sales', 'Expenses'],
['2004', 1000, 400],
['2005', 1170, 460],
['2006', 660, 1120],
['2007', 1030, 540]
]);
var options = {
title: 'Company Performance',
curveType: 'function',
legend: { position: 'bottom' }
};
var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));
var txtBase64 = document.getElementById('txtBase64Image');
google.visualization.events.addListener(chart, 'ready', function () {
txtBase64.value = chart.getImageURI();
});
chart.draw(data, options);
}
</script>
</head>
Body tag:
<body>
<form id="form1" runat="server">
<div id="curve_chart" style="width: 900px; height: 500px"></div>
<%--If you want, you can textbox visible false.--%>
<asp:TextBox ID="txtBase64Image" runat="server" Width="600" TextMode="MultiLine"></asp:TextBox><br/>
<asp:Button ID="Button1" runat="server" Text="Send Mail" OnClick="Button1_Click" />
</form>
</body>
After c# code:
public Image Base64ToImage(string base64String)
{
var imageBytes = Convert.FromBase64String(base64String);
using (var ms = new MemoryStream(imageBytes, 0, imageBytes.Length))
{
var image = Image.FromStream(ms, true);
return image;
}
}
Button click: Send to mail chart. Look EmailSender https://github.com/serkomut/Serkomut.MailSender
protected void Button1_Click(object sender, EventArgs e)
{
var split = txtBase64Image.Text.Split(',')[1];
var image = Base64ToImage(split);
var stream = new MemoryStream();
image.Save(stream, ImageFormat.Jpeg);
stream.Position = 0;
var result = new EmailSender()
.FromHost("smtp.gmail.com")
.Credential("sendermail#gmail.com", "mailPassword")
.FromTo(new Message
{
From = "sendermail#gmail.com",
To = "tomail#gmail.com"
})
.Subject("Subject")
.Body("Content text...")
.Attachment(new Attachment(stream, "chart_image.jpg", "image/jpg"))
.Send();
}
I have a form on which I am adding rows dynamically using Jquery.
Please take a look: DEMO
Now I want to save the data of all rows that has been added in my database using Jquery Ajax call on click event of SAVE button. The point where I am stuck is .. I am not sure how should I extract data of all rows and send it to the webmethod. I mean had it been c# I could have used a DataTable to store data of all rows before sending it to DataBase. I think I should create a string seperated by commas and pipe with data of each row and send it to webmethod. I am not sure if its the right approach and also how this is to be done (ie. creating such a string).
HTML
<table id="field">
<tbody>
<tr id="row1" class="row">
<td> <span class='num'>1</span></td>
<td><input type="text" /></td>
<td><select class="myDropDownLisTId"> <input type="text" class="datepicker" /></select></td><td>
<input type="submit"></input>
</td>
</tr>
</tbody>
</table>
<button type="button" id="addField">Add Field</button>
<button type="button" id="deleteField">Delete Field</button>
<button type="button" id="btnsave">SAVE</button>
2 suggestions:
To keep it as close as what you already have, you could just enclose your table in a form tag, and then you could just submit the form (use something like the jQuery Form plugin to submit it via Ajax). The trickiest part will be to bind that data to action parameters. You may be able to receive it in the form of an array, or you could default to looping through properties of the Request.Form variable. Make sure you generate proper names for those fields.
I think the cleanest way to do it would be to have a JavaScript object holding your values, and having the table generated from that object, with 2-way bindings. Something like KnockoutJS would suit your needs. That way the user enters the data in the table and you'll have it ready to be Json-serialized and sent to the server. Here's a quick example I made.
I wouldn't recommend that approach, but if you wanted to create your own string, you could do something along those lines:
$("#btnsave").click(function () {
var result = "";
$("#field tr").each(function (iRow, row) {
$("td input", row).each(function (iField, field) {
result += $(field).val() + ",";
});
result = result + "|";
});
alert(result);
});
You will have problems if the users types in a comma. That why we use well known serialization formats.
use ajax call on save button event...
like this
$(document).ready(function () {
$('#reqinfo').click(function () {
// debugger;
var emailto = document.getElementById("emailid").value;
if (emailto != "") {
$.ajax({
type: "GET",
url: "/EmailService1.svc/EmailService1/emaildata?Email=" + emailto,
// data: dat,
Accept: 'application/json',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
// debugger;
},
error: function (result) {
// debugger;
}
});
}
else {
//your validation message goes here
return false;
}
});
});
and add you all data in quesry string and transfer it to webservice..
url: "/EmailService1.svc/EmailService1/emaildata?Email=" + emailto + "data1=" + data1,
<script type="text/javascript">
var _autoComplCounter = 0;
function initialize3(_id) {
var input_TO = document.getElementById(_id);
var options2 = { componentRestrictions: { country: 'ID' } };
new google.maps.places.Autocomplete(input_TO, options2);
}
google.maps.event.addDomListener(window, 'load', initialize3);
function incrementValue() {
var value = parseInt(document.getElementById('number').value, 10);
value = isNaN(value) ? 0 : value;
value++;
document.getElementById('number').value = value;
}
function GetDynamicTextBox(value) {
var _id = "AutoCompl" + _autoComplCounter;
_autoComplCounter++;
return '<input name = "DynamicTextBox" type="text" id="' + _id + '" value = "' + value + '" onkeypress = "calcRoute();" />' +
'<input type="button" class="superbutton orange" value="Remove" onclick = "RemoveTextBox(this)" />'
}
function AddTextBox() {
var value = parseInt(document.getElementById('number').value, 10);
value = isNaN(value) ? 0 : value;
value++;
if (document.getElementById('number').value < 3) {
document.getElementById('number').value = value;
var div = document.createElement('DIV');
var _id = "AutoCompl" + _autoComplCounter;
_autoComplCounter++;
var ht = '<input name = "DynamicTextBox" type="text" id="' + _id + '" value = "" onkeypress = "calcRoute();" class="clsgetids" for-action="' + _id + '" />' +
'<input type="button" class="superbutton orange" value="#Resources.SearchOfferRides.btnRemove" onclick = "RemoveTextBox(this); calcRoute();" />';
div.innerHTML = ht;
document.getElementById("TextBoxContainer").appendChild(div);
setTimeout(function () {
var input_TO = document.getElementById(_id);
var options2 = { componentRestrictions: { country: 'ID' } };
new google.maps.places.Autocomplete(input_TO, options2);
}, 100);
document.getElementById("TextBoxContainer").appendChild(div);
}
else {
alert('Enter only 3 stop point. !!');
}
}
function RemoveTextBox(div) {
//calcStopPointRoute();
var value = parseInt(document.getElementById('number').value, 10);
value = isNaN(value) ? 0 : value;
value--;
document.getElementById('number').value = value;
document.getElementById("TextBoxContainer").removeChild(div.parentNode);
}
function RecreateDynamicTextboxes() {
var values = eval('<%=Values%>');
if (values != null) {
var html = "";
for (var i = 0; i < values.length; i++) {
html += "<div>" + GetDynamicTextBox(values[i]) + "</div>";
}
document.getElementById("TextBoxContainer").innerHTML = html;
}
}
// window.onload = RecreateDynamicTextboxes;
</script>
And get the value from textbox:
#region stop point
string[] textboxValues = Request.Form.GetValues("DynamicTextBox");
if (textboxValues != null)
{
for (Int32 i = 0; i < textboxValues.Length; i++)
{
if (textboxValues.Length == 1)
{
model.OptionalRoot = textboxValues[0].ToString();
}
else if (textboxValues.Length == 2)
{
model.OptionalRoot = textboxValues[0].ToString();
model.OptionalRoot2 = textboxValues[1].ToString();
}
else if (textboxValues.Length == 3)
{
model.OptionalRoot = textboxValues[0].ToString();
model.OptionalRoot2 = textboxValues[1].ToString();
model.OptionalRoot3 = textboxValues[2].ToString();
}
else
{
model.OptionalRoot = "";
model.OptionalRoot2 = "";
model.OptionalRoot3 = "";
}
}
}
#endregion
Short answer:
DataTable equivalent in javascript is Array of custom object (not exact equivalent but we can say that)
or
you roll your own DataTable js class which will have all the functions and properties supported by DataTable class in .NET
Long answer:
on client side(aspx)
you define a class MyClass and store all your values in array of objects of that class
and then pass that array after stingyfying it to web method
JSON.stringify(myArray);
on the server side(codebehind)
you just define the web method to accept a list of objects List<MyClass>
PS: When calling web method, Asp.net automatically converts json array into List<Object> or Object[]
Loooong answer (WHOLE Solution)
Page aspx:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<link href="App_Themes/SeaBlue/jquery-ui-1.9.2.custom.css" rel="stylesheet" type="text/css" />
<script src="Scripts/jquery-1.8.3.js" type="text/javascript"></script>
<script src="Scripts/jquery-ui-1.9.2.custom.min.js" type="text/javascript"></script>
<script src="Scripts/json2.js" type="text/javascript"></script>
<script type="text/javascript">
function MyClass(title,option,date) {
this.Title = title;
this.Option = option;
this.Date = date;
}
function GetJsonData() {
var myCollection = new Array();
$(".row").each(function () {
var curRow = $(this);
var title = curRow.find(".title").val();
var option = curRow.find(".myDropDownLisTId").val();
var date = curRow.find(".datepicker").val();
var myObj = new MyClass(title, option, date);
myCollection.push(myObj);
});
return JSON.stringify(myCollection);
}
function SubmitData() {
var data = GetJsonData();
$.ajax({
url: "testForm.aspx/PostData",
data: "{ 'myCollection': " + data + " }",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function () {
alert("Success");
}
});
}
$(document).ready(function () {
filldd();
CreateDP();
var rowstring = "<tr class='row'><td class='number'></td><td><input type='text' class='title'/></td><td><select class='myDropDownLisTId'/><input type='text' class='datepicker'/></td><td><input type='submit'></input></td></tr>";
$("#addField").click(function (event) {
$("#field tbody").append(rowstring);
filldd();
CreateDP();
if ($("td").hasClass("number")) {
var i = parseInt($(".num:last").text()) + 1;
$('.row').last().attr("id", "row" + i);
$($("<span class='num'> " + i + " </span>")).appendTo($(".number")).closest("td").removeClass('number');
}
event.preventDefault();
});
$("#deleteField").click(function (event) {
var lengthRow = $("#field tbody tr").length;
if (lengthRow > 1)
$("#field tbody tr:last").remove();
event.preventDefault();
});
$("#btnsave").click(function () {
SubmitData();
});
});
function filldd() {
var data = [
{ id: '0', name: 'test 0' },
{ id: '1', name: 'test 1' },
{ id: '2', name: 'test 2' },
{ id: '3', name: 'test 3' },
{ id: '4', name: 'test 4' },
];
for (i = 0; i < data.length; i++) {
$(".myDropDownLisTId").last().append(
$('<option />', {
'value': data[i].id,
'name': data[i].name,
'text': data[i].name
})
);
}
}
function CreateDP() {
$(".datepicker").last().datepicker();
}
$(document).on('click', 'input[type="submit"]', function () {
alert($(this).closest('tr')[0].sectionRowIndex);
alert($(this).closest('tr').find('.myDropDownLisTId').val());
});
</script>
</head>
<body>
<form id="frmMain" runat="server">
<table id="field">
<tbody>
<tr id="row1" class="row">
<td>
<span class='num'>1</span>
</td>
<td>
<input type="text" class="title"/>
</td>
<td>
<select class="myDropDownLisTId">
</select>
<input type="text" class="datepicker" />
</td>
<td>
<input type="submit"></input>
</td>
</tr>
</tbody>
</table>
<button type="button" id="addField">
Add Field</button>
<button type="button" id="deleteField">
Delete Field</button>
<button type="button" id="btnsave">
SAVE</button>
</form>
</body>
</html>
CodeBehind:
public partial class testForm : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static void PostData(List<MyClass> myCollection)
{
Console.WriteLine(myCollection.Count);
}
}
public class MyClass
{
string title;
public string Title
{
get { return title; }
set { title = value; }
}
string option;
public string Option
{
get { return option; }
set { option = value; }
}
string date;
public string Date
{
get { return date; }
set { date = value; }
}
}
Hope this helps
References:
Json2.js file
stringify method
define a class in js
I am trying to post the value of the textbox and have that same value posted on the page in the "You said..." section.
My TypeScript/JavaScript is:
declare var document;
declare var xmlhttp;
window.onload = () => {
start();
};
function sayHello(msg: any) {
// Post to server.
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4) {
if (xmlhttp.status == 200) {
// All right - data is stored in xhr.responseText
alert("done" + " " + xmlhttp.responseText);
}
else {
// Server responded with a status code.
alert("error");
}
}
}
xmlhttp.open("POST", "Default.cshtml");
xmlhttp.send("someValue=" + msg);
return msg;
}
function start() {
// Add event Listeners for user interaction
var element = document.getElementById("link");
element.addEventListener("click", function () {
var tb = (<HTMLInputElement>document.getElementById("tbox"));
var element = document.getElementById("response")
.innerText = sayHello(tb.value);
}, false);
// Setup XMLHttpRequests (AJAX)
if (XMLHttpRequest) {
// Somewhat cross-browser
xmlhttp = new XMLHttpRequest();
}
else {
// Legacy IE
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
}
And the HTML is (this page is Default.cshtml):
#{
Layout = "~/_SiteLayout.cshtml";
Page.Title = "Home Page";
var msg = Request["someValue"];
}
<h1>TypeScript HTML App</h1>
<div id="content">
Say Hello:
<br />
<input type="text" value="dfgdfgdfg" id="tbox" />
<br />
<p id="response">awaiting a response.</p>
<br />
<p>You said:<br />
#msg</p>
</div>
And I've included all references properly:
<script src="~/App.js"></script>
The response code I get back is 200.
Am I doing something wrong here? I've followed many tutorials, docs and so forth, and I just don't see what I'm doing wrong. It looks practically identical.
When you are processing an XMLHttpRequest as a POST, you need to add a couple of extra headers - add them before you call send, like this:
var params = "someValue=" + encodeURIComponent(msg);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", params.length.toString());
xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.send(params);
UPDATE - My Full Example
Default.cshtml
#{
Layout = "~/Views/Shared/_Layout.cshtml";
Page.Title = "Home Page";
var msg = Request["someValue"];
}
#if (msg != null) {
Layout = null;
<text>You said #msg</text>
} else {
<h1>TypeScript HTML App</h1>
<div id="content">
Say Hello:
<br />
<input type="text" value="dfgdfgdfg" id="tbox" />
<br />
<p id="response">awaiting a response.</p>
</div>
}
App.ts
declare var document;
declare var xmlhttp: XMLHttpRequest;
window.onload = () => {
start();
};
function sayHello(msg: any) {
// Post to server.
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4) {
if (xmlhttp.status == 200) {
// All right - data is stored in xhr.responseText
//alert("done" + " " + xmlhttp.responseText);
document.getElementById("response").innerText = xmlhttp.responseText;
}
else {
// Server responded with a status code.
alert("error");
}
}
}
var params = "someValue=" + encodeURIComponent(msg);
xmlhttp.open("POST", "");
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", params.length.toString());
xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.send(params);
return msg;
}
function start() {
// Add event Listeners for user interaction
var element = document.getElementById("link");
element.addEventListener("click", function () {
var tb = <HTMLInputElement>document.getElementById("tbox");
sayHello(tb.value);
}, false);
// Setup XMLHttpRequests (AJAX)
if (XMLHttpRequest) {
// Somewhat cross-browser
xmlhttp = new XMLHttpRequest();
}
else {
// Legacy IE
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
}
Can you try replacing:
xmlhttp.send("someValue" + msg);
with
xmlhttp.send("someValue=" + msg);
I hope this helps. As stated I am a bit confused by your flow, but it might still help you.
PageA.cshtml (the page that houses the javascript)
<h1>TypeScript HTML App</h1>
<div id="content">
Say Hello:
<br />
<input type="text" value="dfgdfgdfg" id="tbox" />
<br />
<p id="response">awaiting a response.</p>
</div>
<script src="app.js" type="text/javascript"></script>
PageB.cshtml (the page we request via ajax call)
#{
var msg = Request["someValue"];
}
<p>You said:<br />
#msg</p>
App.js (javascript file running on page A and requesting page B)
declare var document;
declare var xmlhttp;
window.onload = () => {
start();
};
function sayHello(msg: any, callback) {
// Post to server.
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
if (xmlhttp.status == 200) {
// alert(xmlhttp.responseText);
} else {
// Server responded with a status code.
alert("error");
}
}
};
xmlhttp.open("POST", "PageB.cshtml");
xmlhttp.send("someValue=" + msg);
}
function start() {
// Add event Listeners for user interaction
var element = document.getElementById("link");
element.addEventListener("click", function () {
var tb = (<HTMLInputElement>document.getElementById("tbox"));
sayHello(tb.value);
document.getElementById("response")
.innerHTML = tb.value;
}, false);
// Setup XMLHttpRequests (AJAX)
if (XMLHttpRequest) {
// Somewhat cross-browser
xmlhttp = new XMLHttpRequest();
}
else {
// Legacy IE
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
}
What I am doing is making a request from PageA to PageB. Then reading the result I manipulate the dom of PageA to contain the markup received from PageB. This markup contains the message passed along with the request.
Is this the flow you are trying to achieve?
I wrote a google map lookup page. Everthing worked fine until I referenced the page to use a master page. I removed the form tag from the master page as the search button on the map page is a submit button. Everything else on my page appears but the google map div appears with map navigation controls and logo but no map visuals appear.
I retested with the previous, non master page version and the map appears correctly. Any thoughts on what I'm missing?
Please view below Code and let me know its useful ...
MasterPage Code ( GMap.master page)
< body onload="initialize()" onunload="GUnload()" >
< form id="form1" runat="server" >
< div >
< asp:contentplaceholder id="ContentPlaceHolder1" runat="server" >
< /asp:contentplaceholder >
< /div >
< /form >
< /body >
GMatTest.aspx Page which is used GMap.Master page
< %# Page Language="C#" MasterPageFile="~/MasterPages/GMap.master" AutoEventWireup="true"
CodeFile="GMapTest.aspx.cs" Inherits="GMapTest" Title="Google Map Page" % >
< asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server" >
< script src="http://maps.google.com/maps?file=api&v=2&key=< % = AppConfig.GoogleMapApiKey % >"
type="text/javascript" >< /script >
< script type="text/javascript" >
var map = null;
var geocoder = null;
var latsgn = 1;
var lgsgn = 1;
var zm = 0;
var marker = null;
function initialize()
{
if (GBrowserIsCompatible())
{
var latitude= "";
var longitude= "";
map = new GMap2(document.getElementById("map_canvas"));
var center = new GLatLng(0,0);
map.setCenter(center, 17);
map.addControl(new GLargeMapControl());
map.addControl(new GScaleControl());
map.enableScrollWheelZoom();
map.addControl(new GMapTypeControl());
map.enableDoubleClickZoom();
marker = new GMarker(center,{draggable: true});
geocoder = new GClientGeocoder();
GEvent.addListener(marker, "dragend", function() {
var point = marker.getLatLng();
marker.openInfoWindowHtml("Latitude: " + point.y + "< /br > Longitude: " + point.x );
});
GEvent.addListener(marker, "click", function() {
var point = marker.getLatLng();
});
map.addOverlay(marker);
GEvent.trigger(marker, "click");
if (latitude > 0 && longitude > 0)
{
}
else
{
showAddress();
}
}
}
Below porsion is continue so please copy it also
function showAddress()
{
var isAddressFound=false;
var companyAddress = '';
var address='satyam mall, vastrapur, ahmedabad, gujrat, india';
if (geocoder)
{
geocoder.getLatLng(address,function(point) {
if (!point) {
alert(address + " not found");
} else {
isAddressFound =true;
map.setCenter(point,17);
zm = 1;
marker.setPoint(point);
GEvent.trigger(marker, "click");
}
}
);
//If address not found then redirect to company address
if(!isAddressFound)
{
geocoder.getLatLng(companyAddress,
function(point) {
if (!point) {
} else {
isAddressFound =true;
map.setCenter(point,17);
zm = 1;
marker.setPoint(point);
GEvent.trigger(marker, "click");
}
}
);
}
}
}
< /script >
< div id="map_canvas" style="width: 100%; height: 425px" >
< /div >
< /asp:Content >
this is the code i used.it works fine here but whenever i add master page it does not perform any use functionality
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Find latitude and longitude with Google Maps</title>
<script src="http://maps.google.com/maps?file=api&v=2&key=ABQIAAAAPkZq56tNYNmeuZjNQQ2p3hT0NZP-HbfQNNfWb9Z5SLbjZKYKwBTrGBqtttFmF2d-kWv2B2nqW_NyEQ"
type="text/javascript"></script>
<script type="text/javascript">
function load() {
if (GBrowserIsCompatible()) {
var map = new GMap2(document.getElementById("map"));
map.addControl(new GSmallMapControl());
map.addControl(new GMapTypeControl());
var center = new GLatLng(48.89364, 2.33739);
map.setCenter(center, 15);
geocoder = new GClientGeocoder();
var marker = new GMarker(center, {draggable: true});
map.addOverlay(marker);
document.getElementById("lat").innerHTML = center.lat().toFixed(6);
document.getElementById("lng").innerHTML = center.lng().toFixed(6);
GEvent.addListener(marker, "dragend", function() {
var point = marker.getPoint();
map.panTo(point);
document.getElementById("lat").innerHTML = point.lat().toFixed(6);
document.getElementById("lng").innerHTML = point.lng().toFixed(6);
});
GEvent.addListener(map, "moveend", function() {
map.clearOverlays();
var center = map.getCenter();
var marker = new GMarker(center, {draggable: true});
map.addOverlay(marker);
document.getElementById("lat").innerHTML = center.lat().toFixed(6);
document.getElementById("lng").innerHTML = center.lng().toFixed(6);
GEvent.addListener(marker, "dragend", function() {
var point =marker.getPoint();
map.panTo(point);
document.getElementById("lat").innerHTML = point.lat().toFixed(6);
document.getElementById("lng").innerHTML = point.lng().toFixed(6);
});
});
}
}
function showAddress(address) {
var map = new GMap2(document.getElementById("map"));
map.addControl(new GSmallMapControl());
map.addControl(new GMapTypeControl());
if (geocoder) {
geocoder.getLatLng(
address,
function(point) {
if (!point) {
alert(address + " not found");
} else {
document.getElementById("lat").innerHTML = point.lat().toFixed(6);
document.getElementById("lng").innerHTML = point.lng().toFixed(6);
map.clearOverlays()
map.setCenter(point, 14);
var marker = new GMarker(point, {draggable: true});
map.addOverlay(marker);
GEvent.addListener(marker, "dragend", function() {
var pt = marker.getPoint();
map.panTo(pt);
document.getElementById("lat").innerHTML = pt.lat().toFixed(6);
document.getElementById("lng").innerHTML = pt.lng().toFixed(6);
});
GEvent.addListener(map, "moveend", function() {
map.clearOverlays();
var center = map.getCenter();
var marker = new GMarker(center, {draggable: true});
map.addOverlay(marker);
document.getElementById("lat").innerHTML = center.lat().toFixed(6);
document.getElementById("lng").innerHTML = center.lng().toFixed(6);
GEvent.addListener(marker, "dragend", function() {
var pt = marker.getPoint();
map.panTo(pt);
document.getElementById("lat").innerHTML = pt.lat().toFixed(6);
document.getElementById("lng").innerHTML = pt.lng().toFixed(6);
});
});
}
}
);
}
}
</script>
</head>
<body onload="load()" onunload="GUnload()" >
<p>This page uses the Google Maps API to find out accurate geographical coordinates (latitude and longitude) for any place on Earth. <br/>It provides two ways to search, either by moving around the map and zooming in, or by typing an address if the place is unknown.<br/>
<i>
<p> The default location and address are those of Mondeca office in Paris.<br />
<p><b> Find coordinates by moving around the map</b></p> <p>1. Drag and drop the map to broad location. <br/>
2. Zoom in for greater accuracy. <br/>
3. Drag and drop the marker to pinpoint the place. The coordinates are refreshed at the end of each move. </p>
<form action="#" onsubmit="showAddress(this.address.value); return false">
<p>
<input type="text" size="60" name="address" value="3 cité Nollez Paris France" />
<input type="submit" value="Search!" />
</p>
</form>
<p align="left">
<table bgcolor="#FFFFCC" width="300">
<tr>
<td width="100"><b>Latitude</b></td>
<td id="lat"></td>
</tr>
<tr>
<td width="100"><b>Longitude</b></td>
<td id="lng"></td>
</tr>
</table>
</p>
<p>
<div align="center" id="map" style="width: 600px; height: 400px"><br/></div>
</p>
</body>
</html>
It was same problem as mentioned above. when I used master page no google map was drawn. I found solution later.
You need to call the Javascript function in .aspx page where you want to show google map (like initialize();) may be different in your case.
code in my case:
<script type="text/javascript"">
window.onload = function () {
DrawGoogleMap();
}
function DrawGoogleMap() {
if (GBrowserIsCompatible()) {
map = new GMap2(document.getElementById("GoogleMap_Div"));
geocoder = new GClientGeocoder();
GService.GetGoogleObject(fGetGoogleObject);
}
}
</script>
Load up FireFox and FireBug, start looking for javascript errors.
One item that I have found, you have to call setCenter on the map for it to display.
Also, if you are adding markers (or layers), you have to add the marker after you call setCenter.
Ended up having to force the div to visible
See this thread on google maps support forums:
http://groups.google.com/group/Google-Maps-Troubleshooting/browse_thread/thread/0d27b66eef5f5d9e/1259a2991412f796?lnk=raot
Thanks!!
One thing that can change when you add a master page is your elements ids.
If the div you are displaying the map in has runat="server" on it, you could have a problem.
You would add that tag so you could manipulate the div from code-behind.
So, if my div looks like this:
<div id="gmap" runat="server"></div>
If so, when you are initializing your map, you need to get the ClientId of the div. That would look like this:
var mapDiv = '<%= gmap.ClientID %>';
var map = new GMap2(mapDiv);
the code i used is
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<META NAME="AUTHOR" CONTENT="Rakshith Krishnappa">
<META NAME="DESCRIPTION" CONTENT="KML Tool - Get Latitude and Longitude for KML Polyline">
<META NAME="KEYWORDS" CONTENT="Google, maps, mashup, tools, kml, polyline">
<META NAME="ROBOTS" CONTENT="ALL">
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" />
<title>Mapmash | Geocoder Tool | Geocode - Reverse Geocode - IP Geocode</title>
<%--<style type="text/css">
<!--
html {
height: 100%; width:100%;overflow:hidden;
}
body {
background-color: white;
font-family: Arial, sans-serif;
font-size:10pt
}
h1 {
font-size: 18pt;
}
#map {
height: 100%;
}
#hand_b {
width:31px;
height:31px;
background-image: url(http://google.com/mapfiles/ms/t/Bsu.png);
}
#hand_b.selected {
background-image: url(http://google.com/mapfiles/ms/t/Bsd.png);
}
#placemark_b {
width:31px;
height:31px;
background-image: url(http://google.com/mapfiles/ms/t/Bmu.png);
}
#placemark_b.selected {
background-image: url(http://google.com/mapfiles/ms/t/Bmd.png);
}
#line_b {
width:31px;
height:31px;
background-image: url(http://google.com/mapfiles/ms/t/Blu.png);
}
#line_b.selected {
background-image: url(http://google.com/mapfiles/ms/t/Bld.png);
}
#shape_b {
width:31px;
height:31px;
background-image: url(http://google.com/mapfiles/ms/t/Bpu.png);
}
#shape_b.selected {
background-image: url(http://google.com/mapfiles/ms/t/Bpd.png);
}
-->
</style>
<style type="text/css">
v\:* {
behavior:url(#default#VML);
}
</style>--%>
<script type="text/javascript" src="http://www.google.com/jsapi?key=ABQIAAAAPkZq56tNYNmeuZjNQQ2p3hT0NZP-HbfQNNfWb9Z5SLbjZKYKwBTrGBqtttFmF2d-kWv2B2nqW_NyEQ"></script>
<script type="text/javascript">
google.load("maps", "2");
</script>
<script src="dragzoom.js" type="text/javascript"></script>
<script src="http://adserver.lat49.com/lat49/v0.10/lat49.js" type="text/javascript"></script>
<!-- Start of Google Analytics Code -->
<script src="http://www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-2417064-1";
urchinTracker();
</script>
<!-- End of Google Analytics Code -->
<script type="text/javascript">
//<![CDATA[
//rakf1 modified code taken from these 2 sources: - http://www.gorissen.info/Pierre/maps/googleMapLocationv4.php and - Distance Measurement Tool - Google Mapplets
// argItems code taken from
// http://www.evolt.org/article/Javascript_to_Parse_URLs_in_the_Browser/17/14435/?format=print
var map;
var coordinates = '';
var geocoder = new GClientGeocoder();
var added = 0;
var marker;
function write_point() {
var position = marker.getPoint();
var lat = position.y.toFixed(6);
var lng = position.x.toFixed(6);
coordinates = lng + "," + lat + "\n";
document.getElementById("attribute").value = 'lat="'+lat+'" lng="'+lng+'"';
document.getElementById("latlng").value = '<lat>'+lat+'</lat>\n<lng>'+lng+'</lng>';
document.getElementById("kml").value = lng+','+lat;
document.getElementById("coord").value = marker.getPoint().toUrlValue();
}
function get_address1() {
GEvent.addListener(marker, "click", function(){
var position = marker.getPoint();
var lat = position.y.toFixed(6);
var lng = position.x.toFixed(6);
var html = 'FreeReverseGeo.com (~address):<br><iframe id="RSIFrame" name="RSIFrame" style="overflow:hidden; width:200px; height:55px; border: 1px" src="http://www.freereversegeo.com/gmap-api.php?lat_1=' + lat + '&lng_1=' + lng + '"></iframe><br>('+lat+','+lng+')';
marker.openInfoWindowHtml(html);
});
}
function get_address() {
GEvent.addListener(marker, "click", function(){
var position = marker.getPoint();
geocoder.getLocations(position, function(addresses) {
if(addresses.Status.code != 200) {
marker.openInfoWindowHtml("<b>Google Reverse Geocode:</b><br>Reverse geocoder failed to find an address for " + position.toUrlValue());
}
else {
address = addresses.Placemark[0];
var html = address.address;
marker.openInfoWindowHtml("<b>Google Reverse Geocode:</b><br>"+html);
}
});
});
}
function my_location() {
if (google.loader.ClientLocation) {
var cl = google.loader.ClientLocation;
var html = 'Google ClientLocation: <br><font size="+1">' + cl.address.city + ', ' + cl.address.region+ '<br> ' + cl.address.country+'</font><br>('+cl.latitude+','+cl.longitude+')';
var point = new GLatLng(cl.latitude, cl.longitude);
if(!marker) {
map.setZoom(12);
marker = new GMarker(point,{title: "Click to get address", draggable: true});
map.addOverlay(marker);
added = 1;
}
map.setCenter(point);
marker.setPoint(point);
marker.openInfoWindowHtml(html);
}
}
function draw_point() {
GEvent.addListener(map, 'click', function(overlay, point) {
if (point && !added) {
marker = new GMarker(point, {icon:G_DEFAULT_ICON, draggable: true, title: "Click to get address"});
map.addOverlay(marker);
added = 1;
GEvent.addListener(marker, "dragend", function(){
write_point();
});
}
else if (point && added) {
marker.setPoint(point);
}
write_point();
get_address();
});
}
function showAddress(address) {
geocoder.getLatLng(
address,
function(point) {
if (!point) {
alert(address + " not found");
} else {
map.setCenter(point, 11);
if(!marker) {
marker = new GMarker(point, {icon:G_DEFAULT_ICON, draggable: true, title: "Click to get address"});
map.addOverlay(marker);
get_address();
added = 1;
}
marker.setPoint(point);
write_point();
}
}
);
}
function showLat49Ads(){
Lat49.initAds(19);
var center = map.getCenter();
var lat = center.lat();
var lng = center.lng();
var zoomlevel = Lat49.Tile.convertGMap2Zoom(map.getZoom());
Lat49.updateAdByLatLon("lat49ads", lat, lng, zoomlevel);
}
function load(){
map = new GMap2(document.getElementById("map"),{draggableCursor: 'crosshair', draggingCursor: 'crosshair'});
map.addControl(new GSmallZoomControl());
map.addControl(new GMenuMapTypeControl(),new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(61,7)));
map.addMapType(G_PHYSICAL_MAP);
map.addControl(new GOverviewMapControl());
var boxStyleOpts = { opacity: .2, border: "2px solid yellow" };
var otherOpts = {
buttonHTML: "<img src='zoom-control-inactive1.png' title='Drag Zoom' />",
buttonZoomingHTML: "<img src='zoom-control-active1.png' title='Drag Zoom: Cancel' />",
buttonStartingStyle: {width: '15px', height: '15px'},
overlayRemoveTime: 0 };
map.addControl(new DragZoomControl(boxStyleOpts, otherOpts, {}), new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(25,7)));
map.setCenter(new GLatLng(37.35, -121.93), 12);
draw_point();
showLat49Ads();
GEvent.addListener(map, "moveend", showLat49Ads);
}
//]]>
</script>
</head>
<body onload="load()" onunload="GUnload()">
<table width="100%" height="100%" style="width:100%; height:100%">
<tr style="vertical-align:top">
<td style="width:320px">
<table><tr>
</tr></table>
</td>
<td>
</td>
<td align="right">
<nobr>
<form action="#" onsubmit="showAddress(this.address.value); return false">
<input type="text" size="30" name="address" value="Chicago, IL" />
<input type="submit" value="Go!" />
</form>
</nobr>
</td>
</tr>
<tr>
<td valign="top">
<div style="width:300px;font-size:8pt"><h1>GeoCoder</h1>Click on the map or search a place to add a marker and drag marker around to get marker position coordinates. Click on marker to get approximate address.</div>
<br><span style="font-size:8pt"><b>Coordinates (lat, lng):</b> [for GLatLng]</span><br>
<input type="text" size="30" id="coord" onclick="this.select()"/>
<br><br><span style="font-size:8pt"><b>Coordinates (lng, lat):</b> [for KML]</span><br>
<input type="text" size="30" id="kml" onclick="this.select()"/>
<br><br><span style="font-size:8pt"><b>Coordinates (lat="x.xx" lng="x.xx"):</b></span><br>
<input type="text" size="30" id="attribute" onclick="this.select()"/>
<br><br><span style="font-size:8pt"><b>Coordinates (<lat> <lng>):</b></span><br>
<textarea rows="2" cols="24" id="latlng" onclick="this.select()" ></textarea>
<br>
<br>
<script type="text/javascript"><!--
google_ad_client = "pub-2773616400896769";
/* maptools_300x250_01 */
google_ad_slot = "1034665593";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
</td>
<td colspan="2" width="100%" height="100%">
<div style="position:relative;width:100%;height:100%">
<div id="lat49ads" lat49adposition="top-right"
style="position:absolute;top:7px; right:4px; width:125px; height:133;z-index:99999;"></div>
<div id="map" style="width:100%;height:400px;min-height:400px;border:1px solid #999;"></div>
</div>
</td>
</tr>
</table>
</body>
</html>
if anyone have any idea regarding to code i posted earlier please post a comment.
thanks