I’m trying to add multiple markers to a map after fetching the positions via an AJAX call, but the markers simply won’t show up. I checked lat and lon, they are retrieved correctly. I tried two ways of adding them (the traditional maps way and through a library I use called gmaps.js), but none of them works.
Do I need a closure to simply add the markers ? I don’t need to add events and stuff (yet).
I’ve been searching for solutions, but none of what I found seems to work. Please help.
Here’s the code (comments inside):
function mapInit( vID )
{
// INIT MAP
var map = new GMaps({
div: '#map',
lat: 0,
lng: 0,
zoom: 14,
zoomControl: false,
panControl: false,
mapTypeControl: false,
scaleControl: false
});
var vData = '';
var club_centered = false;
// get villa info via AJAX
// single villa if vID = 0; else get all villas
$.ajax({
url: ajax_vars.ajax_url,
type: 'POST',
beforeSend: function( x )
{
if( x && x.overrideMimeType ) {
x.overrideMimeType("application/json;charset=UTF-8");
}
},
data: 'action=get_villa_data&id='+vID,
success: function( response )
{
vData = response;
},
complete: function()
{
for ( var i = 0; i < vData.length; i++ )
{
if ( vData[i].lat )
{
console.log( vData[i].lat );
console.log( vData[i].lon );
// using gmaps.js
// map.addMarker({
// title: vData[i].title,
// lat: parseFloat( vData[i].lat ),
// lng: parseFloat( vData[i].lng )
// });
// traditional maps way
// I get an error if I uncomment the 'map:map' line
marker = new google.maps.Marker({
position: new google.maps.LatLng( parseFloat(vData[i].lat), parseFloat(vData[i].lon) ),
// map: map
});
}
}
}
});
// add CLUB marker
// this works perfectly
var clubLat = 37.809750047720904;
var clubLon = 20.875182151794434;
// GMaps.geocode({
// address: clubAddress,
// callback: function(results, status){
// if(status=='OK'){
// var latlng = results[0].geometry.location;
map.addMarker({
title: 'The Club',
lat: clubLat,
lng: clubLon
});
// if ( club_centered )
map.setCenter( clubLat, clubLon );
// }
// }
// });
}
I think your problem is when creating the map, because you’re getting an error on map:map, so possibly the map is not created properly.
Try using this instead: