Solved

Google maps API javascript - adding markers after initialize

Posted on 2014-01-21
18
3,639 Views
Last Modified: 2014-01-21
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
Comment
Question by:JoachimPetersen
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 6
  • 6
  • 5
  • +1
18 Comments
 
LVL 58

Expert Comment

by:Gary
ID: 39798145
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
 

Author Comment

by:JoachimPetersen
ID: 39798173
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
 

Author Comment

by:JoachimPetersen
ID: 39798177
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
MS Dynamics Made Instantly Simpler

Make Your Microsoft Dynamics Investment Count  & Drastically Decrease Training Time by Providing Intuitive Step-By-Step WalkThru Tutorials.

 
LVL 43

Expert Comment

by:Chris Stanyon
ID: 39798181
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
 
LVL 58

Expert Comment

by:Gary
ID: 39798196
You need to give the map time to initialise

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

(Actually made a few other changes - but minor)
0
 
LVL 38

Expert Comment

by:Tom Beck
ID: 39798216
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
 
LVL 58

Expert Comment

by:Gary
ID: 39798223
(Yep that is my other minor changes)
But his problem is trying to add the marker before the map is finished initialising.
0
 
LVL 38

Expert Comment

by:Tom Beck
ID: 39798242
The API does have an 'idle' listener that executes when the map is finished loading.

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

Author Comment

by:JoachimPetersen
ID: 39798265
<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
 
LVL 58

Expert Comment

by:Gary
ID: 39798280
Good point!
0
 
LVL 58

Expert Comment

by:Gary
ID: 39798291
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
 

Author Comment

by:JoachimPetersen
ID: 39798349
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
 
LVL 38

Expert Comment

by:Tom Beck
ID: 39798350
This:

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

Expert Comment

by:Tom Beck
ID: 39798366
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
 

Author Comment

by:JoachimPetersen
ID: 39798368
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
 
LVL 38

Assisted Solution

by:Tom Beck
Tom Beck earned 200 total points
ID: 39798389
See my last post.
0
 
LVL 58

Accepted Solution

by:
Gary earned 300 total points
ID: 39798399
http://jsfiddle.net/GaryC123/dr2wu/4/

Incorporating Tom's correction to my idle placement.
0
 

Author Closing Comment

by:JoachimPetersen
ID: 39798436
Perfect solution.
0

Featured Post

PeopleSoft Has Never Been Easier

PeopleSoft Adoption Made Smooth & Simple!

On-The-Job Training Is made Intuitive & Easy With WalkMe's On-Screen Guidance Tool.  Claim Your Free WalkMe Account Now

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In my daily work (mainly using ASP.net), I need to write a lot of JavaScript code. One of the most repetitive tasks I do are the jQuery Ajax calls. You know: (CODE) I don't know if for you it's the same, but for me is soooo tedious to write the …
JavaScript can be used in a browser to change parts of a webpage dynamically. It begins with the following pattern: If condition W is true, do thing X to target Y after event Z. Below are some tips and tricks to help you get started with JavaScript …
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

705 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question