Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

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

Posted on 2008-10-15
4
Medium Priority
?
471 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
[X]
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
4 Comments
 
LVL 5

Accepted Solution

by:
web4net earned 2000 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

RHCE - Red Hat OpenStack Prep Course

This course will provide in-depth training so that students who currently hold the EX200 & EX210 certifications can sit for the EX310 exam. Students will learn how to deploy & manage a full Red Hat environment with Ceph block storage, & integrate Ceph into other OpenStack service

Question has a verified solution.

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

Introduction This article shows how to use the open source plupload control to upload multiple images. The images are resized on the client side before uploading and the upload is done in chunks. Background I had to provide a way for user…
Wouldn’t it be nice if you could test whether an element is contained in an array by using a Contains method just like the one available on List objects? Wouldn’t it be good if you could write code like this? (CODE) In .NET 3.5, this is possible…
This tutorial will teach you the special effect of super speed similar to the fictional character Wally West aka "The Flash" After Shake : http://www.videocopilot.net/presets/after_shake/ All lightning effects with instructions : http://www.mediaf…
In this video, Percona Solution Engineer Dimitri Vanoverbeke discusses why you want to use at least three nodes in a database cluster. To discuss how Percona Consulting can help with your design and architecture needs for your database and infras…

661 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