views:

740

answers:

2

My code: http://jsbin.com/epuxu

With help from SO, I managed to get addresses geocoded and their according pins placed on the map. The problem is that I can't select the coordinates in order to append a #message div to it on the map because I don't have the coordinates anymore.

I suspect I'm doing something wrong in this section:

/* Message
--------------------*/
$("#message").appendTo(map.getPane(G_MAP_FLOAT_SHADOW_PANE));

    function displayPoint(marker, index){
     $("#message").hide();

     var moveEnd = GEvent.addListener(map, "moveend", function(){
      var markerOffset = map.fromLatLngToDivPixel(marker.getLatLng());
      $("#message")
       .fadeIn()
       .css({ top:markerOffset.y, left:markerOffset.x });

      GEvent.removeListener(moveEnd);
     });
     map.panTo(marker.getLatLng());
    }

it works when I use the original coordinate code (this is commented out on jsbin):

var markers = [
    [39.729308,-121.854087],
    [39.0,-121.0]
    ];

    for (var i = 0; i < markers.length; i++) {
     var point = new GLatLng(markers[i][0], markers[i][1]);
     marker = new GMarker(point);
     map.addOverlay(marker);
     markers[i] = marker;
    }

but I need help getting it to work with this current code:

function showAddress(markers) {
 if (geocoder) {
  geocoder.getLatLng(markers,
   function(point) {
    if (!point) {
     alert(markers + " not found");
    } else {
     marker = new GMarker(point);
     map.addOverlay(marker);
     markers[i] = marker;
    }
   }
  );
 }
}

for (var i = 0; i < markers.length; i++) {
 showAddress(markers[i]);
}

I'm kinda new to utilizing the google maps api, so any insight on what I'm doing wrong would be very helpful. Thanks =]

+1  A: 

I'm not sure what exactly you're looking for. By "#message div", do you mean an info window like this? If so, you could do something among the lines of the following (note the GEvent.addListener() line):

/* Geocoded Addresses
--------------------*/
var markers = [
 ["624 Nord Ave #20, Chico CA"],
 ["200 Nord Ave, Chico CA"],
 ["100 Nord Ave, Chico CA"],
 ["5th and Ivy, Chico CA"]
];

function showAddress(markers) {
 if (geocoder) {
  geocoder.getLatLng(markers,
   function(point) {
    if (!point) {
     alert(markers + " not found");
    } else {
     marker = new GMarker(point);
     GEvent.addListener(marker, 'click', function() {
      marker.openInfoWindowHtml('<strong>Awesome place</strong><br>746 Blah street<br>1337 Awesomeville');
     });
     map.addOverlay(marker);
     markers[i] = marker;
    }
   }
  );
 }
}

for (var i = 0; i < markers.length; i++) {
 showAddress(markers[i]);
}

Try it out, go click a marker! :)

Mathias Bynens
Thank you Mathias for your answer, as it did teach me about adding the info window to individual markers, which is useful to know. My question was unclear, and for that I apologize, but brianpeiris's answer above was what I was looking to accomplish (if you're curious about what I was trying to do in the first place). Thank you for your assistance though.
tester
+4  A: 

Hello again Dancrew32!

I'm afraid there were quite a few things wrong with your code :P

I had to do a bit of plastic surgery but here's the result: http://jsbin.com/atofe

The following is a description of the changes I made. Let me know if you need help understanding anything.


<script type="text/javascript">
  document.write(marker);
</script>

I had to comment this out since it was causing an error. I'm guessing you left it in there by mistake.

<script type="text/javascript">
  // document.write(marker);
</script>


var markers = [
  ["624 Nord Ave #20, Chico CA"],
  ["200 Nord Ave, Chico CA"],
  ["100 Nord Ave, Chico CA"],
  ["5th and Ivy, Chico CA"]
];

Since we are using addresses instead of coordinates, you don't need to (in fact you shouldn't because it only complicates things) encapsulate each string in an array. I also renamed it to addresses to make it more clear and prevent conflicts with the actual markers (more on that later).

var addresses = [
  "624 Nord Ave #20, Chico CA",
  "200 Nord Ave, Chico CA",
  "100 Nord Ave, Chico CA",
  "5th and Ivy, Chico CA"
];


function showAddress(markers) {
  if (geocoder) {
    geocoder.getLatLng(markers,
      function(point) {
        if (!point) {
          alert(markers + " not found");
        } else {
          marker = new GMarker(point);
          map.addOverlay(marker);
          markers[i] = marker;
        }
      }
    );
  }
}

for (var i = 0; i < markers.length; i++) {
  showAddress(markers[i]);
}


/* Add Markers to List
--------------------*/
$(markers).each(function(i,marker){
  $("<li>")
    .html(i+" - "+marker)
    .click(function(){
      displayPoint(marker, i);
    })
    .appendTo("#list");
  GEvent.addListener(marker, "click", function(){
    displayPoint(marker, i);
  });
});

This is where I had to make the most changes. You made a couple of significant mistakes here.

First, you re-used the variable markers when you should have used a new name. In the process you wrote over the array of address strings and misunderstood where things were stored (This is why I renamed the array of address strings to addresses).

Second, you tried to add the markers to the list before the geocoder actually returned its response. I think you didn't realize that getLatLng is an asynchronous function, so it executes the callback function only after the geocoder returns its response. Since you didn't wait for the response, it rendered the "Add markers to list" section useless as the markers had not been retrieved yet.

So, to fix these issues I moved the "Add markers to list" section inside the new handleGeocoderResponse function. This ensures the markers are added to the list only after the geocoder response is returned. I also had to use a double-closure since we are using a loop along with an asynchronous function.

function handleGeocoderResponse(addr, j) {
  /*
    These are closures. We have to return a function
    that contains our Geocoder repsonse handling code
    in order to capture the values of "addr" and "j"
    as they were when they were passed in.  
  */
  return (function(point) {

    if (!point) {
      alert(addr + " not found");
    }
    else {
      var marker = new GMarker(point);
      map.addOverlay(marker);

      /* Add markers to list
      ------------------------*/
      $("<li>")
        .html(j + " - " + addr)
        .click(function(){
          displayPoint(marker, j);
        })
        .appendTo("#list");

      GEvent.addListener(marker, "click", function(){
        displayPoint(marker, j);
      });
    }

  });
}

for (var i = 0; i < addresses.length; i++) {
  if (geocoder) {
    var address = addresses[i];
    geocoder.getLatLng(
      address,
      handleGeocoderResponse(address, i)
    );
  }
}
brianpeiris
Brian, thanks a ton for your detailed explanation. As someone who has never really had professional programming instruction, it is very beneficial to have an expert such as yourself help me learn from my mistakes. So again, thanks!
tester
You're welcome. Explaining things to others helps me learn as well. In fact I had to dive into closures (see the link in my answer) in order to answer your question, it's not an area I deal with too often so I learnt quite a bit myself! Thanks for the quality question :)
brianpeiris
I've been watching that video series this afternoon (cool link). Nested functions do seem to get complicated fast.
tester