Sam Leicester
Sam Leicester

Reputation: 109

Geocoding using Google Maps API v3 - Linking the original request to the response

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
}

Upvotes: 0

Views: 789

Answers (2)

Sam Leicester
Sam Leicester

Reputation: 109

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
  });
}

Upvotes: 1

geocodezip
geocodezip

Reputation: 161334

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.

Upvotes: 1

Related Questions