Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7730113
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 1, 20262026-06-01T06:08:28+00:00 2026-06-01T06:08:28+00:00

I am trying to find the distance between 2 points, one being from user

  • 0

I am trying to find the distance between 2 points, one being from user input and the other an address from my database. I have put together the code below, which seems to work (I have test variables in place so no database pulls are being made for testing), however I have hit a wall; I cannot figure out why I need to click the button twice for the output to show?

Any help is much appreciated

CODE BELOW:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml">
  <head>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
    <title>Google Maps JavaScript API Example: Extraction of Geocoding Data</title>
    <script src="http://maps.google.com/maps?file=api&v=2&key=ABQIAAAA7j_Q-rshuWkc8HyFI4V2HxQYPm-xtd00hTQOC0OXpAMO40FHAxT29dNBGfxqMPq5zwdeiDSHEPL89A" type="text/javascript"></script>
<!-- According to the Google Maps API Terms of Service you are required display a Google map when using the Google Maps API. see: http://code.google.com/apis/maps/terms.html -->
    <script type="text/javascript">

 //var globalAddr = new Array();
 var globalName;
 var xmlhttp;
 var geocoder, location1, location2;
 var distanceVal;

    function initialize() {
        geocoder = new GClientGeocoder();
    }

        function showLocation() {
        geocoder.getLocations(document.getElementById("address1").value, function (response) {
            if (!response || response.Status.code != 200)
            {
                alert("Sorry, we were unable to geocode the first address");
            }
            else
            {
                location1 = {lat: response.Placemark[0].Point.coordinates[1], lon: response.Placemark[0].Point.coordinates[0], address: response.Placemark[0].address};
                geocoder.getLocations(document.getElementById("address2").value, function (response) {
                    if (!response || response.Status.code != 200)
                    {
                        alert("Sorry, we were unable to geocode the second address");
                    }
                    else
                    {
                        location2 = {lat: response.Placemark[0].Point.coordinates[1], lon: response.Placemark[0].Point.coordinates[0], address: response.Placemark[0].address};
                        calculateDistance();
                    }
                });
            }
        });
    }

    function calculateDistance()
    {

            var glatlng1 = new GLatLng(location1.lat, location1.lon);
            var glatlng2 = new GLatLng(location2.lat, location2.lon);
            var miledistance = glatlng1.distanceFrom(glatlng2, 3959).toFixed(1);
            var kmdistance = (miledistance * 1.609344).toFixed(1);

            distanceVal = miledistance;
    }

 function loadXMLDoc(url,cfunc)
 {
        if (window.XMLHttpRequest)
          {// code for IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp=new XMLHttpRequest();
          }
        else
        {// code for IE6, IE5
            xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
        }
        xmlhttp.onreadystatechange=cfunc;
        xmlhttp.open("GET",url,true);
        xmlhttp.send();
 }
 function getData(str)
        {
        loadXMLDoc("getData.php?address="+str,function()
            {
                if (xmlhttp.readyState==4 && xmlhttp.status==200)
                {
                    var x = xmlhttp.responseText;
                    var dnames = x.split("~~~");
                    var daddr = x.split("^^^");
                    daddr.shift();
                    dnames.pop();

                    var testArray = new Array('85281','18657','90210');

                    var shortest = 999999;

                    for(var i = 0; i <= testArray.length-1; i++)
                    {

                        document.getElementById("address2").value = testArray[i];//daddr[i];
                        showLocation();

                        //i get a blank alert 3 times here the first time, then I get the a value the 2nd time.. makes no sense!
                        alert(distanceVal);

                        if (shortest > distanceVal)
                        {
                            shortest = distanceVal;
                            globalName = dnames[i];
                        }

                    }

                    document.getElementById("results").innerHTML = globalName + " " + shortest;

                }
            })
        }

    </script>
  </head>

  <body onload="initialize()">

    <form>
      <p>
        <input type="text" id="address1" name="address1" class="address_input" size="40" />
        <input type="hidden" id="address2" name="address2" />
        <input type="hidden" id="distance" name="distance" />
        <input type="button" name="find" value="Search" onclick="getData(document.getElementsByName('address1')[0].value)"/>
      </p>
    </form>
    <p id="results"></p>

  </body>
</html>
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-01T06:08:29+00:00Added an answer on June 1, 2026 at 6:08 am

    When you call showLocation() in your getData() callback, that sets off two geocoder calls and if both are successful calls calculateDistance().

    However, both those geocoder calls take time. The first getLocations() sets off a geocode request and lets it continue, to be dealt with in its callback. Within that function, there’s another request which is dealt with in its own callback.

    While those are waiting for results, the code execution has carried on and reached alert(distanceVal) even though calculateDistance() hasn’t been called yet. Consequently distanceVal isn’t set yet.

    When you click the button again, the global distanceVal will have been populated through all the callback functions, so (even though the second set of geocodes/callbacks have not completed), it will have a value to display. However, if you change the values you are testing, you will find it’s displaying the old value which is now incorrect.

    Everything which depends on values found in a callback function must be processed within that callback function. If you move the display of data into calculateDistance() everything will be fine, because the data is available to that function.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Trying to work out distance between two points (lat & lng) I have an
I am trying to find the distance between two longitude and latitude points. I
I'm trying to find the distance between two points (for which I've latitudes &
i'm trying to use the GeoKit plugin to calculate the distance between 2 points.
For a website where a user enters his address, I'm trying to find the
Trying to find the sqlserver adapter for rails on windows. I have tried getting
Trying to find a way to send a POST HTTPS request from Python to
I have a matrix having around 1000 geospatial points(Longitude, Latitude) and i am trying
I am trying to extract numbers from a typical scoreboard that you would find
I need a basic function to find the shortest distance between a point and

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.