Solved

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

Posted on 2008-10-15
4
466 Views
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,
        GListener.Event.mouseover);
        GMap1.addInfoWindow(window);
 
 
======  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
        sqlConnection2.Open();
     
        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
        sqlConnection2.Close();

Open in new window

0
Comment
Question by:bmanmike39
  • 2
4 Comments
 
LVL 5

Accepted Solution

by:
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):
http://blog.donnfelker.com/post/HOWTO-Build-a-Store-Locator-in-ASPNET.aspx  
0
 
LVL 5

Expert Comment

by:web4net
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;
        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(); 
        }
    }
}

Open in new window

0

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
custom authorization on controller action and HTML in asp.net mvc 1 42
Unlocking a column in excel using C# 17 26
ModalPopup  question 22 37
Aspx calendar pop up control 3 25
Just a quick little trick I learned recently.  Now that I'm using jQuery with abandon in my asp.net 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…
IntroductionWhile developing web applications, a single page might contain many regions and each region might contain many number of controls with the capability to perform  postback. Many times you might need to perform some action on an ASP.NET po…
The Email Laundry PDF encryption service allows companies to send confidential encrypted  emails to anybody. The PDF document can also contain attachments that are embedded in the encrypted PDF. The password is randomly generated by The Email Laundr…
In an interesting question (https://www.experts-exchange.com/questions/29008360/) here at Experts Exchange, a member asked how to split a single image into multiple images. The primary usage for this is to place many photographs on a flatbed scanner…

679 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