Solved

Explanation of how chunk of C# works with JavaScript

Posted on 2008-10-27
3
713 Views
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;

        searchResults.DataBind();
 

        // 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);

        connection.Open();

        

        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(); 

        da.Fill(data.Location);

        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();

        builder.AppendLine(firstLine);
 

        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,

                HttpUtility.HtmlEncode(row.LocationName),

                HttpUtility.HtmlEncode(locationAddress),

                HttpUtility.UrlEncode(locationAddress),

                row.Longitude,

                row.Latitude),

                "}", Environment.NewLine);

            builder.AppendLine(jsonLocation);
 

            // 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)

            {

                builder.Append(',');

            }

        }
 

        builder.AppendLine(lastLine);

        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)

        {

            _itemCount++; 

            Literal locationNumber =(Literal) e.Item.FindControl("locationNumber");

            locationNumber.Text = _itemCount.ToString(); 

        }

    }

}
 
 
 
 

=================  JavaScript in page: ==================
 

<script type="text/javascript">

    //<![CDATA[

    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 = "http://www.google.com/mapfiles/shadow50.png";

            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="http://maps.google.com/maps?f=q&hl=en&q=from:'+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 = northEast.lat() - southWest.lat();

            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));

            }

          }

        }

    }
 

    //]]>

    </script>

Open in new window

0
Comment
Question by:bmanmike39
3 Comments
 
LVL 21

Expert Comment

by:silemone
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
0
 
LVL 6

Accepted Solution

by:
AmarIs26 earned 500 total points
ID: 22813806
JSON (JavaScript Object Notation) is a lightweight data-interchange format. In asp.net 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

GetJsonHomeSpatialInfo
GetJSONLocations

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.

ProximityLocations.locations[i].latitude

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());
            ms.Close();
        }
        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.
0

Featured Post

What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

Problem Hi all,    While many today have fast Internet connection, there are many still who do not, or are connecting through devices with a slower connect, so light web pages and fast load times are still popular.    If your ASP.NET page …
Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
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…

746 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

Need Help in Real-Time?

Connect with top rated Experts

8 Experts available now in Live!

Get 1:1 Help Now