Ajax call start loading like a freak - c#

I have a site for testing Ajax... and it works:
<%# Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true"
CodeBehind="AJAX.aspx.cs" Inherits="HB___test.AJAX" %>
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
<script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
function Ajax() {
var xmlHttp;
try {
xmlHttp = new XMLHttpRequest(); // Firefox, Opera 8.0+, Safari
} catch (e) {
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP"); // Internet Explorer
} catch (e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
alert("No AJAX!?");
return false;
}
}
}
xmlHttp.onreadystatechange = function () {
document.getElementById('chat').innerHTML = xmlHttp.responseText;
setTimeout('Ajax()', 10000);
}
xmlHttp.open("GET", "ajax-Content.aspx", true);
xmlHttp.send(null);
}
window.onload = function () {
setTimeout('Ajax()', 10000);
}
</script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
Kummefryser...!
<div id="chat" class="fisk" style="width: 500px; height: 500px">
</div>
</asp:Content>
And here is the site it's laoding:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="ajax-Content.aspx.cs" Inherits="HB___test.ajax_Content" %>
<body>
<form id="form1" runat="server">
<div>
<asp:ListBox ID="lbChat" runat="server" Rows="10" Width="400px"></asp:ListBox>
</div>
</form>
</body>
And the codebehind for the above site:
public partial class ajax_Content : System.Web.UI.Page
{
grjenie31Entities gr;
protected void Page_Load(object sender, EventArgs e)
{
gr = new grjenie31Entities();
var query = from es in gr.chats
where es.id > ((from esh in gr.chats select esh.id).Max() - 15)
orderby es.timestamps descending
select es;
List<chat> list = new List<chat>();
foreach (chat chat in query)
{
list.Add(chat);
}
for (int i = 0; i < list.Count; i++)
{
lbChat.Items.Add("[" + list[i].timestamps + "] " + list[i].personID.ToString() + ": " + list[i].besked);
}
this.lbChat.SelectedIndex = this.lbChat.Items.Count - 1;
}
}
But when I load the site ajax-Content.aspx it start reloading freakingly fast... so in 30 seconds I can't read the text it load in the ajax.Content.aspx site.
Any ideas??

xmlHttp.onreadystatechange fires not only on success, you should only start the new timeout on readystate 4
furtherMore you should define a variable for the timeout to be able to clear an existing timeout before running a new.

Related

how to pass mxgraph generated xml to Action of controller?

