0

I have a list of schools that I want to plot on a Google Map. I'm using Google's Geocoding Service to lookup the lng/lat for a given postcode, upon successfully retrieving this information I want to drop a marker, together with adding the appropriate event listener that opens an infobox when a given marker is clicked.

When I make a request to the geocoder it's in the context of a school, when I receive a callback I lose this context. You'll see from code below that I've come up with a clunky solution to this, although it fails occasionally when the geocoder results truncate the postcode.

Should I be using something like jQuery's Deferred Object to solve this issue?

var geocoder;
var map;
var infowindow
var iterator = 0;
geosearch = new Array();

function drop() {
  for (var i = 0; i < schools.length; i++) {
    setTimeout(function() { // delay added to prevent being throttled
      addMarker();
      iterator++;
    }, i * 1000);
  }
}

function addMarker() {
  address = schools[iterator].addresses[0].address.zip;
  geosearch[address] = schools[iterator]; // this is how I'm keeping track of initial request

  geocoder.geocode( { 'address': address }, function(results, status) {
    var school = geosearch[results[0].address_components[0].short_name]; // loading the school associated with the initial request, which only works if the postcode completely matches up - clunky!

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

      // each school has tags, I want to set a marker if certain tags exist
      if ($.inArray('D', school.tags) > 0) {
        var image = 'map_markers/brown_MarkerD.png';
      } else if ($.inArray('C', school.tags) > 0) {
        var image = 'map_markers/red_MarkerC.png';
      } else if ($.inArray('B', school.tags) > 0) {
        var image = 'map_markers/yellow_MarkerB.png';
      } else if ($.inArray('A', school.tags) > 0) {
        var image = 'map_markers/green_MarkerA.png';
      } else {
        var image = 'map_markers/blue_MarkerZ.png';
      }

      // add the marker to the map, using result
      var marker = new google.maps.Marker({
          map: map,
          position: results[0].geometry.location,
          draggable: false,
          icon: image,
          shadow: 'http://www.google.com/mapfiles/arrowshadow.png',
          animation: google.maps.Animation.DROP
      });

      // adds listening on marker so that popup box appears when clicked
      google.maps.event.addListener(marker, 'click', (function(marker, school) {
        return function() {
          infowindow.setContent(
            '<a href="https://vitalcpd.highrisehq.com/companies/'+school.id+'" target="_blank">'+school.name+'</a>'
            +'<address>'
            +school.addresses[0].address.street+'<br />'
            +school.addresses[0].address.city+'<br />'
            +school.addresses[0].address.state+'<br />'
            +school.addresses[0].address.zip+'<br />'
            +school.addresses[0].address.country+'<br />'
            +'</address>');
          infowindow.open(map, marker);
        }
      })(marker, school));

    } else {
      console.log("* NOT found: " + status);
    }
  });
}

function initialise() {
  geocoder = new google.maps.Geocoder();
  infowindow = new google.maps.InfoWindow();
  var latlng = new google.maps.LatLng(54.82659788452641,-3.417279296874991);
  var mapOptions = {
    zoom: 6,
    center: latlng,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  }
  map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);

  drop(); // loops through schools to add marker
}
Sam Leicester
  • 109
  • 10

2 Answers2

1

I would suggest geocoding the addresses offline and storing the coordinates in your database (or wherever you are storing the addresses). Then use the coordinates to display the markers.

I would also suggest reviewing this article on geocoding strategies from the documentation

To answer your question, I would suggest using javascript function closures to associate the address with the callback function.

geocodezip
  • 158,664
  • 13
  • 220
  • 245
  • Thanks for your answer. I agree that caching the coordinates would be more sensible. At the moment I'm more concerned in relating the callback response to the school I used to originate the geocode request. I know that this has something to do with scope/closures and am a stuck specifically on this. I was wondering whether the jQuery Deferred is a framework that organises this scope? The solution must be something generic for non-blocking requests that provide a callback. – Sam Leicester Jul 24 '12 at 08:22
  • A function closure (a geocodeAddress function that takes the address and any other required information and holds them in a function closure) is the solution I have used in the past and suggested to others to solve this problem. jQuery Deferred doesn't seem like it will help (unless it does so by really slowing down the geocoding process), but I don't know anything about it. – geocodezip Jul 24 '12 at 12:24
  • I didn't actually need to use a closure, it was actually simpler than this as I've detailed in my answer. – Sam Leicester Jul 26 '12 at 14:52
1

The problem I was experiencing here was just a questions of scope, and in particular the way that I was referencing the school within the addMarker() function. Rather than referencing the school within the schools array using the global iterator variable, I instead pass in this school, this way the correct school is always referenced on the callback that is created within this scope.

var geocoder;
var map;
var infowindow
var iterator = 0;

function drop() {
  for (var i = 0; i < schools.length; i++) {
    setTimeout(function() {
      addMarker(schools[iterator]); // pass in the school as an argument
      iterator++;
      $('#current_school').text(iterator); // taken this out of addMarker()
    }, i * 1000);
  }
}

function addMarker(school) {
  geocoder.geocode( { 'address': school.addresses[0].address.zip }, function(results, status) {
    ... // the inners from here remain the same
  });
}
Sam Leicester
  • 109
  • 10