VB.NET - I want to calculate distance between two area.user enter zipcode in textboxes.

Asked By Ranjan on 28-Jun-12 01:42 AM
Earn up to 40 extra points for answering this tough question.
 my code is:

        Dim z1 As Integer
        Dim z2 As Integer


        z1 = TextBox1.Text
        z2 = TextBox2.Text

        'If (z1 == DBNull.Value||z2==null) then

       '     Throw New ArgumentException
        ' End If


        Dim earthradius As Double = 3956.0871071030492
        Dim latitude1radians As Double = (z1.latitude / 180) * Math.PI
        Dim longitude1radians As Double = (z1.longitude / 180) * Math.PI
        Dim latitude2radians As Double = (z2.latitude / 180) * Math.PI
        Dim longitude2radians As Double = (z2.longitude / 180) * Math.PI


        Dim distance As Double =
              (earthradius * 2) *
               Math.Asin(
                   Math.Sqrt(
                      Math.Pow(
                        Math.Sin((latitude1radians - latitude2radians) /
     2), 2) + Math.Cos(latitude1radians) * Math.Cos(latitude2radians) *
                           Math.Pow(Math.Sin((longitude1radians -
     longitude2radians) / 2), 2)))
        Return

show error in z1.latitude(latitude is not member of integer.)



[)ia6l0 iii replied to Ranjan on 28-Jun-12 12:18 PM
Yes.  That's right. The latitude is not a member of integer.  Integer are whole numbers only.  Type cast Z1 to appropriate object that holds the latitude property
Vikram Singh Saini replied to Ranjan on 29-Jun-12 05:57 AM
Hi,

I searched google lot and finally found the solution for same.

********** FIND DISTANCE BETWEEN TWO AREA VIA ZIP CODES **********

We have created a demo window application with two textboxes for accepting zipcodes. And on basis of those zip code values we are picking latitude and longitude from database. And then calculating distance between them.



The database file I have used for the demo application can be downloaded from http://federalgovernmentzipcodes.us/. The database is in .csv format. I opened it in Excel and saved it as .xlsx. Imported the .xlsx in Access database & saved in table named zipcodes. There are two sized database(s). I downloaded one with 4.2 MB size.

We have created custom class ZipCode (class idea picked up from http://www.techrepublic.com/blog/programming-and-development/how-do-i-determine-the-distance-between-zip-codes-using-c/634 and modified by me for getting data from database. And then storing that data in List type. The original code is picking data from xml file.) as shown below:

using System;
using System.Collections.Generic;
using System.Data.OleDb;
using System.Configuration;
using System.Data;
 
namespace ZipDistancer
{
  public class ZipCode
  {
    private string _code;
    private string _state;
    private double _latitude;
    private double _longitude;
 
    public string Code
    {
      get { return _code; }
      set { _code = value; }
    }
 
    public string State
    {
      get { return _state; }
      set { _state = value; }
    }
 
    public double Longitude
    {
      get { return _longitude; }
      set { _longitude = value; }
    }
 
    public double Latitude
    {
      get { return _latitude; }
      set { _latitude = value; }
    }
 
    #region Static methods/variables
    private static List<ZipCode> _codeList;
 
    public static List<ZipCode> CodeList
    {
      get { return _codeList; }
      set { _codeList = value; }
    }
 
    public static void LoadData()
    {
      using (OleDbConnection con = new OleDbConnection(ConfigurationManager.ConnectionStrings["ZipCon"].ConnectionString))
      {
        string query = "SELECT ZipCode, State, Latitude, Longitude FROM zipcodes";
 
        using (OleDbCommand cmd = new OleDbCommand(query, con))
        {
          con.Open();
          using (OleDbDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection))
          {
            DataTable dt = reader.GetSchemaTable();
            _codeList = new List<ZipCode>();
            string latitude, longitude;
 
            while (reader.Read())
            {
              ZipCode code = new ZipCode();
              code._code = reader[0].ToString();
              code._state = reader[1].ToString();
 
              latitude = reader[2].ToString(); longitude = reader[3].ToString();
              if (!String.IsNullOrEmpty(latitude) && !String.IsNullOrEmpty(longitude))
              {
                code.Latitude = Convert.ToDouble(latitude);
                code.Longitude = Convert.ToDouble(longitude);
              }
 
              _codeList.Add(code);
            }
            reader.Close();
 
          }
 
          con.Close();
        }
      }
    }
 
    public static double Distance(string zipCode1,
                    string zipCode2)
    {
      ZipCode z1 = _codeList.Find(
              delegate(ZipCode z)
              {
                return z.Code == zipCode1;
              });
 
      ZipCode z2 = _codeList.Find(
              delegate(ZipCode z)
              {
                return z.Code == zipCode2;
              });
 
      if (z1 == null || z2 == null)
        throw new ArgumentException
          ("One of the codes does not exist.");
 
      double earthsRadius = 3956.087107103049;
 
      double latitude1Radians =
        (z1.Latitude / 180) * Math.PI;
 
      double longitude1Radians =
        (z1.Longitude / 180) * Math.PI;
 
      double latitude2Radians =
        (z2.Latitude / 180) * Math.PI;
 
      double longitude2Radians =
        (z2.Longitude / 180) * Math.PI;
 
      double distance =
        (earthsRadius * 2) *
        Math.Asin(
         Math.Sqrt(
          Math.Pow(
           Math.Sin((latitude1Radians -
               latitude2Radians) / 2), 2) +
          Math.Cos(latitude1Radians) *
          Math.Cos(latitude2Radians) *
          Math.Pow(
           Math.Sin((longitude1Radians -
               longitude2Radians) / 2), 2)
         )
        );
 
      return distance;
    }
    #endregion
  }
}