I have started a project using asp.net mvc5 and then downloaded the mxGraph project from its original source of github https://github.com/jgraph/mxgraph
I have loaded mxgraph www folder and also src folder in my mvc project and edited my Index.cshtml file as below
<!--[if IE]><meta http-equiv="X-UA-Compatible" content="IE=5,IE=9" ><!
[endif]-->
<!DOCTYPE html>
<html>
<head>
<title>Grapheditor</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<link rel="stylesheet" type="text/css" href="/styles/grapheditor.css">
<script type="text/javascript">
var urlParams = (function(url)
{
var result = new Object();
var idx = url.lastIndexOf('?');
if (idx > 0)
{
var params = url.substring(idx + 1).split('&');
for (var i = 0; i < params.length; i++)
{
idx = params[i].indexOf('=');
if (idx > 0)
{
result[params[i].substring(0, idx)] = params[i].substring(idx + 1);
}
}
}
return result;
})(window.location.href);
mxLoadResources = false;
</script>
<script type="text/javascript" src="/js/Init.js"></script>
<script type="text/javascript" src="/deflate/pako.min.js"></script>
<script type="text/javascript" src="/deflate/base64.js"></script>
<script type="text/javascript" src="/jscolor/jscolor.js"></script>
<script type="text/javascript" src="/sanitizer/sanitizer.min.js"></script>
<script type="text/javascript" src="/src/js/mxClient.js"></script>
<script type="text/javascript" src="/js/EditorUi.js"></script>
<script type="text/javascript" src="/js/Editor.js"></script>
<script type="text/javascript" src="/js/Sidebar.js"></script>
<script type="text/javascript" src="/js/Graph.js"></script>
<script type="text/javascript" src="/js/Format.js"></script>
<script type="text/javascript" src="/js/Shapes.js"></script>
<script type="text/javascript" src="/js/Actions.js"></script>
<script type="text/javascript" src="/js/Menus.js"></script>
<script type="text/javascript" src="/js/Toolbar.js"></script>
<script type="text/javascript" src="/js/Dialogs.js"></script>
</head>
<body class="geEditor">
<script type="text/javascript">
(function() {
var editorUiInit = EditorUi.prototype.init;
EditorUi.prototype.init = function() {
editorUiInit.apply(this, arguments);
this.actions.get('export').setEnabled(false);
if (!Editor.useLocalStorage)
{
mxUtils.post(OPEN_URL, '', mxUtils.bind(this, function(req) {
var enabled = req.getStatus() != 404;
this.actions.get('open').setEnabled(enabled || Graph.fileSupport);
this.actions.get('import').setEnabled(enabled || Graph.fileSupport);
this.actions.get('save').setEnabled(enabled);
this.actions.get('saveAs').setEnabled(enabled);
this.actions.get('export').setEnabled(enabled);
}));
}
};
mxResources.loadDefaultBundle = false;
var bundle = mxResources.getDefaultBundle(RESOURCE_BASE, mxLanguage) || mxResources.getSpecialBundle(RESOURCE_BASE, mxLanguage);
mxUtils.getAll([bundle, /*STYLE_PATH +*/ '/styles/default.xml'], function(xhr) {
mxResources.parse(xhr[0].getText());
var themes = new Object();
themes[Graph.prototype.defaultThemeName] = xhr[1].getDocumentElement();
new EditorUi(new Editor(urlParams['chrome'] == '0', themes));
}, function() {
document.body.innerHTML = '<center style="margin-top:10%;">Error loading resource files. Please check browser console.</center>';
});
})();
</script>
</body>
</html>
this page loads properly.
and my init.js is as below:
// URLs for save and export
window.EXPORT_URL = window.EXPORT_URL || '/export';
window.SAVE_URL = window.SAVE_URL || 'save';
window.OPEN_URL = window.OPEN_URL || '/open.html';
window.RESOURCES_PATH = window.RESOURCES_PATH || '/resources';
window.RESOURCE_BASE = window.RESOURCE_BASE || window.RESOURCES_PATH + '/grapheditor';
window.STENCIL_PATH = window.STENCIL_PATH || '/stencils';
window.IMAGE_PATH = window.IMAGE_PATH || '/images';
window.STYLE_PATH = window.STYLE_PATH || '/styles';
window.CSS_PATH = window.CSS_PATH || '/styles';
window.OPEN_FORM = window.OPEN_FORM || '/open.html';
window.mxBasePath = window.mxBasePath || '/src';
window.mxLanguage = window.mxLanguage || urlParams['lang'];
window.mxLanguages = window.mxLanguages || ['de'];
and now i want to pass the generated xml to my Action after drawing diagram and click on File/Save.
Thanks for Reply. I found solution of my mean.
#{
Layout = null;
}
<!--[if IE]><meta http-equiv="X-UA-Compatible" content="IE=5,IE=9" ><![endif]-->
<!DOCTYPE html>
<html>
<head>
<!--head is as past and jquery added-->
//previous repeated code collapsed for brevity
<script src="~/Scripts/jquery-3.3.1.min.js"></script>
</head>
<body class="geEditor">
<script type="text/javascript">
// Extends EditorUi to update I/O action states based on availability of backend
(function () {
var editorUiInit = EditorUi.prototype.init;
EditorUi.prototype.init = function () {
editorUiInit.apply(this, arguments);
this.actions.get('export').setEnabled(false);
//previous repeated code collapsed for brevity
this.editor.setFilename('doc1.xml');
//save editorUi object
var editorUI = this;
//this part shal be inserted
//override EditorUi.saveFile function for customization
this.save = saveXml;
function saveXml() {
if (editorUI.editor.graph.isEditing()) {
editorUI.editor.graph.stopEditing();
}
var xml = mxUtils.getXml(editorUI.editor.getGraphXml());
//xml = encodeURIComponent(xml);
if (xml.length < MAX_REQUEST_SIZE) {
$.ajax({
type: "POST",
url: "home/save",
processData: false,
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ 'xml': xml }),
success: function (response) {
//alert(response.message);
},
error: function (ex) {
alert(ex.message);
}
});
}
else {
mxUtils.alert(mxResources.get('drawingTooLarge'));
mxUtils.popup(xml);
return;
}
};
//reset onload open function
this.open = defaultOpen;
function defaultOpen() {};
};
})();
</script>
</body>
</html>

