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
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
  • 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

Efficient way to get backups off site to Azure

This user guide provides instructions on how to deploy and configure both a StoneFly Scale Out NAS Enterprise Cloud Drive virtual machine and Veeam Cloud Connect in the Microsoft Azure Cloud.

Question has a verified solution.

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

This article aims to explain the working of CircularLogArchiver. This tool was designed to solve the buildup of log file in cases where systems do not support circular logging or where circular logging is not enabled
The article shows the basic steps of integrating an HTML theme template into an ASP.NET MVC project
There's a multitude of different network monitoring solutions out there, and you're probably wondering what makes NetCrunch so special. It's completely agentless, but does let you create an agent, if you desire. It offers powerful scalability …
Monitoring a network: why having a policy is the best policy? Michael Kulchisky, MCSE, MCSA, MCP, VTSP, VSP, CCSP outlines the enormous benefits of having a policy-based approach when monitoring medium and large networks. Software utilized in this v…

623 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