And we have called the ZipCode class from btnCalculate_Click as:

if (!String.IsNullOrEmpty(txtFromZip.Text) && (!String.IsNullOrEmpty(txtToZip.Text)))
      {
        ZipDistancer.ZipCode.LoadData();
        lblResult.Text = "Distance is: " + Convert.ToString(ZipDistancer.ZipCode.Distance(txtFromZip.Text, txtToZip.Text));
      }

And here is the zip file of entire project. DistanceCalculator.zip


In last as you can notice z1.Latitude and z2.Longitude are the public properties of the ZipCode class instance. Hope this helps. Let us know the action result.
Super Man replied to Ranjan on 29-Jun-12 02:50 PM
Just fetch longitude an latitude from DB or make use of any third party web service which provides those values based on zip code.

    // get all these four values from any source

        Dim z1_latitudeAs Double =    //Store latitude of Zip 1
        Dim z1_longitudeAs Double =  //Store longitude of Zip 1
        Dim z2_latitudeAs Double =   //Store latitiude of Zip 2
        Dim z2_longitudeAs Double =   //Store longitude of Zip 1


        Dim latitude1radians As Double = (z1_latitudeAs/ 180) * Math.PI
        Dim longitude1radians As Double = (z1_longitude / 180) * Math.PI
        Dim latitude2radians As Double = ( z2_latitudeAs / 180) * Math.PI
        Dim longitude2radians As Double = (z2_longitudeAs / 180) * Math.PI
