I am creating a map for users on my website. The way it works is I use PHP and AJAX to get all the sites users addresses, I then pass these values to my JS as JSON where I generate a google map centered around the current users address with a marker for each user on the map. This part works at the moment but what I'm struggling with is generating a unique infowindow for each user. As it is right now I get the same info window for all markers, how can I fix this?
JS
jQuery(document).ready(function($){
$.ajax({
url: ajax_url,
type: 'post',
dataType: 'json',
data: {
action: 'map'
},
error : function(response){
console.log(response);
},
success : function(response){
var mapOptions = {
zoom: 16,
}
var geocoder = new google.maps.Geocoder();
var infowindow = new google.maps.InfoWindow();
// current user position
geocoder.geocode({'address': response.current[0].postcode}, function(results, status){
map.setCenter( results[0].geometry.location );
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
});
// other users loop
for( var i = 0; i < response.other.length; i++ ){
var postcode = response.other[i].postcode;
geocoder.geocode( {'address': postcode}, function(results, status){
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
google.maps.event.addListener(marker, 'click', function(){
infowindow.close(); // Close previously opened infowindow
infowindow.setContent( "<div id='infowindow'>"+ postcode +"</div>");
infowindow.open(map, this);
});
});
}
var map = new google.maps.Map(document.getElementById("buddy_map"), mapOptions);
return false;
}
});
});
PHP
add_action('wp_ajax_nopriv_map', 'addresses');
add_action('wp_ajax_map', 'addresses');
function addresses(){
global $current_user;
$address_street = get_user_meta( $current_user->ID, 'shipping_address_1', true );
$address_city = get_user_meta( $current_user->ID, 'shipping_city', true );
$address_postcode = get_user_meta( $current_user->ID, 'shipping_postcode', true );
$address = $address_street . ', ' . $address_city . ', ' . $address_postcode;
$cur_user[] = array(
"postcode" => $address
);
$other_users[] = array(
"postcode" => "LS11 6NA"
);
$other_users[] = array(
"postcode" => "LS11 6LY"
);
echo json_encode( array( "current" => $cur_user, "other" => $other_users) );
die();
}
I know my PHP file needs some work its just a rough draft to get this working first.