Javascript not working with Ext.Net

I am using Asp.net with Ext.Net framework. And I must use Javascript code (not ext.net code).
Default.aspx page:
<asp:UpdatePanel runat="server">
<ContentTemplate>
<asp:Button runat="server" Text="tıkla" ID="btnGetir" OnClick="btnGetir_Click" />
............
............
Default.aspx.cs page:
public void btnGetir_Click(object sender, EventArgs e)
{
String url = "http://blablablablabla:8080/MeramElektrik2/webresources/entities.layers/GetLayer/1004";
String html_sonuc;
WebResponse objResponse;
WebRequest objRequest = HttpWebRequest.Create(url);
objResponse = objRequest.GetResponse();
using (StreamReader sr =
new StreamReader(objResponse.GetResponseStream()))
{
html_sonuc = sr.ReadToEnd();
sr.Close();
}
////////////Script Çalıştırma Kodu///////////////////////////
ScriptManager.RegisterStartupScript(
this,
this.GetType(),
"deneme2",
"deserialize('" + html_sonuc + "');",
true);
/////////////////////////////////////////////////////////////
txtScript.Text = html_sonuc;
}
OpenLayerUsers.js page:
function deserialize(html_sonuc) { //GEOJSON I, ÇİZİLMİŞ ŞEKLE DÖNÜŞTÜRÜYOR
//var element = document.getElementById('txtScript');
var features = geojson.read(html_sonuc);
//var features = json.read(element.value);
var bounds;
if (features) {
if (features.constructor != Array) {
features = [features];
}
for (var i = 0; i < features.length; ++i) {
if (!bounds) {
bounds = features[i].geometry.getBounds();
} else {
bounds.extend(features[i].geometry.getBounds());
}
}
vectors.addFeatures(features);
map.zoomToExtent(bounds);
var plural = (features.length > 1) ? 's' : '';
//element.value = features.length + ' feature' + plural + ' added'
} else {
//element.value = 'Bad input';
}
}
Result, deserialize(html_sonuc) function not working.
here is the simple test case
aspx page
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="Js/jquery-1.8.2.min.js"></script>
<script>
Ext.onReady(function () {
});
function deserialize(testdt) {
alert('sonic bumm:' + testdt);
}
</script>
</head>
<body>
<form id="form1" runat="server">
<ext:ResourceManager ID="myrsc" runat="server"></ext:ResourceManager>
<div>
<asp:Button runat="server" Text="tıkla" ID="btnGetir" OnClick="btnGetir_Click" />
</div>
</form>
</body>
</html>
and the code behind;
protected void btnGetir_Click(object sender, EventArgs e)
{
// do something here
// and add the client script
string testdt = "testdata";
string script = "deserialize('" + testdt + "')";
myrsc.AddScript(script);
}

how to access values returned by google feed api in page load?

