Trying to implement AJAX and WebService to return xml, using this to populate a javascript array and create a Google Map with markers.
I think my problem is with the WebService itself, as it keeps returning Null.
Sorry for the messy code ahead of time, playing around with just everything to get this to work.
wsGetLatLog.asmx -
Imports System.Web.Services
Imports System.Web.Services.Protocols
Imports System.ComponentModel
Imports System.Web.Script.Services
Imports System.Data
Imports System.Data.SqlClient
Imports System.Xml
<System.Web.Script.Services.ScriptService()> _
<System.Web.Services.WebService(Namespace:="http://getSQLLatLogDAL.com/", Description:="This Service contains methods that gets geo data from SQL")> _
<System.Web.Services.WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<ToolboxItem(False)> _
Public Class wsGetLatLog
Inherits System.Web.Services.WebService
<WebMethod()> _
Public Function getAll() As String
Dim strConnection As String = ConfigurationManager.ConnectionStrings("ConnectionString").ToString()
Dim connection As SqlConnection = Nothing
Dim queryString As String
Dim output(4) As Array
Dim ds As DataSet = Nothing
queryString = "SELECT [intKey], [txtStreet], [streetLat], [streetLog] FROM [properties]"
connection = New SqlConnection(strConnection)
connection.Open()
Dim adapter As New SqlDataAdapter(queryString, connection)
ds = New DataSet()
adapter.Fill(ds, "marker")
Return ds.GetXml.ToString()
End Function
End Class
googleMapsV3.js -
function createXmlHttpRequest() {
try {
if (typeof ActiveXObject != 'undefined') {
return new ActiveXObject('Microsoft.XMLHTTP');
} else if (window["XMLHttpRequest"]) {
return new XMLHttpRequest();
}
} catch (e) {
changeStatus(e);
}
return null;
};
function xmlParse(str) {
if (typeof ActiveXObject != 'undefined' && typeof GetObject != 'undefined') {
var doc = new ActiveXObject('Microsoft.XMLDOM');
doc.loadXML(str);
return doc;
}
if (typeof DOMParser != 'undefined') {
return (new DOMParser()).parseFromString(str, 'text/xml');
}
return createElement('div', null);
}
function initialize(xml) {
var myOptions = {
zoom: 14,
center: new google.maps.LatLng(37.293, -87.123),
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
var markers = xml.documentElement.getElementsByTagName("marker");
var properties = new Array(markers.length);
for (var i = 0; i < markers.length; i++) {
properties[i] = new Array(3);
//[i,0] = intKey
properties[i, 0] = markers[i].childNodes[0].nodeValue;
alert(properties[i, 0]);
//[i,1] = txtStreet
properties[i, 1] = markers[i].childNodes[1].nodeValue;
alert(properties[i, 1]);
//[i,2] = streetLat
properties[i, 2] = markers[i].childNodes[2].nodeValue;
alert(properties[i, 2]);
//[i,3] = streetLog
properties[i, 3] = markers[i].childNodes[3].nodeValue;
alert(properties[i, 3]);
}
setMarkers(map, properties);
}
function setMarkers(map, locations) {
// Add markers to the map
// Marker sizes are expressed as a Size of X,Y
// where the origin of the image (0,0) is located
// in the top left of the image.
// Origins, anchor positions and coordinates of the marker
// increase in the X direction to the right and in
// the Y direction down.
var image = new google.maps.MarkerImage('/images/home.png',
// This marker is 20 pixels wide by 32 pixels tall.
new google.maps.Size(32, 27),
// The origin for this image is 0,0.
new google.maps.Point(0, 0),
// The anchor for this image is the base of the flagpole at 0,32.
new google.maps.Point(0, 27));
var shape = {
coord: [1, 1, 1, 32, 32, 27, 32, 1],
type: 'poly'
};
var onMarkerClick = function (url) {
window.location.href = varUrl;
};
for (var i = 0; i < locations.length; i++) {
var beach = locations[i];
var myLatLng = new google.maps.LatLng(beach[2], beach[3]);
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
icon: image,
shape: shape,
title: beach[1],
zIndex: beach[0],
html: "/propertyHouse.aspx?intKey=" + beach[0]
});
google.maps.event.addListener(marker, 'click', (function (marker, i) {
return function () {
window.location.href = this.html;
}
})(marker, i));
}
}
Thanks for your assistance. I debugged the webservice, but never got it to work quite right.
Instead I switched from using a webservice to just calling the db from the code-behind, putting it in a ADO.NET DataTable, and manually writing the javascript in a StringBuilder.
Private Sub Page_PreRender(sender As Object, e As System.EventArgs) Handles Me.PreRender
getAll()
End Sub
Public Sub getAll()
Dim strConnection As String = ConfigurationManager.ConnectionStrings("ConnectionString").ToString()
Dim connection As SqlConnection = Nothing
Dim queryString As String
Dim output(4) As Array
queryString = "SELECT [intKey], [txtStreet], [streetLat], [streetLog] FROM [properties]"
connection = New SqlConnection(strConnection)
connection.Open()
Dim adapter As New SqlDataAdapter(queryString, connection)
Dim ds As DataSet = New DataSet
adapter.Fill(ds, "markers")
Dim javascript As New StringBuilder()
Dim dataTable As New DataTable()
dataTable = ds.Tables(0)
Dim i As Integer = 0
Dim rowCount As Integer = dataTable.Rows.Count
For i = 0 To rowCount - 1 Step 1
If (i = 0) Then
javascript.Append("var properties = [")
End If
Dim dataRow As DataRow = dataTable.Rows(i)
For j As Integer = 0 To dataRow.Table.Columns.Count - 1
If j = 0 Then
javascript.Append("[")
End If
Dim value As String = dataRow(j).ToString().Trim()
javascript.Append("'" & value & "'")
If (j + 1) = dataRow.Table.Columns.Count Then
javascript.Append("]")
Else
javascript.Append(",")
End If
Next
If (i + 1) = dataTable.Rows.Count Then
javascript.Append(vbLf & "];" & vbLf)
Else
javascript.Append("," & vbLf)
End If
Next
Page.ClientScript.RegisterClientScriptBlock(scriptType, "ArrayScript", javascript.ToString(), True)
connection.Close()
End Sub
Marked as answer by weklund on Jun 29, 2012 03:02 PM
weklund
Member
1 Points
5 Posts
Problem with WebService/AJAX Implementation
Jun 25, 2012 10:53 PM|LINK
Trying to implement AJAX and WebService to return xml, using this to populate a javascript array and create a Google Map with markers.
I think my problem is with the WebService itself, as it keeps returning Null.
Sorry for the messy code ahead of time, playing around with just everything to get this to work.
wsGetLatLog.asmx -
Imports System.Web.Services Imports System.Web.Services.Protocols Imports System.ComponentModel Imports System.Web.Script.Services Imports System.Data Imports System.Data.SqlClient Imports System.Xml <System.Web.Script.Services.ScriptService()> _ <System.Web.Services.WebService(Namespace:="http://getSQLLatLogDAL.com/", Description:="This Service contains methods that gets geo data from SQL")> _ <System.Web.Services.WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _ <ToolboxItem(False)> _ Public Class wsGetLatLog Inherits System.Web.Services.WebService <WebMethod()> _ Public Function getAll() As String Dim strConnection As String = ConfigurationManager.ConnectionStrings("ConnectionString").ToString() Dim connection As SqlConnection = Nothing Dim queryString As String Dim output(4) As Array Dim ds As DataSet = Nothing queryString = "SELECT [intKey], [txtStreet], [streetLat], [streetLog] FROM [properties]" connection = New SqlConnection(strConnection) connection.Open() Dim adapter As New SqlDataAdapter(queryString, connection) ds = New DataSet() adapter.Fill(ds, "marker") Return ds.GetXml.ToString() End Function End ClassgoogleMapsV3.js -
function createXmlHttpRequest() { try { if (typeof ActiveXObject != 'undefined') { return new ActiveXObject('Microsoft.XMLHTTP'); } else if (window["XMLHttpRequest"]) { return new XMLHttpRequest(); } } catch (e) { changeStatus(e); } return null; }; function xmlParse(str) { if (typeof ActiveXObject != 'undefined' && typeof GetObject != 'undefined') { var doc = new ActiveXObject('Microsoft.XMLDOM'); doc.loadXML(str); return doc; } if (typeof DOMParser != 'undefined') { return (new DOMParser()).parseFromString(str, 'text/xml'); } return createElement('div', null); } function initialize(xml) { var myOptions = { zoom: 14, center: new google.maps.LatLng(37.293, -87.123), mapTypeId: google.maps.MapTypeId.ROADMAP } var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); var markers = xml.documentElement.getElementsByTagName("marker"); var properties = new Array(markers.length); for (var i = 0; i < markers.length; i++) { properties[i] = new Array(3); //[i,0] = intKey properties[i, 0] = markers[i].childNodes[0].nodeValue; alert(properties[i, 0]); //[i,1] = txtStreet properties[i, 1] = markers[i].childNodes[1].nodeValue; alert(properties[i, 1]); //[i,2] = streetLat properties[i, 2] = markers[i].childNodes[2].nodeValue; alert(properties[i, 2]); //[i,3] = streetLog properties[i, 3] = markers[i].childNodes[3].nodeValue; alert(properties[i, 3]); } setMarkers(map, properties); } function setMarkers(map, locations) { // Add markers to the map // Marker sizes are expressed as a Size of X,Y // where the origin of the image (0,0) is located // in the top left of the image. // Origins, anchor positions and coordinates of the marker // increase in the X direction to the right and in // the Y direction down. var image = new google.maps.MarkerImage('/images/home.png', // This marker is 20 pixels wide by 32 pixels tall. new google.maps.Size(32, 27), // The origin for this image is 0,0. new google.maps.Point(0, 0), // The anchor for this image is the base of the flagpole at 0,32. new google.maps.Point(0, 27)); var shape = { coord: [1, 1, 1, 32, 32, 27, 32, 1], type: 'poly' }; var onMarkerClick = function (url) { window.location.href = varUrl; }; for (var i = 0; i < locations.length; i++) { var beach = locations[i]; var myLatLng = new google.maps.LatLng(beach[2], beach[3]); var marker = new google.maps.Marker({ position: myLatLng, map: map, icon: image, shape: shape, title: beach[1], zIndex: beach[0], html: "/propertyHouse.aspx?intKey=" + beach[0] }); google.maps.event.addListener(marker, 'click', (function (marker, i) { return function () { window.location.href = this.html; } })(marker, i)); } }default.aspx -
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent"> <asp:ScriptManager runat="server" ID="scriptManagerId" EnableCdn="True" EnablePageMethods="True"> <Scripts> <asp:ScriptReference Path="googleMapsV3.js" /> </Scripts> <Services> <asp:ServiceReference Path="wsGetLatLog.asmx" /> </Services> </asp:ScriptManager> <script type="text/javascript"> var DelayInSeconds = 2; var xml = xmlparse(wsGetLatLog.getAll()); function InitConstantCall() { setTimeout('ConstantCall()', DelayInSeconds * 1000); } function ConstantCall() { initialize(xml); } </script> <div id="sidebar" class="grid_10 push_1"> <h3>Map</h3> <div id="map_canvas"></div> </div> <div class="clear"></div> </asp:Content>Scriptmanager ajax javascript webservice googleMaps
weklund
Member
1 Points
5 Posts
Re: Problem with WebService/AJAX Implementation
Jun 25, 2012 11:03 PM|LINK
1 element would look just like this:
<marker>
<intKey>4</intKey>
<txtStreet>633 Stringtown Rd</txtStreet>
<streetLat>37.2834244</streetLat>
<streetLog>-87.1276317</streetLog>
</marker>
Catherine Sh...
All-Star
23372 Points
2490 Posts
Microsoft
Re: Problem with WebService/AJAX Implementation
Jun 29, 2012 07:44 AM|LINK
Hi,
According to your description above, it seems like that there is something wrong with webservice. Thus, I would suggest you do it as follows:
1. Do the query in the database and see whether it returns null.
2. If it can return data from the database, please set a break point at the code below and see whether ds is null.
If it is, please debug the webservice step by step and try to find the issue.
Best wishes,
Feedback to us
Develop and promote your apps in Windows Store
weklund
Member
1 Points
5 Posts
Re: Problem with WebService/AJAX Implementation
Jun 29, 2012 03:02 PM|LINK
Thanks for your assistance. I debugged the webservice, but never got it to work quite right.
Instead I switched from using a webservice to just calling the db from the code-behind, putting it in a ADO.NET DataTable, and manually writing the javascript in a StringBuilder.
Private Sub Page_PreRender(sender As Object, e As System.EventArgs) Handles Me.PreRender getAll() End Sub Public Sub getAll() Dim strConnection As String = ConfigurationManager.ConnectionStrings("ConnectionString").ToString() Dim connection As SqlConnection = Nothing Dim queryString As String Dim output(4) As Array queryString = "SELECT [intKey], [txtStreet], [streetLat], [streetLog] FROM [properties]" connection = New SqlConnection(strConnection) connection.Open() Dim adapter As New SqlDataAdapter(queryString, connection) Dim ds As DataSet = New DataSet adapter.Fill(ds, "markers") Dim javascript As New StringBuilder() Dim dataTable As New DataTable() dataTable = ds.Tables(0) Dim i As Integer = 0 Dim rowCount As Integer = dataTable.Rows.Count For i = 0 To rowCount - 1 Step 1 If (i = 0) Then javascript.Append("var properties = [") End If Dim dataRow As DataRow = dataTable.Rows(i) For j As Integer = 0 To dataRow.Table.Columns.Count - 1 If j = 0 Then javascript.Append("[") End If Dim value As String = dataRow(j).ToString().Trim() javascript.Append("'" & value & "'") If (j + 1) = dataRow.Table.Columns.Count Then javascript.Append("]") Else javascript.Append(",") End If Next If (i + 1) = dataTable.Rows.Count Then javascript.Append(vbLf & "];" & vbLf) Else javascript.Append("," & vbLf) End If Next Page.ClientScript.RegisterClientScriptBlock(scriptType, "ArrayScript", javascript.ToString(), True) connection.Close() End Sub