Marker with an Information Window

Now that we have a marker on the map, we can add an information window.
map3-1.png

There are three basic things to pay attention to:

These steps are shown below:

/* Create content.  Here we are concatenating strings together with the JS "+" operator */
var statue_info = "<strong>John Harvard Statue</strong><br/>" +
    "<a href='http://www.summer.harvard.edu/blog-news-events/3-lies-harvard'>3 Lies of Harvard</a>";

/* Create the InfoWindow object; note we pass in the content */
var statue_infowindow = new google.maps.InfoWindow({
    content: statue_info
});

/* Create the marker (we've seen this before) */
var statue_marker = new google.maps.Marker({
  position: statue_latlng,
  map: harvard_yard_map,
  title: 'John Harvard Statue'
});

/* Create the listener so that the info window opens when the marker is clicked */
google.maps.event.addListener(statue_marker, 'click', function() {
  statue_infowindow.open(harvard_yard_map,statue_marker);
});

Full example:

<!DOCTYPE html>
<html>
<head>
<title>Map of Harvard Yard</title>
<meta charset="utf-8"/>
<style type="text/css">
#map-canvas {width: 100%; height: 500px;}
</style>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp"> </script>
<script>
var harvard_yard_map;
/* John Harvard Status
42.374474,-71.117207 */
var statue_latlng = new google.maps.LatLng(42.374474, -71.117207);
function initialize() {
var mapOptions = {
zoom: 17,
center: statue_latlng
};
harvard_yard_map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
var statue_info = "<strong>John Harvard Statue</strong><br/>" +
"<a href='http://www.summer.harvard.edu/blog-news-events/3-lies-harvard'>3 Lies of Harvard</a>";
var statue_infowindow = new google.maps.InfoWindow({
content: statue_info
});
var statue_marker = new google.maps.Marker({
position: statue_latlng,
map: harvard_yard_map,
title: 'John Harvard Statue'
});
google.maps.event.addListener(statue_marker, 'click', function() {
statue_infowindow.open(harvard_yard_map,statue_marker);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<h1>Map of Harvard Yard</h1>
<div id="map-canvas"> Map Goes Here </div>
</body>
</html>

Map with Marker working examples:

Copyright © David Heitmeyer