am currently using google feed api to get feed links dynamically. am trying to use the results returned by the api to create rss feed for my website..Now the problem is api function call takes place only after the page load so i cant access the url values returned by the api in page load function..
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
<script type="text/javascript" src="https://www.google.com/jsapi?key=ABQIAAAAxII5vpTAk5gatTPIMAFoCxStIDvCAqMV0_KActMytIL1qEezxxQeBqRzIurcFfnrUgG2YMlC07VgbQ"></script>
<script type="text/javascript">
google.load("feeds", "1", { "callback": OnLoad });
function OnLoad() {
// Query for president feeds on cnn.com
var query = 'atlanta bridal shows';
google.feeds.findFeeds(query, findDone);
}
function findDone(result) {
// Make sure we didn't get an error.
if (!result.error) {
// Get content div
var content = document.getElementById('content');
var html = '';
var submenu = new Array()
// Loop through the results and print out the title of the feed and link to
// the url.
for (var i = 0; i < result.entries.length; i++) {
var entry = result.entries[i];
html += '<p>' + entry.title + '</p>';
submenu[i] = entry.url;
}
content.innerHTML = html;
document.getElementById('<%= Hidden1.ClientID %>').value = submenu;
}
}
google.setOnLoadCallback(OnLoad);
</script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<asp:HiddenField ID="Hidden1" runat="server" ondatabinding="Hidden1_DataBinding"
onunload="Hidden1_Unload" onvaluechanged="Hidden1_ValueChanged" />
<div id="content"></div>
</asp:Content>
pageload event:
protected void Page_Load(object sender, EventArgs e)
{
WebClient client = new WebClient();
string path = Request.Url.GetLeftPart(UriPartial.Authority) +
VirtualPathUtility.ToAbsolute("~/user/feed.htm");
Stream stream = client.OpenRead(path);
StreamReader sr = new StreamReader(stream);
string content = sr.ReadToEnd();
}
What should i do to access the values returned by the api in page load??
First of all you have to create feed.htm and put above code in it.
feed.htm (which is located at root of web-app)
<script type="text/javascript" src="https://www.google.com/jsapi?key=ABQIAAAAxII5vpTAk5gatTPIMAFoCxStIDvCAqMV0_KActMytIL1qEezxxQeBqRzIurcFfnrUgG2YMlC07VgbQ"></script>
<script type="text/javascript">
google.load("feeds", "1", { "callback": OnLoad });
function OnLoad() {
// Query for president feeds on cnn.com
var query = 'atlanta bridal shows';
google.feeds.findFeeds(query, findDone);
}
function findDone(result) {
// Make sure we didn't get an error.
if (!result.error) {
// Get content div
var content = document.getElementById('content');
var html = '';
var submenu = new Array()
// Loop through the results and print out the title of the feed and link to
// the url.
for (var i = 0; i < result.entries.length; i++) {
var entry = result.entries[i];
html += '<p>' + entry.title + '</p>';
submenu[i] = entry.url;
}
content.innerHTML = html;
document.getElementById('<%= Hidden1.ClientID %>').value = submenu;
}
}
google.setOnLoadCallback(OnLoad);
</script>
<div id="content"></div>
Then after in page_load event of .aspx page use System.Net.WebClient class methods to request the feed.htm.
TestFeed.aspx (which is located at root of web-app)
Markup:
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server"></asp:Label>
</div>
</form>
</body>
Code-behind:
protected void Page_Load(object sender, EventArgs e)
{
WebClient client = new WebClient();
string path = Request.Url.GetLeftPart(UriPartial.Authority) + VirtualPathUtility.ToAbsolute("~/feed.htm");
Stream stream = client.OpenRead(path);
StreamReader sr = new StreamReader(stream);
//To view the result
Label1.Text = sr.ReadToEnd();
}

How can I retrieve query string from my webpage .ASPX to my HTML file script?

Here is my Code in my page 'Welcome.aspx.cs':
protected void Page_PreRender(object sender, EventArgs e)
{
string menus = string.Empty;
if (this.hfAccessLvl.Value == string.Empty)
{
Response.Redirect("login.aspx");
}
myMenu.Text = AlMenu("js/MyMenu.html?accesLevel=" + this.hfAccessLvl.Value + "|" + virtualDrive, "no", "400px", "100");
}
In my MyMenu.html code:
<html>
<body runat="server">
<form id="form1" runat="server">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html;CHARSET=iso-8859-1" />
<title>Test Only</title>
<script type="text/javascript" src="jquery.min.js"></script>
<script language="JavaScript" src="crossbrowser.js" type="text/javascript"></script>
<script language="JavaScript" src="outlook.js" type="text/javascript"></script>
<script type="text/javascript">
var o = new createOutlookBar('Bar',0,0,screenSize.width,screenSize.height,'#606060','white')
var p
var accessLevell = GetQueryString('accesLevel').split('|')[0]; // Get Access level of user
var virtualDrive = GetQueryString('accesLevel').split('|')[1]; // Get Virtual drive that was set if any...
//create first panel
p = new createPanel('al','Nestle Web Sites');
p.addButton('home.gif','Home','parent.location="' + virtualDrive + '/Welcome.aspx"');
p.addButton('home.gif','Log-Out','parent.location="' + virtualDrive + '/Login.aspx"');
o.addPanel(p);
o.draw();
</script>
</head>
</form>
</body>
</html>
Now I want to get the query string value that I'd pass from Welcome.aspx.cs in my MyMenu.html script file:
var accessLevell = GetQueryString('accesLevel').split('|')[0];
var virtualDrive = GetQueryString('accesLevel').split('|')[1];
Try this:
function GetQueryString( name )
{
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( window.location.href );
if( results == null )
return "";
else
return results[1];
}
(code taken from http://www.netlobo.com/url_query_string_javascript.html )

Google map blank when used with master page

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

Categories

Resources