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