vendredi 19 août 2016

Adding Google Maps markers - Javascript 'IF' does not work in 'FOR' loop

I would like to add different coloured markers to a Google Map; if the address is a rental house ("Y"), and add red markers if the address belongs to a private advertiser ("N"). I thought it could be easily done by an IF condition, but somehow it does not work and I can not figure out the solution. The if (usertypes[x]=="Y") {} is not recognised so it automatically jumps to else {}, that's why the result is always blue now.

The code:

var addresses = ['address1', 'address2', 'address3', 'address4', 'address5'];
var usertypes = ['Y', 'N', 'Y', 'Y', 'N'];
var bounds = new google.maps.LatLngBounds();

// the loop:
for (var x = 0; x < addresses.length; x++) {
  $.getJSON('http://ift.tt/1dMgVj6' + addresses[x] + '&sensor=false', null, function(data) {
    var p = data.results[0].geometry.location
    var latlng = new google.maps.LatLng(p.lat, p.lng);

    // set red marker if the advertiser is a private user:
    if (usertypes[x] == "Y") {
      new google.maps.Marker({
        position: latlng,
        map: map,
        icon: 'http://ift.tt/Jp3W8N',
        title: 'item position'
      });

      bounds.extend(latlng);

      // set blue marker if it is a rental house:
    } else {
      new google.maps.Marker({
        position: latlng,
        map: map,
        icon: 'http://ift.tt/1kglguQ',
        title: 'item position'
      });
      
      bounds.extend(latlng);
    }
  });
}

map.fitBounds(bounds);

Thanks for your help :)

Aucun commentaire:

Enregistrer un commentaire