help
Server 28-Oct-12 08:22 PM Hi I am using this SP to get zipcode within a radious here is the sp: CREATE Procedure sp_ZipCode_Range / * Returns zip codes within specified range. * / ( @ZipCode int = Null, @Miles Float ) As set nocount on Declare @Latitude Float(10) Declare Longitude Float(10) - - Lookup longitude, latitude for zip codes Select @Latitude = Latitude , @Longitude = Longitude From zipcode Where Zip = @ZipCode Select Zip, Zip_Name From zipcode Where Longitude Is
23 PM how can i find the distance within a certain radius of a given zipcode / . ? The data that i have has the the Longitude and Latitude. . . . . . can i use this to measure the distance within a given radius ?? and how. also procedure is used to calc miles distance from - - two points on earth. You can get latitude and longitude for places on - - earth, then just use this procedure to calc how many miles are output ) As Begin / * ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** / / * Routine to calc miles distance from two points on earth * / / * specified in latitude / longitude pairs.* / / * Inputs are "degrees.minutes" ie: 33.0654 * / / * ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** / set nocount on declare @Lat1 decimal(28 73.996119, 41.768420, -73.960450 / * SELECT miles = @miles = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = CREATE TABLE places ( statecode char(2), zipcode char(5), lat float, long float ) insert into places select 'AL', '35085' , 32.965120 , -86
In my asp.net application I was using Geocode to find latitude and longitude for given address and was saving these in database. Its very strange that, its was which it was working but now for that also its returning zero as logitude and latitude. Please let me know how to fix this problem Here is the code i am using, which was working before, I have not changed anything public decimal Longitude { get { return _longitude ; } set { this . _longitude = value ; } } #endregion } public class Geocode { private const string _googleUri example> / / / 3276 Westchester Ave, Bronx, NY 10461 / / / / / / or / / / / / / New York, NY / / / / / / or / / / / / / 10461 (just a zipcode) / / / < / example> / / / < / remarks> / / / < / param> / / / <returns> A spatial coordinate that contains the latitude and longitude of the address.< / returns> public static Coordinate GetCoordinates ( string address ) { WebClient client = new WebClient (); Uri
cmd = new SqlCommand(); cmd.Connection = sqlCnn; cmd.CommandType = CommandType.Text; string frontCmdText = "INSERT INTO ZIPS (ZipCode, Latitude, " + "Longitude, City, State, StateCD) VALUES ( \ '"; sqlCnn.Open(); string cmdText = ""; / / Have to run in debug mode in sqlCmd = new SqlCommand(); sqlCmd.Connection = sqlCnn; sqlCmd.CommandType = CommandType.Text; string frontCmdText = "INSERT INTO ZIPS (ZipCode, Latitude, " + "Longitude, City, State, StateCD) VALUES ( \ '"; string sqlCmdText = ""; / / Have to run in debug mode in order to sqlCmd = new SqlCommand(); sqlCmd.Connection = sqlCnn; sqlCmd.CommandType = CommandType.Text; string frontCmdText = "INSERT INTO ZIPS_TEST (ZipCode, Latitude, " + "Longitude, City, State, StateCD) VALUES ( \ '"; string sqlCmdText = ""; / / Have to run in debug mode in order
I need to be able to provide a proximity search by zip code 1) Database (1) Acos (1) Sin (1) Cos (1) FTP (1) Tina, You need a zipcode table with longitude and Latitude Info about every zipcode and this info actually is available. then you need to calculate using the Longitude and Latitude, I contacted JPL in Pasadena one time and they actually referred me to some formulas even bother checking with the US Postal Service. They don't maintain a zip to latitude / longitude database. There are a number of companies that do sell them, and then there
PM I have a table that stores storelocations and their geographic info: I also have : zipCode, Lattitude, Longitude, X, Y, Z 00210 43.005895, -71, 013202 0.237923301587627 -0.691497000835541 0.682073603357508 If y, z. Thanks for your help. the distance between 2 zip codes based on the latitude and longitude coordinates. I once used one in a zip code component I wrote. However, the X if you would like to treat everybody to one converted into SQL. . . keywords: SQL Server, latitude and longitude coordinates, geographic info, zip code description: getting geographic information and locations I have a table that stores storelocations and their geographic info: I also have : zipCode, Lattitude, L
Remote Scripting.Net (AJAX, NOT!) Zipcode UserControl with MSN Virtual Earth Map by Peter A. Bromberg, Ph.D. Peter Bromberg Ah will query a database of US zipcodes when you enter any valid US 5 digit zipcode, and perform an out - of - band Remote Scripting callback to the database and update the with the City, State, County, State and County US Gov't "FIPS" codes, and the Latitude and Longitude. But Wait! If you call in the the next 10 minutes, we'll even use RegisterStartupScript( "ctrlId" , "<script> var ctrlId = '" + this .ClientID + "_';< / script> " ); } [RemoteScripting.Method] public DataTable PopulateZipData( string zipCode) { SqlConnection cn = new SqlConnection(System.Configuration.ConfigurationSettings.AppSettings[ "connString" ].ToString()); SqlCommand cmd = new SqlCommand( "dbo.usp_GetZipCodeData" , cn); cmd.CommandType = CommandType.StoredProcedure ; SqlParameter p = new SqlParameter( "@Zipcode" , this .txtZip.Text); cmd.Parameters.Add(p); SqlDataAdapter da = new SqlDataAdapter(cmd); DataSet ds = new by the ASP.NET Web Form Designer. / / InitializeComponent(); base .OnInit(e); RemoteScripting.Manager.Register( this , "ZipCode.Control" , RemoteScripting.Debug.None); } / / / <summary> / / / Required method for Designer support - do not modify / / / the contents
way to perform the reverse geocoding process (to know the street address based on a Latitude Longitude Point). the easiest way is to use the Haversine algorithm to measure the distance of the information of the streets of overall nation with the format: ID(Int), NAME(Char), LATITUDE(Float), LONGITUDE(Float), PARENTID(Int) Now you can check the register with the lowest distance to the 000.000 distances and then Order by Distance!!!. Something like: SELECT TOP 1 ID, Name, Latitude, Longitude, dbo.Haversine(4.7131725, -74.057433, dbo.RevGeo.Latitude, dbo.RevGeo.Longitude)as Distance FROM RevGeo Order by Distance This operation takes around 3 seconds in a
turn by turn. I am exporting the records from access by sorting them by either longitude, latitude (which sometimes gives me addresses spanning the breadth of the city) or latitude, longitude (which usually gives me addresses in a linear fashion). Sometimes there are several addresses on sort of order. Thanks!!! Access Queries Discussions DeLorme (1) Brewer (1) Neighborhoods (1) Thousands (1) Longitude (1) Carriers (1) Hundreds (1) Latitude (1) What does your record layout look like? What datatype do you use for Lat Long? - - Message posted via http: / / www.accessmonster.com I do not follow as longitude and latitude signify a single point. Are your street addresses loaded as cross streets against the longitude