Improve company productivity with a Business Account.Sign Up

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 4420
  • Last Modified:

Google maps API javascript - adding markers after initialize

Hello

I have a problem, I need to replace/delete/add new markers to the map after the google map is initialized.

How can this be done?

The problem is that you cannot add markers unless it is executed in the google map initialize function, I want to add markers after the initialize function had run.
Here is an example:
<!DOCTYPE html>
<html>
  <head>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <title>Info windows</title>
    <style>
      html, body, #map-canvas {
        height: 100%;
        margin: 0px;
        padding: 0px
      }
    </style>
    <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
    <script>
// This example displays a marker at the center of Australia.
// When the user clicks the marker, an info window opens.

function initialize() {
  var myLatlng = new google.maps.LatLng(-25.363882,131.044922);
  var mapOptions = {
    zoom: 4,
    center: myLatlng
  };

  var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);

  var contentString = '<div id="content">'+
      '<div id="siteNotice">'+
      '</div>'+
      '<h1 id="firstHeading" class="firstHeading">Uluru</h1>'+
      '<div id="bodyContent">'+
      '<p><b>Uluru</b>, also referred to as <b>Ayers Rock</b>, is a large ' +
      'sandstone rock formation in the southern part of the '+
      '<p>Attribution: Uluru, <a href="http://en.wikipedia.org/w/index.php?title=Uluru&oldid=297882194">'+
      'http://en.wikipedia.org/w/index.php?title=Uluru</a> '+
      '(last visited June 22, 2009).</p>'+
      '</div>'+
      '</div>';

  var infowindow = new google.maps.InfoWindow({
      content: contentString
  });

  var marker = new google.maps.Marker({
      position: myLatlng,
      map: map,
      title: 'Uluru (Ayers Rock)'
  });
  google.maps.event.addListener(marker, 'click', function() {
    infowindow.open(map,marker);
  });
}

google.maps.event.addDomListener(window, 'load', initialize);

    </script>
  </head>
  <body>
    <div id="map-canvas"></div>
  </body>
</html>

Open in new window


Put this outside the initialize function and it will not add a marker:
  var contentString = '<div id="content">'+
      '<div id="siteNotice">'+
      '</div>'+
      '<h1 id="firstHeading" class="firstHeading">Uluru</h1>'+
      '<div id="bodyContent">'+
      '<p><b>Uluru</b>, also referred to as <b>Ayers Rock</b>, is a large ' +
      'sandstone rock formation in the southern part of the '+
      '<p>Attribution: Uluru, <a href="http://en.wikipedia.org/w/index.php?title=Uluru&oldid=297882194">'+
      'http://en.wikipedia.org/w/index.php?title=Uluru</a> '+
      '(last visited June 22, 2009).</p>'+
      '</div>'+
      '</div>';

  var infowindow = new google.maps.InfoWindow({
      content: contentString
  });

  var marker = new google.maps.Marker({
      position: myLatlng,
      map: map,
      title: 'Uluru (Ayers Rock)'
  });
  google.maps.event.addListener(marker, 'click', function() {
    infowindow.open(map,marker);
  });

Open in new window


I simply need to add markers without having the map to reload.

Thank you in advance.
0
JoachimPetersen
Asked:
JoachimPetersen
  • 6
  • 6
  • 5
  • +1
2 Solutions
 
GaryCommented:
Assume this is what you are looking for
All I have done is remove your marker from the initialisation and placed it a function call

http://jsfiddle.net/GaryC123/dr2wu/2/
0
 
JoachimPetersenAuthor Commented:
yup, but when I try to execute this by simpy putting it in like this:
      google.maps.event.addDomListener(window, 'load', initialize);
      addMarker();
then it does not add a marker, it do however run the function (I putted an alarm in the function)
0
 
JoachimPetersenAuthor Commented:
I need it to run the function when map is initialized and then have a timer to update it (executing the function)
- I do know how to do the timer thing, just look at my post above and tell me what it does not add a marker.
0
Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

 
Chris StanyonCommented:
As Gary says, just put the marker code in it's own function (or directly a Button click event). No need to do this on initialisation:

$('#addMarker').click(function() {
	//location for the new marker
	myLatlng = new google.maps.LatLng(50.418144, -5.073824);

	//add the marker to the map
	marker = new google.maps.Marker({
		position: myLatlng,
		map: map,
		title:"A New Marker!"
	});
	
	//create the info window
	infowindow = new google.maps.InfoWindow({
		content: '<div>This is an info window</div>'
	});

	//bind the marker 'click' to show the info window
	google.maps.event.addListener(marker, 'click', function() {
		infowindow.open(map,marker);
	});

});

