Solved

Google maps API javascript - adding markers after initialize

Posted on 2014-01-21
18
3,174 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
  • 6
  • 6
  • 5
  • +1
18 Comments
 
LVL 58

Expert Comment

by:Gary
Comment Utility
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
Comment Utility
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
Comment Utility
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
 
LVL 42

Expert Comment

by:Chris Stanyon
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
(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
Comment Utility
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
Comment Utility
<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
Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 58

Expert Comment

by:Gary
Comment Utility
Good point!
0
 
LVL 58

Expert Comment

by:Gary
Comment Utility
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
Comment Utility
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
Comment Utility
This:

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

Expert Comment

by:Tom Beck
Comment Utility
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
Comment Utility
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
Comment Utility
See my last post.
0
 
LVL 58

Accepted Solution

by:
Gary earned 300 total points
Comment Utility
http://jsfiddle.net/GaryC123/dr2wu/4/

Incorporating Tom's correction to my idle placement.
0
 

Author Closing Comment

by:JoachimPetersen
Comment Utility
Perfect solution.
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

I've been trying to accomplish this for a while and it just struck me yesterday how to accomplish this task. I have done searches all over the internet looking for ways to email pages from my applications and finally I have done it!!! Every single s…
In Part 1 (http://www.experts-exchange.com/Programming/Languages/Scripting/JavaScript/A_7849-Hex-Maze.html) we covered the hexagonal maze basics -- how the cells are represented in a JavaScript array and how the maze is displayed.  In this part, we'…
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…

744 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

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now