0

I've been trying to geocode an address into LatLng coordinates, but I'm having a lot of difficulty doing so. I know geocode() is an asynchronous function, and I have been toying with callbacks with no avail. I've been looking at other posts like this one (How to return value from an asynchronous callback function?), but I'm having difficulty understanding the concept. If anyone can show me how to properly do that callback function, will be much appreciated. Lot of headache over this one. Was able to get the callback to do an alert() that gives the correct LatLng, but not set the position parameter. Sorry couldn't figure it out from the example cited earlier. Pretty new to the language. Any references you can point me to to understand the concept are greatly appreciated as well. Thanks!

  var location;
  var image;
  var map;
  var geocoder;
  var address;

  function initialize() {
    var mapOptions = {
      center: new google.maps.LatLng(42.763146, -73.3776),
      zoom: 6,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    var map = new google.maps.Map(document.getElementById("map_canvas"),
        mapOptions);
    var cloudLayer = new google.maps.weather.CloudLayer();
    cloudLayer.setMap(map);

    addressSet(function(address) {
        console.log(address);
        // tried to set location = address;, location = new google.maps.LatLng(address);
        // neither works
    });

    addMtsToMap(location,
                map,
                new google.maps.MarkerImage("img/mts/skier.png", null, null, null, new google.maps.Size(50,50)));

  }

  function addMtsToMap(location, map, image) {

    var marker = new google.maps.Marker({
        position: location,
        map: map,
        icon: image
    });

    var infoWindow = new google.maps.InfoWindow({content: "<h1>Powder!!!</h1>"});

    google.maps.event.addListener(marker, "click", function() {
        infoWindow.open(map, marker);
    });
  }

  function addressSet(callback) {

    geocoder = new google.maps.Geocoder();

    geocoder.geocode({address: "Killington+VT"}, function(results, status) {

        if (status == google.maps.GeocoderStatus.OK) {

            address = results[0].geometry.location;
            callback(address);
        }
    });
  }
Community
  • 1
  • 1
cgood
  • 165
  • 1
  • 1
  • 16

1 Answers1

0

Sorry all. Couldn't believe what I found after messing with this for so long. I declared var map again in initialize, which made my addressSet() function pull the incorrect global map variable. Deleting the var made it work.

cgood
  • 165
  • 1
  • 1
  • 16