-1

Hi I have the following code. I would like to update my Google Maps Marker with the location given from a clicked image. Currently i have an array of images being created inside the for loop. When a user clicks on an image i would like the restMarker to update with the new longitude and latitude. Then the marker position is updated outside the loop. I can not seem to get the code below to work.

var restMarker = {
  lat: 0, //Just set to a trivial value 
  lng: 0
};

let imagesZom = $("#zomato");
for (i = 0; i < passArrayI.length; i++) {
  imagesZom.append(
    $("<a>").attr("href", passArrayW[i])
      .attr("target", "_blank")
      .append("<img id = img" + i + " " + "src =" + passArrayI[i] + "</img>")
      .click(function() {
        restMarker = {
          lat: parseFloat(passArrayLat[i]),
          lng: parseFloat(passArrayLong[i])
        };
      })
  )
}

setTimeout(function() {
  marker.setPosition(restMarker);
  map.setCenter(marker.getPosition());
}, 100)

When i run the following code it works but when i try to put it into a for loop like above i can't get it to work.

var restMarker = {
  lat: parseFloat(passArrayLat[0]),
  lng: parseFloat(passArrayLong[0])
};
setTimeout(function() {
  marker.setPosition(restMarker);
  map.setCenter(marker.getPosition());
}, 100)
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
Sam
  • 89
  • 1
  • 1
  • 11

1 Answers1

0

in loop you are overriding same restMarker variable inside click event handler. you can push longitude and latitude in data attributes of image and retrive it while calling click event handler. see below code

    var restMarker = {
      lat: 0, //Just set to a trivial value 
      lng: 0
    };

    let imagesZom = $("#zomato");
    for (i = 0; i < passArrayI.length; i++) {
      imagesZom.append(
        $("<a>").attr("href", passArrayW[i])
          .attr("target", "_blank")
          .append("<img class='mapImage' id ='img" + i + "' src ='" + passArrayI[i] 
               + "' data-lat='" + passArrayLat[i] 
               + "'  data-long='" + passArrayLong[i] + "'> </img>");
        );
    }

    // write separeate click handler for all images
   $(document).on('click','.mapIamge',function() {
            var latVal = $(this).data('lat');
            var lngVal = $(this).data('long');
            restMarker = {
              lat: parseFloat(latVal),
              lng: parseFloat(lngVal)
            };
   });

    setTimeout(function() {
      marker.setPosition(restMarker);
      map.setCenter(marker.getPosition());
    }, 100);
Bhushan Kawadkar
  • 28,279
  • 5
  • 35
  • 57