Open in new window

0
 
GaryCommented:
You need to give the map time to initialise

setTimeout(function(){addMarker()},2000);

(Actually made a few other changes - but minor)
0
 
Tom BeckCommented:
I think what the OP is missing from Gary's example is that the variables map and myLatLng have been moved outside the initialize function making them global. It will not work unless you do that.
0
 
GaryCommented:
(Yep that is my other minor changes)
But his problem is trying to add the marker before the map is finished initialising.
0
 
Tom BeckCommented:
The API does have an 'idle' listener that executes when the map is finished loading.

google.maps.event.addListener(map, 'idle', function() {
    addMarker();
});
0
 
JoachimPetersenAuthor Commented:
<script type="text/javascript">
      // true
      var map;
      var marker;
      function initialize() {      
        var myOptions = {
          //map basic
          zoom: 5,
          center: new google.maps.LatLng(33.678176, -116.242568)
        };
        map = new google.maps.Map(document.getElementById('map_canvas'),myOptions);
      }
      
      google.maps.event.addDomListener(window, 'load', initialize);
      
      google.maps.event.addListener(map, 'idle', function() {
    	addMarker();
	  });
      
      function addMarker() {
      var contentString = '<div id="content">'+
      '<div id="siteNotice">'+
      '</div>'+
      '<h1 id="firstHeading" class="firstHeading">Uluru</h1>'+
      '<div id="bodyContent">'+
      '<p><b>Uluru</b>, also referred to as <b>Ayers Rock</b>, is a large ' +
      'sandstone rock formation in the southern part of the '+
      '<p>Attribution: Uluru, <a href="http://en.wikipedia.org/w/index.php?title=Uluru&oldid=297882194">'+
      'http://en.wikipedia.org/w/index.php?title=Uluru</a> '+
      '(last visited June 22, 2009).</p>'+
      '</div>'+
      '</div>';
      var infowindow = new google.maps.InfoWindow({
      content: contentString
  	  });
      marker = new google.maps.Marker({
      position: new google.maps.LatLng(33.678176, -116.242568),
      map: map,
      title: 'Uluru (Ayers Rock)'
      });
      google.maps.event.addListener(marker, 'click', function() {
      	infowindow.open(map,marker);
      });
      }
         
    </script>

Open in new window

I have seen all the great advice you guys have said, but this still does not work?
0
 
GaryCommented:
Good point!
0
 
GaryCommented:
That's not the code I have in my fiddle.

<script>
var map
var myLatlng = new google.maps.LatLng(-25.363882,131.044922);

function initialize() {
  var googleMapOptions = {
    zoom: 4,
    center: myLatlng
  };

map = new google.maps.Map(document.getElementById("map-canvas"), googleMapOptions);
}

google.maps.event.addDomListener(window, 'load', initialize);
 
             function addMarker() {
      var contentString = '<div id="content">'+
      '<div id="siteNotice">'+
      '</div>'+
      '<h1 id="firstHeading" class="firstHeading">Uluru</h1>'+
      '<div id="bodyContent">'+
      '<p><b>Uluru</b>, also referred to as <b>Ayers Rock</b>, is a large ' +
      'sandstone rock formation in the southern part of the '+
      '<p>Attribution: Uluru, <a href="http://en.wikipedia.org/w/index.php?title=Uluru&oldid=297882194">'+
      'http://en.wikipedia.org/w/index.php?title=Uluru</a> '+
      '(last visited June 22, 2009).</p>'+
      '</div>'+
      '</div>';
      var infowindow = new google.maps.InfoWindow({
      content: contentString
  });
      var marker = new google.maps.Marker({
      position: myLatlng,
      map: map,
      title: 'Uluru (Ayers Rock)'
  });
  google.maps.event.addListener(marker, 'click', function() {
    infowindow.open(map,marker);
  });
             }
google.maps.event.addListener(map, 'idle', function() {
    addMarker();
}); 
</script>

Open in new window

0
 
JoachimPetersenAuthor Commented:
This should then be the final code?
<!DOCTYPE html>
<html>
  <head>
    <title>Map</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no,  target-densitydpi=device-dpi">
    <meta charset="UTF-8">
    <style type="text/css">
    html, body, #map_canvas {
        margin: 0;
        padding: 0;
        height: 100%;
	}
    </style>
    <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script type="text/javascript">
var map
var myLatlng = new google.maps.LatLng(-25.363882,131.044922);

