0

I am trying to embed a google map with markers in my webpage. But I am getting an undefined alert message if I use the following code

var infowindow = null;
var geocoder;
$(document).ready(function () { initialize();  });

function codeAddress(address) {
    geocoder = new google.maps.Geocoder();
    geocoder.geocode( { 'address': address}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            //alert(results[0].geometry.location);
            return (results[0].geometry.location);
        } 
    });
}

function initialize() {
    default_location = codeAddress("<?php echo $location;?>");
    alert(default_location);
}

Instead of that If i am doing the alert with in the codeAdress function as below it is correctly showing the latitude and longitude.

var infowindow = null;
var geocoder;
$(document).ready(function () { initialize();  });

function codeAddress(address) {
    geocoder = new google.maps.Geocoder();
    geocoder.geocode( { 'address': address}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            alert(results[0].geometry.location);

        } 
    });
}

function initialize() {
    codeAddress("<?php echo $location;?>");
}

Can somebody Identify whats the problem? I am new to javascripts

3 Answers 3

3

The geocoder call is asynchronous, meaning that it takes some time to return and does not follow the sequential order as written. It also means that in the first bit, the function finishes before it gets to your return (results[0].geometry.location) statement. So alert has nothing to display.

Other than inserting statements inside the geocode request, you can write a callback pattern to separate the script logic. The callback, which passes the location as the parameter, executes when the geocode call is successful.

http://jsfiddle.net/3KXKm/

  var infowindow = null;
  var geocoder = new google.maps.Geocoder();

  $(document).ready(function () { initialize();  });

  function codeAddress(address, callback) {
    geocoder.geocode( { 'address': address}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        callback(results[0].geometry.location);
      } 
    });
  }

  function initialize() {
    codeAddress("Chicago, IL", function(default_location) {
      var map = new google.maps.Map(document.getElementById("map_canvas"),
        { center: default_location,
        zoom: 3, mapTypeId: google.maps.MapTypeId.ROADMAP });

      locations = ["Los Angeles", "Davis", "Truth or Consequences",
        "Ann Arbor", "Massachusetts"];

      for (var i = 0; i < locations.length; i++) {
        codeAddress(locations[i], function(latLng) {
          new google.maps.Marker({map:map, position:latLng});
        });
      }
    });
  }
Sign up to request clarification or add additional context in comments.

5 Comments

@ heitor Chang : i want to show a map of my users. The problem is that they are saving the locations as human readable addresses. I am using the source of this page @ you.arenot.me/map.html for my script. can you help me, particularly to get the location for the sites variable?
See the updated answer. For a list of locations, the codeAddress function can place a marker. You can do anything with the latLng the function returns.
@user632347 I forgot to warn you, the geocoder sometimes won't work as expected, for example with a generic address like "300 Third Street" without a city name and state. If you are dealing with US cities with state names it should be OK. If you are dealing in a single city, you can do some checking if the user entered the city, if not, add it in the code, for example. Going from LatLng to address is easy, the other way can be tricky.
@ heitor Chang: Thanks for the information. But now I am getting the same title for all the markers. Here is the code I am trying. I tried it for last 2hours with no progress. Can you help on this too? Please see this jsfiddle.net/3KXKm/1
I was copying this answer for my answer and saw your comment. It's the old function-in-a-loop gotcha, just needs to be wrapped in (function(i){...})(i); Try the update. jsfiddle.net/3KXKm/2
0

geocode does not return the result instantly. This is why you get nothing in the first version of your code. So if you want to do something with the geocode result you should do it in the callback function like in the second version of your code.

Comments

0

Your

return (results[0].geography.location);

Only return the value of the nested function, not that of codeAddress function. Maybe if hou tell us what you're trying to do we can help.

1 Comment

I need to get the latitude and longitude of the user. Because my users save their locations as human readable. I need to convert it to lat and long to show them as markers

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.