Need help with loop to create dynamic markers on a map.

Posted on 2008-10-15
Last Modified: 2013-12-17
How would i get this code to create markers on my map? Below is the code I want to loop through to create the marker, and the code have that connects to the db that has the map coordinance.

below is the code to add a markers,  i just need to know how i would loop this to make it happen

The variables past in from my db are "pxq" and "pyq"

Thanks for any help.

=====   Code i want to loop through and create markers : ========

// pxq & pyq are variable that feed coordinance into the map marker code

        GLatLng latlon = new GLatLng(pxq, pyq);

        GMarker icono = new GMarker(latlon);

        GInfoWindow window = new GInfoWindow(icono, x,false,



======  This is the code i have:  ===============

SqlConnection sqlConnection2 = new SqlConnection("Data Source=.\\SQLEXPRESS  works ....");

    //  SqlCommand cmd = new SqlCommand();

        SqlCommand cmd = new SqlCommand();


	string qustring = "SELECT * FROM xyq ";

cmd.CommandText = qustring;

cmd.CommandType = CommandType.Text;

        cmd.Connection = sqlConnection2;

        //OpenFile connection



        SqlDataReader reader = cmd.ExecuteReader();

           while (reader.Read())


                object zoq = reader[0].ToString();

                object xqt = reader[1].ToString();

                object yqt = reader[2].ToString();

             // converting object to double

                double pxq = double.Parse(xqt.ToString());

                double pyq = double.Parse(yqt.ToString());

	     // pxq and pyq are public vars



        //close connection


Open in new window

Question by:bmanmike39
  • 2

Accepted Solution

web4net earned 500 total points
ID: 22726944
Why reinvent the wheel ... please let me know if the following solution works for you (if not, I have other solutions):  

Expert Comment

ID: 22822882
Any updates?

Here is my sample code.
using System;

using System.Data;

using System.Configuration;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Web.UI.HtmlControls;

using System.Data.SqlClient;

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




Open in new window


Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Just a quick little trick I learned recently.  Now that I'm using jQuery with abandon in my applications, I have grown tired of the following syntax:      (CODE) I suppose it just offends my sense of decency to put inline VBScript on a…
More often than not, we developers are confronted with a need: a need to make some kind of magic happen via code. Whether it is for a client, for the boss, or for our own personal projects, the need must be satisfied. Most of the time, the Framework…
This Micro Tutorial hows how you can integrate  Mac OSX to a Windows Active Directory Domain. Apple has made it easy to allow users to bind their macs to a windows domain with relative ease. The following video show how to bind OSX Mavericks to …
This tutorial gives a high-level tour of the interface of Marketo (a marketing automation tool to help businesses track and engage prospective customers and drive them to purchase). You will see the main areas including Marketing Activities, Design …

920 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

13 Experts available now in Live!

Get 1:1 Help Now