I have a function that creates Google maps markers. I pass in data from a database query. Then I have the function perform another database query using one value as the foreign key. I am trying then to put all the results (the data from the first query and the data from the second query) into a string, which the marker will display in an infoWindow.
But somehow, the program views the string as “undefined” unless I build it outside of the $.post function for the second query. What’s going on? Shouldn’t the program be able to read that string?
Here is my code:
function createMarker(marker_id, point,street, neighborhood, date,map) {
// Create the HTML text based on the values passed in from XML
$.post('get_victimdata.php', {marker_id:marker_id},
function(victimdata){
objVictimdata = jQuery.parseJSON(victimdata);
markerhtml = "";
markerhtml += "<strong>Street: </strong>" + street + "<br>";
markerhtml += "<strong>Neighborhood: </strong>" + neighborhood + "<br>";
markerhtml += "<strong>Date: </strong>" + date + "<br><br>";
for (var i=0; i < objVictimdata.length; i++) {
var image_path = objVictimdata[i].image_path;
var image_height = objVictimdata[i].image_height;
markerhtml += "<strong>Victim Name: </strong>" + objVictimdata[i].name + "<br>";
markerhtml += "<strong>Age:</strong> " + objVictimdata[i].age + "<br>";
markerhtml += "<strong>Race:</strong> " + objVictimdata[i].race + "<br>";
markerhtml += "<strong>Gender:</strong> " + objVictimdata[i].gender + "<br>";
markerhtml += "<strong>Cause:</strong> " + objVictimdata[i].cause + "<br><br>";
console.log(markerhtml);
}//end for
})//end post
console.log(markerhtml);
var image = new google.maps.MarkerImage('http://labs.google.com/ridefinder/images/mm_20_green.png',
new google.maps.Size(12, 20),
new google.maps.Point(0,0),
new google.maps.Point(6, 20));
var marker = new google.maps.Marker({
position: point,
map: map,
icon: image
});
var infoWindow = new google.maps.InfoWindow(); //initialize infoWindow
// Add a click event to each marker which will open the HTML window
marker.infowindow = new google.maps.InfoWindow({
content: markerhtml
});
google.maps.event.addListener(marker, "click", function() {
marker.infowindow.open(map, marker);
});
};//end create marker
Try the following code. The diffence is that I placed all statemetns following the call to $.post inside of the anonymous function which is fired after and only if the post succeeds. When you call $.Post, the function on the inside isn’t ran until the post is complete, but execution still continues to the following statements while the post occurs in the background!
Paraphrased The inner anonymous function has been expanded to include most of the code. If you are unsure of the difference, try using a program like WinMerge which will show you the difference: