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

  • SEARCH
  • Home
  • 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 8800845
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 14, 20262026-06-14T00:41:49+00:00 2026-06-14T00:41:49+00:00

I’m trying to give a global variable a value after some code is processed.

  • 0

I’m trying to give a global variable a value after some code is processed. It’s not working as planned.

What I do is enter an address and city in two textboxes. It goes into the last function and calls codeAddress which gets the coordinates of the address.

From there i send the coordinates to setLatLng and it works fine. But i can’t call longlats using the getLatLng to see the set value.

It’ll only show a value if I add an address and city two times. I’m thinking the longlats are being initialized too late that I don’t see the correct value in time.

Any advice?

Relevant code is below.

<script>
var longlats ="";

function setLatLng(x,y){
    longlats = x+","+y;
    alert(longlats) //shows value
}

function getLatLng(){
    alert(longlats);
    return longlats;
    //calling this gives undefined
}

function codeAddress() {

$('#map').show();
var geocoder = new google.maps.Geocoder();
var address = document.getElementById("address").value +"," + document.getElementById("city").value;

geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
    var lat = results[0].geometry.location.lat();
    var lng = results[0].geometry.location.lng();
    locationsall[counter] = new Array();
    locationsall[counter][0] = address;
    locationsall[counter][1] = lat; //has value
    locationsall[counter][2] = lng; //has value
    setLatLng(locationsall[counter][1],locationsall[counter][2]);

counter++;

} 

$(function() {
$("#locationadd").click(function() {
   codeAddress();
   var get = getLatLng();//value is undefined..
  //i want to do stuff with the values in longlats
}
)};

</script>

Edit1

 $("#locationadd").click(function() {
var address = $("#address").val();
var city = $("#city").val();

if (address =="" || city =="") {
    $("#locationtext").text('*Please enter an address and city');
    return false;
} 
else {
    codeAddress(function(){
    var get = getLatLng();
    var longlat = get.split(",");
    var lat = longlat[0];
    var lng = longlat[1];

    var $tr2 = $('<tr>').css({
            'padding': '4px',
            'background-color': '#ddd'
    }).appendTo('#locationDeals');

    var location = [
            address,
            city
    ];
    locations.push(location);

    for (i = 0; i < 2; i++) {
        var $td2 = $('<td>').appendTo($tr2);
        $('<span>').text(location[i]).appendTo($td2);
        $('<input type="hidden">').attr({
            'name': 'loc[' + ctr + '][' + i + ']',
            'value': location[i]
        }).appendTo($td2);
    }
    var $tdRemoveRow2 = $('<td>').appendTo($tr2);
    $('<a>').attr({
        'href': '#',
        'id': 'submit-button'
    }).text("Remove").click(function() {
    var index2 = $tr2.index();
    $("#locationDeals input[type='hidden']").each(function() {
        this.name = this.name.replace(/\[(\d+)\]/, function(str2, number2) {
          return "[" + (+number2 > index2 - 1 ? number2 - 1 : number2) + "]";
        });
    });

    $tr2.remove();
    var tmp = locations.splice(locations.indexOf(location), 1);
    deleteMarker(tmp);
    return false;
    }).appendTo($tdRemoveRow2);

    ctr++;
    document.getElementById("address").value = "";
    document.getElementById("city").value = "";
    document.getElementById("address").focus();
    $("#locationtext").text('');

    return false;
    });
    } 
});
  • 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-14T00:41:50+00:00Added an answer on June 14, 2026 at 12:41 am

    The problem is geocoder.geocode is asynchronous. You can’t do it the way you do because your codeAddress function will return before longlats is set. You need to change your coding style to use longlats only after google maps have returned the result.

    You need to change your code from this:

    $("#locationadd").click(function() {
       codeAddress();
       var get = getLatLng();//value is undefined..
      //i want to do stuff with the values in longlats
    }
    

    To this:

    $("#locationadd").click(function() {
       codeAddress(function(){
         var get = getLatLng();
         //do stuff with the values in longlats
       });
    });
    

    In order to do that, you need to change copyAddress to:

    function codeAddress(callback) {
    
      /*
       * Some stuff
       */
    
      geocoder.geocode( { 'address': address}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
          /*
           * Some stuff
           */
    
          setLatLng(locationsall[counter][1],locationsall[counter][2]);
    
          callback(); // This is where/when the values are returned
                      // so this is where/when we want to execute code.  
        } 
      })
    }
    

    Additional explanation:

    From your comments, it appears that you’re still trying to do this:

    var val;
    codeAddress(function(){
        val = getLatLng();
    });
    doStuffWith(val);
    

    This won’t work because codeAddress returns BEFORE getLatLng executes. You need to change the style of your coding. You need to write it like this:

    codeAddress(function(){
        val = getLatLng();
        doStuffWith(val);
    });
    

    That is, you need to move all code that you would have written after the call to codeAddress to the function INSIDE codeAddress.

    The reason for it is that the way the code executes is something like this:

    • BROWSER ENTERS JAVASCRIPT PHASE:

         codeAddress is called
                |
                |
                |--------------> inside codeAddress a request to google maps
                |                is made which registers a callback function
                |                to be executed once it returns.
                v
         codeAddress returns
         note that at this point getLatLng isn't called yet
         this is because the browser haven't made the request
         to google maps yet because it's still executing the
         javascript engine.
                |
                v
         code written after codeAddress is executed
         (remember, the call to google maps still haven't happened yet)
                |
                v
         no more javascript to execute
      
    • javascript phase ends, BROWSER ENTERS DOM RENDERING PHASE

         The DOM gets updated and drawn on screen if there are any changes.
      
    • DOM rendering ends, BROWSER ENTERS NETWORK PHASE

         (note: in reality the network layer is asynchronous)
      
         Browser executes pending requests (images, iframes, XMLHttprequest etc.)
         Makes the necessary network connections and begins downloading stuff.
                |
                |
                v
         Browser services completed requests and schedules appropriate events
         (update DOM, trigger onreadystatechange etc.)
         Note that at this point no javascript or DOM updates actually happens.
         The browser does things in a loop, not recursively.
         It is at this point that the google maps request is made.
                |
                v
         No more network operations to service
      
    • network phase ends, BROWSER ENTERS JAVASCRIPT PHASE

         google maps request completes, onreadystatechange executes
                |
                |
                |----> inside onreadystatechange the callback to the
                |      google maps API is called
                |             |
                |             '-----> inside the google maps callback getLatLng
                |                     is called, then the callback to codeAddress
                |                     is called.
                |                          |
                |                          '------> inside the callback to
                |                                   codeAddress you can now
                |                                   use the returned values.
                |                                   This is the reason you need
                |                                   to move all your code here.
                v
         no more javascript to execute
      
    • javascript phase ends, BROWSER ENTERS DOM RENDERING PHASE

    and the event loop continues.

    As you can see, you can’t simply return the values from codeAddress. Instead you need to move your code inside codeAddress to have it executed at the right time.

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

Sidebar

Related Questions

For some reason, after submitting a string like this Jack’s Spindle from a text
I am trying to understand how to use SyndicationItem to display feed which is
Basically, what I'm trying to create is a page of div tags, each has
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
link Im having trouble converting the html entites into html characters, (&# 8217;) i
I have just tried to save a simple *.rtf file with some websites and
I am trying to render a haml file in a javascript response like so:
I have this code to decode numeric html entities to the UTF8 equivalent character.
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
I have this code: - (void)parser:(NSXMLParser *)parser foundCDATA:(NSData *)CDATABlock { NSString *someString = [[NSString

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.