-3

I dont understand, how could this happen? I only got 1 variable but it seems like it has 2 different values. Please see the output below. Here's the code of the webpage:

<!DOCTYPE html>
<html>
<head>
<script src="http://maps.googleapis.com/maps/api/js"></script>
<script>
    var map;
    var geocoder;
    var center = new google.maps.LatLng(11.17840187,122.59643555);
    var marker = new google.maps.Marker();
    var info = new google.maps.InfoWindow();
    var latitude = 0.00;
    var longitude = 0.00;
    var address = "NO ADDRESS";
    var loaded = false;

    function initialize() {
        var mapProp = {
           center : center,
           zoom : 5,
           mapTypeId : google.maps.MapTypeId.ROADMAP
        };
        map = new google.maps.Map(document.getElementById("googleMap"),mapProp);
        geocoder = new google.maps.Geocoder();
        google.maps.event.addListener(map, "click", function (event) {
            latitude = event.latLng.lat();
            longitude = event.latLng.lng();
            center = new google.maps.LatLng(latitude,longitude);
            displayAddress();
            moveToCenter();
            console.log("Address : " + address)
        });
    }

    google.maps.event.addDomListener(window, 'load', initialize);

    function moveToCenter(){
        map.panTo(center);
        marker.setPosition(center);
        marker.setMap(map);
    }

    function displayAddress(){
        geocoder.geocode( {'latLng': center},
        function(results, status) {
          if(status == google.maps.GeocoderStatus.OK) {
            if(results[0]) {
              address = results[0].formatted_address;
            }
            else {
              address = "";
            }
            info.setContent("<b>" + address + "</b>");
            info.open(map,marker);
          }
        });
    }

    function setWidth(width){
        document.getElementById('googleMap').style.width = width + "px";
        google.maps.event.trigger(map, 'resize');
    }

    function setHeight(height){
        document.getElementById('googleMap').style.height = height + "px";
        google.maps.event.trigger(map, 'resize');
    }
</script>

<style>
    body
    {
        padding : 0; 
        margin  : 0;
        overlow : hidden;
    }
    #googleMap
    {
        width  : 600px;
        height : 600px;
        overlow : hidden;
    }
</style>
</head>
<body>
<div id="googleMap"></div>
</body>
</html>

I have a variable address in my code, but I dont understand why it has two different values. How does this happen? Is it a Javascript Bug?

Here's the output:

enter image description here

Walker
  • 307
  • 4
  • 15
  • 2
    `address = results[0].formatted_address` I'm not sure what you're expecting? And whoever upvoted this, this is not an example of a good question. If you can't see it from a quick scan, this is what debuggers are for... – Zong Apr 15 '16 at 02:49
  • address varialbe is declared globally, and I triggered an onclick event on the map, to display the address in the marker and print its values in the console and it has two different results. – Walker Apr 15 '16 at 02:52
  • @ZongZhengLi, what is the solution for this? – Walker Apr 15 '16 at 02:53
  • Hey! That code is to get the location address in a give latitude ang longitude. – Walker Apr 15 '16 at 02:57
  • @ZongZhengLi, you dont know what your talking about!!!! – The Well Apr 15 '16 at 03:00
  • @TheWell Whereas his comments make sense, you didn’t make any good impression on your understanding of this topic yet. – Sebastian Simon Apr 15 '16 at 03:11

3 Answers3

4

I see what you're asking now. Perhaps we can we rephrase the question.

Q: Why when I set address in displayAddress() does it display the address correctly in the map but still log "No address" in the console?

A: It's because you've introduced an asynchronous process into your code.

You think that the following should happen:

  1. Set address to "No address"
  2. Call displayAddress() which changes the value of address and also displays it on the map
  3. Log the changed address

What's actually happening is this:

  1. Set address to "No address"
  2. Call displayAddress() - the async process geocode starts
  3. Log the address (this hasn't changed)
  4. The async operation completes and the address is displayed on the map.

If you want to know more about async processes and how to return values from them this SO question has lots of relevant information.

Community
  • 1
  • 1
Andy
  • 61,948
  • 13
  • 68
  • 95
2

I think the problem comes from the fact that the code which modifies your address variable is called after the console.log instruction.

As a matter of fact, all of the following code:

if(status == google.maps.GeocoderStatus.OK) {
    if(results[0]) {
        address = results[0].formatted_address;
    }
    else {
        address = "";
    }
    info.setContent("<b>" + address + "</b>");
    info.open(map,marker);
}

is contained in the callback function which is passed to the geocoder.geocode method, and which will then be executed once the remote request has been completed. Which, given the reponse time of the remote request (a few tens or hundreds of miiliseconds), occurs after the execution of the console.log statement.

Vincz777
  • 521
  • 5
  • 12
-3

Take a closer look at your code.

function displayAddress(){
    geocoder.geocode( {'latLng': center},
    function(results, status) {
      if(status == google.maps.GeocoderStatus.OK) {
        if(results[0]) {
          address = results[0].formatted_address; <------ Take a look at this
        }
        else {
          address = "";
        }
        info.setContent("<b>" + address + "</b>");
        info.open(map,marker);
      }
    });
}