user198003
user198003

Reputation: 11151

How to change position of marker, created in run-time (Google Maps v3)

I have to create several markers on Google Maps, in run-time.

Their initial position is randomly defined.

When they are created, how can I change position of some of them? New position is also randomly defined.

I did tried with

marker1.setPosition(pt);

... but, I'm getting error

marker1 is not defined

I guess that problem is that marker1 is not defined in moment when map is created... Something like that.

Can you help me how can I solve this one?

p.s. There is no limit of how many markers will be created.

UPDATE Markers are created with:

function addNewMarker( locationsTotal ) {

if (document.getElementById("lon1").value == '') document.getElementById("lon1").value = '19';
if (document.getElementById("lat1").value == '') document.getElementById("lat1").value = '45';

var parliament = (map.getCenter());

var newMarker = 'marker' + locationsTotal;
newMarker = new google.maps.Marker({
  name:newMarker,
  id:newMarker,
  map:map,
  draggable:true,
  animation: google.maps.Animation.DROP,
  position: parliament, 
  icon: 'img/pin.png'
});

google.maps.event.addListener(newMarker, "dragend", function() {
  var center = newMarker.getPosition();
  var latitude = center.lat();
  var longitude = center.lng();
  var newLon = 'lon' + locationsTotal;
  var newLat = 'lat' + locationsTotal;
  document.getElementById(newLon).value = longitude;
  document.getElementById(newLat).value = latitude;
});

}

Upvotes: 1

Views: 2067

Answers (1)

WojtekT
WojtekT

Reputation: 4775

As You can see newMarker is visible only in the scope of addNewMarker function. What you need is to store your markers in array visible in global scope. For example: Modify your function:

var allMarkers = [];
function addNewMarker( locationsTotal ) {
   //.... skip
  allMarkers.push(newMarker);
}

All your markers are now stored in an array so you can manipulate them.

To access marker by name add function:

function getMarker(name) {
  for (k in allMarkers)
     if (allMarkers[k].name == name) return allMarkers[k];
  return null;
}

Upvotes: 3

Related Questions