3

I need to work with EACH of markers on map, so what i want is something like this:

var marker[5] = new google.maps.Marker({
  position: new google.maps.LatLng(31.0962,36.2738),
  map: map, //declared before ..
  optimized: false,
  label:'FRED'
});

so i can handle each marker like this: (also many interactions with server side)

marker[5].setPosition(NewPosition);

i know that above form is not possible, but cant find accurate answer.

Fredi
  • 149
  • 3
  • 13
  • create an array of markers called `markers`. then do `markers.forEach...` – Paul Thomas Feb 22 '17 at 17:17
  • Really wouldn't have been very hard to google it or search here. Already been answered numerous times -http://stackoverflow.com/questions/3059044/google-maps-js-api-v3-simple-multiple-marker-example – Paul Thomas Feb 22 '17 at 17:18
  • @PaulThomasGC Thanks, i know my self as a googler :) , but answers don't solve problem for me. for that link, i can GENERATE all markers.. but i cant ACCESS to each unique marker after ganarating. i need assign id for each marker for access and work with it. – Fredi Feb 22 '17 at 17:28
  • I see. If you were to use the code on the link I sent then you could alter it my making a new array `var markers = []` around the same place as `var marker, i;` and then after where you create the marker (`marker = new google.maps ... `) do `markers.push(marker)`. You will then have an array containing all the actual markers. You can then do as you suggest `marker[5].setPosition(NewPosition)` – Paul Thomas Feb 22 '17 at 17:39

1 Answers1

4

Script amended from Google Maps JS API v3 - Simple Multiple Marker Example\

Working fiddle: https://jsfiddle.net/6tyavn93/

var locations = [
  ['Bondi Beach', -33.890542, 151.274856, 4],
  ['Coogee Beach', -33.923036, 151.259052, 5],
  ['Cronulla Beach', -34.028249, 151.157507, 3],
  ['Manly Beach', -33.80010128657071, 151.28747820854187, 2],
  ['Maroubra Beach', -33.950198, 151.259302, 1]
];

var map = new google.maps.Map(document.getElementById('map'), {
  zoom: 10,
  center: new google.maps.LatLng(-33.92, 151.25),
  mapTypeId: google.maps.MapTypeId.ROADMAP
});

var infowindow = new google.maps.InfoWindow();

var marker, i;
var markers = [];

for (i = 0; i < locations.length; i++) {  
  marker = new google.maps.Marker({
    position: new google.maps.LatLng(locations[i][1], locations[i][2]),
    map: map
  });

  markers.push(marker);

  google.maps.event.addListener(marker, 'click', (function(marker, i) {
    return function() {
      infowindow.setContent(locations[i][0]);
      infowindow.open(map, marker);
    }
  })(marker, i));
}

console.log(markers[0]);
Community
  • 1
  • 1
Paul Thomas
  • 2,756
  • 2
  • 16
  • 28