function initialize() {
  var googleMapOptions = {
    zoom: 4,
    center: myLatlng
  };

map = new google.maps.Map(document.getElementById("map-canvas"), googleMapOptions);
}

google.maps.event.addDomListener(window, 'load', initialize);
 
             function addMarker() {
      var contentString = '<div id="content">'+
      '<div id="siteNotice">'+
      '</div>'+
      '<h1 id="firstHeading" class="firstHeading">Uluru</h1>'+
      '<div id="bodyContent">'+
      '<p><b>Uluru</b>, also referred to as <b>Ayers Rock</b>, is a large ' +
      'sandstone rock formation in the southern part of the '+
      '<p>Attribution: Uluru, <a href="http://en.wikipedia.org/w/index.php?title=Uluru&oldid=297882194">'+
      'http://en.wikipedia.org/w/index.php?title=Uluru</a> '+
      '(last visited June 22, 2009).</p>'+
      '</div>'+
      '</div>';
      var infowindow = new google.maps.InfoWindow({
      content: contentString
  });
      var marker = new google.maps.Marker({
      position: myLatlng,
      map: map,
      title: 'Uluru (Ayers Rock)'
  });
  google.maps.event.addListener(marker, 'click', function() {
    infowindow.open(map,marker);
  });
             }
google.maps.event.addListener(map, 'idle', function() {
    addMarker();
}); 
</script>
  </head>
  <body>
    <div id="map_canvas"></div>
  </body>
</html>

Open in new window

My browser does not display it
0
 
Tom BeckCommented:
This:

map = new google.maps.Map(document.getElementById("map_canvas"), googleMapOptions);
0
 
Tom BeckCommented:
And put the idle listener inside the initialize function;

function initialize() {
  var googleMapOptions = {
    zoom: 4,
    center: myLatlng
  };

map = new google.maps.Map(document.getElementById("map_canvas"), googleMapOptions);

google.maps.event.addListener(map, 'idle', function() {
    addMarker();
}); 
}

Open in new window

0
 
JoachimPetersenAuthor Commented:
correct had a - insted of a _, now the code should work, but i does not display the marker? it should be Cathals newest javascript code(only replaced the map canvas name).
<!DOCTYPE html>
<html>
  <head>
    <title>Map</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no,  target-densitydpi=device-dpi">
    <meta charset="UTF-8">
    <style type="text/css">
    html, body, #map_canvas {
        margin: 0;
        padding: 0;
        height: 100%;
	}
    </style>
    <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script type="text/javascript">
var map
var myLatlng = new google.maps.LatLng(-25.363882,131.044922);

function initialize() {
  var googleMapOptions = {
    zoom: 4,
    center: myLatlng
  };

map = new google.maps.Map(document.getElementById("map_canvas"), googleMapOptions);
}

google.maps.event.addDomListener(window, 'load', initialize);
 
             function addMarker() {
      var contentString = '<div id="content">'+
      '<div id="siteNotice">'+
      '</div>'+
      '<h1 id="firstHeading" class="firstHeading">Uluru</h1>'+
      '<div id="bodyContent">'+
      '<p><b>Uluru</b>, also referred to as <b>Ayers Rock</b>, is a large ' +
      'sandstone rock formation in the southern part of the '+
      '<p>Attribution: Uluru, <a href="http://en.wikipedia.org/w/index.php?title=Uluru&oldid=297882194">'+
      'http://en.wikipedia.org/w/index.php?title=Uluru</a> '+
      '(last visited June 22, 2009).</p>'+
      '</div>'+
      '</div>';
      var infowindow = new google.maps.InfoWindow({
      content: contentString
  });
      var marker = new google.maps.Marker({
      position: myLatlng,
      map: map,
      title: 'Uluru (Ayers Rock)'
  });
  google.maps.event.addListener(marker, 'click', function() {
    infowindow.open(map,marker);
  });
             }
google.maps.event.addListener(map, 'idle', function() {
    addMarker();
}); 
</script>
  </head>
  <body>
    <div id="map_canvas"></div>
  </body>
</html>

Open in new window

0
 
Tom BeckCommented:
See my last post.
0
 
GaryCommented:
http://jsfiddle.net/GaryC123/dr2wu/4/

Incorporating Tom's correction to my idle placement.
0
 
JoachimPetersenAuthor Commented:
Perfect solution.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

The 14th Annual Expert Award Winners

The results are in! Meet the top members of our 2017 Expert Awards. Congratulations to all who qualified!

  • 6
  • 6
  • 5
  • +1
Tackle projects and never again get stuck behind a technical roadblock.
Join Now