Explanation of how chunk of C# works with JavaScript

Posted on 2008-10-27
Last Modified: 2013-12-17
Below is code Im trying to figure out.  I have a Google map, and Im trying to pull the coordinance out of a database and create markers on the  map.  I found this sample and it is almost what i need. but to add the remaining functionality, i need to understand the code.  Can someone please explain whats happening in this code.  I dont get how the code in the data adapter is being converted to JavaScript and looped though the Gmap API.

Thanks for the help

======================  Code behind:  =================
using GoogleGeocoder;
using System.Text; 
public partial class _Default : System.Web.UI.Page 
    protected void Page_Load(object sender, EventArgs e)
        totalMatchingTitle.Visible = IsPostBack;
        clickInstructions.Visible = IsPostBack; 
    protected void startSearchButton_Click(object sender, EventArgs e)
        clickInstructions.Visible = true; 
        Coordinate coordinate = Geocode.GetCoordinates(addressTextBox.Text);
        LocationsData data = GetLocationData(coordinate);
        // Set up the locations 
        searchResults.DataSource = data.Location;
        // Set result count
        totalResultCount.Text = data.Location.Rows.Count > 0 ? data.Location.Rows.Count.ToString() : "No Results Found.";  
        // Get the locations, in JSON format. 
        string jsonScript = GetJSONLocations(data);
        // Get the home location (where the user entered their address) in JSON format. 
        string homeSpatialInfo = GetJsonHomeSpatialInfo(coordinate, addressTextBox.Text);
        // Write the JSON objects to the client. 
        ClientScript.RegisterClientScriptBlock(GetType(), "homeSpatialInfo", homeSpatialInfo, true); 
        ClientScript.RegisterClientScriptBlock(GetType(), "jsonMapObjects", jsonScript, true);
    /// <summary>
    /// Gets the store locations and the coordinate for the "from" area (the address the user entered). 
    /// </summary>
    /// <param name="coordinate">A coordinate.</param>
    /// <param name="data">A LocationsData dataset.</param>
    private LocationsData GetLocationData(Coordinate coordinate)
        SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["StoresDb"].ConnectionString);
        string SQL = "GetNearbyLocations";
        SqlCommand command = new SqlCommand(SQL, connection);
        command.Parameters.Add(new SqlParameter("@CenterLatitude", coordinate.Latitude));
        command.Parameters.Add(new SqlParameter("@CenterLongitude", coordinate.Longitude));
        command.Parameters.Add(new SqlParameter("@SearchDistance", distanceDropDown.SelectedValue));
        command.Parameters.Add(new SqlParameter("@EarthRadius", 3961));  // In Miles
        command.CommandType = CommandType.StoredProcedure;
        SqlDataAdapter da = new SqlDataAdapter(command);
        LocationsData data = new LocationsData(); 
        return data; 
    /// <summary>
    /// Gets a json variable for the home address and latitude/longitude coordinates.
    /// </summary>
    /// <param name="coordinate">The coordinate.</param>
    /// <param name="fromAddress">The address that of where the map is going to be locaed "from".</param>
    /// <returns>A string representation of a JSON variable.</returns>
    protected string GetJsonHomeSpatialInfo(Coordinate coordinate, string fromAddress)
        string top = "var homeSpatialInfo = {"; 
        string bottom = "};";
        string jsonVariable = String.Format("\"latitude\" : \"{0}\", \"longitude\" : \"{1}\", \"fromAddress\" : \"{2}\"", coordinate.Latitude, coordinate.Longitude, HttpUtility.UrlEncode(fromAddress));
        return String.Concat(top, jsonVariable, bottom, Environment.NewLine); 
    /// <summary>
    /// Retursn a JSON object in the format of a string. 
    /// <remarks>
    /// It should return a string that resembles a JSON object array in this format: 
    /// <example>
    /// var ProximityLocations = {"locations": [
    ///            {"name": "testName", "address": "123 test addre", "urladdress": "123+test+addre", "longitude": "192.009", "latitude" : "65.235"},
    ///            {"name": "tesdsfsdftName", "address": "65 test addre", "urladdress": "123+test+addre", "longitude": "3342.009", "latitude" : "633.235"},
    ///            {"name": "te33333333", "address": "123 test addre", "urladdress": "123+test+addre", "longitude": "123492.009", "latitude" : "15.235"}
    ///           ]};
    /// </example>
    /// If there are no locations, the JSON object will be empty. 
    /// </remarks>
    /// </summary>
    /// <param name="data">The LocationData dataset that has the locations in it.</param>
    /// <returns>A string representation of a JSON object.</returns>
    protected string GetJSONLocations(LocationsData data)
        string firstLine = "var ProximityLocations = {\"locations\": ["; 
        string lastLine = "]};";
        string JSONObjectFormat = "\"name\": \"{0}\", \"address\": \"{1}\", \"urladdress\": \"{2}\", \"longitude\": \"{3}\", \"latitude\" : \"{4}\"";
        StringBuilder builder = new StringBuilder();
        string jsonLocation; 
        string locationAddress; 
        foreach (LocationsData.LocationRow row in data.Location)
            locationAddress = String.Format("{0}, {1}, {2}, {3}", row.Address, row.City, row.State, row.Zip);
            jsonLocation = String.Concat("{", String.Format(JSONObjectFormat,
                "}", Environment.NewLine);
            // Only add comma if it is not the last row. The last row does not have a comma. See example in method comments.
            if (data.Location.Rows.IndexOf(row) != data.Location.Rows.Count-1)
        return builder.ToString(); 
    /// <summary>
    /// A variable to count the number of iterations in the repeater. Used for displaying organized data.
    /// </summary>
    protected int _itemCount = 0; 
    protected void searchResults_ItemDataBound(object sender, RepeaterItemEventArgs e)
        // Add the number to the screen for organization.
        if (e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item)
            Literal locationNumber =(Literal) e.Item.FindControl("locationNumber");
            locationNumber.Text = _itemCount.ToString(); 
=================  JavaScript in page: ==================
<script type="text/javascript">
    var undefined = "undefined"; 
    function load() 
        if(typeof(homeSpatialInfo) != undefined && typeof(ProximityLocations) != undefined)
          if (GBrowserIsCompatible()) {
            var map = new GMap2(document.getElementById("map"));
            map.addControl(new GSmallMapControl());
            map.addControl(new GMapTypeControl());
            map.setCenter(new GLatLng(homeSpatialInfo.latitude, homeSpatialInfo.longitude), 14);
            // Create a base icon for all of our markers that specifies the
            // shadow, icon dimensions, etc.
            var baseIcon = new GIcon();
            baseIcon.shadow = "";
            baseIcon.iconSize = new GSize(20, 34);
            baseIcon.shadowSize = new GSize(37, 34);
            baseIcon.iconAnchor = new GPoint(9, 34);
            baseIcon.infoWindowAnchor = new GPoint(9, 2);
            baseIcon.infoShadowAnchor = new GPoint(18, 25);
            // Creates a marker whose info window displays the letter corresponding// to the given index.
            function createMarker(point, name, address, urladdress, locationNumber) {
              var icon = new GIcon(baseIcon);  
              icon.image = "images/markers/marker" + locationNumber + ".png";
              var marker = new GMarker(point, icon);
              GEvent.addListener(marker, "click", function() {
 // changes here    You also add images here                                                                              // could use var to put link to info page here. string with id              
                marker.openInfoWindowHtml(name + '<br>' + address + '<br>' + '<a target="_blank" href="'+homeSpatialInfo.fromAddress+'+to:'+urladdress+'">Directions</a>');
              return marker;
            // Load all the markers from the JSON ProximityLocations variable
            var bounds = map.getBounds();
            var southWest = bounds.getSouthWest();
            var northEast = bounds.getNorthEast();
            var lngSpan = northEast.lng() - southWest.lng();
            var latSpan = -;
            for (var i = 0; i < ProximityLocations.locations.length; i++) {
              var point = new GLatLng(ProximityLocations.locations[i].latitude,ProximityLocations.locations[i].longitude);
              map.addOverlay(createMarker(point, ProximityLocations.locations[i].name, ProximityLocations.locations[i].address, ProximityLocations.locations[i].urladdress, i+1));

Open in new window

Question by:bmanmike39
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
LVL 21

Expert Comment

ID: 22813527
 // Write the JSON objects to the client.
        ClientScript.RegisterClientScriptBlock(GetType(), "homeSpatialInfo", homeSpatialInfo, true);
        ClientScript.RegisterClientScriptBlock(GetType(), "jsonMapObjects", jsonScript, true);

registers script and gives to json, which is a javascript/aspnet framework

Accepted Solution

AmarIs26 earned 500 total points
ID: 22813806
JSON (JavaScript Object Notation) is a lightweight data-interchange format. In you can convert any object (which is marked as     [Serializable]    [DataContract] ) to JSON format.
One of the common use is to convert the objects at the server from .Net format to JSON format so they can be used in Code.

Your code gets the information from the database and then converts it into JSON format.  for this the method


are used.

These objects are then passed back to the page, which are then used in the javascript code.

 // Write the JSON objects to the client.
ClientScript.RegisterClientScriptBlock(GetType(), "homeSpatialInfo", homeSpatialInfo, true);
ClientScript.RegisterClientScriptBlock(GetType(), "jsonMapObjects", jsonScript, true);

The following if statement checks if the two arrays have been created.
if(typeof(homeSpatialInfo) != undefined && typeof(ProximityLocations) != undefined)

The advantage of converting objects to JSON is that you can use them the same way at the client side as you would in server side code without writing any custom data structure.


Finally, The code in the GetJsonHomeSpatialInfo and GetJSONLocations could be simplified by using a generic serialiser method like the following.

The following is a method which i use in my code:

    public static string SerialiseSearchArgs(SearchEventArgs args)
        DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(SearchEventArgs));
        string jsonData = string.Empty;
        SearchEventArgs s = args;
        using (MemoryStream ms = new MemoryStream())
            ser.WriteObject(ms, s);
            jsonData = Encoding.Default.GetString(ms.ToArray());
        return jsonData;

Whilst the code you already have would be fine, but if you were to use the json concept for your own custom classes, then the above method would make things a lot easier for you.

Featured Post

Resolve Critical IT Incidents Fast

If your data, services or processes become compromised, your organization can suffer damage in just minutes and how fast you communicate during a major IT incident is everything. Learn how to immediately identify incidents & best practices to resolve them quickly and effectively.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Technology Resume 7 68
sort Multi-dimensional array 6 12
Adjust the codes 3 30
Javascript: Range object 16 9
Today I had a very interesting conundrum that had to get solved quickly. Needless to say, it wasn't resolved quickly because when we needed it we were very rushed, but as soon as the conference call was over and I took a step back I saw the correct …
This article will give core knowledge of JavaScript and will head in to your first JavaScript program. I am Durvesh Naik and I am here to deal with this series of JavaScript. I will teach you JavaScript in part wise , as its quite boring to read big…
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

749 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question