Skip to content

Instantly share code, notes, and snippets.

@ffflabs
Last active August 29, 2015 14:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ffflabs/a4bd1e692e2db3e1dfe0 to your computer and use it in GitHub Desktop.
Save ffflabs/a4bd1e692e2db3e1dfe0 to your computer and use it in GitHub Desktop.
Drawing markers from an array/json and attaching infowindows to them

Example:

Using a JS object to draw a collection of markers, taking the position and additional attributes from the object itself.

On each loop the marker is drawn, and it receives a click listener, which in turn opens an infowindow whose content is the markers properties, taken from the JS object.

Made as an example for Stack Overflow

<!DOCTYPE html>
<html>
<meta charset="utf-8">
<head>
<style>
.infowindow {
width:200px;
height:150px;
}
#map-canvas {
}
</style>
<body>
<script src="http://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&libraries=visualization,drawing,places,weather,geometry"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<script>
var width = 900,
height = 600,
globalOverlay = null,
map = null;
jQuery(document).ready(function() {
jQuery('#map-canvas').width(width);
jQuery('#map-canvas').height(height);
});
function initialize() {
map = new google.maps.Map(document.getElementById('map-canvas'), {
zoom: 6,
center: {lat: 37.55, lng: -90.963}
});
var WindCollection=[
{name: 'Place 1', lat: 37.55, lng:-90 , wind_speed:50, direction:'NW', temperature:'60'},
{name: 'Place 2', lat: 36.15, lng:-94 , wind_speed:45, direction:'N', temperature:'62'},
{name: 'Place 3', lat: 36.12, lng:-89 , wind_speed:55, direction:'SE', temperature:'59'}
];
WindCollection.forEach(function(windplace) {
var marker=new google.maps.Marker({position:{lat:windplace.lat, lng:windplace.lng}, clickable:true, map:map, animation:google.maps.Animation.DROP });
google.maps.event.addListener(marker,'click',function() {
var infowindow = new google.maps.InfoWindow();
var infolist=jQuery('<ul></ul>');
for (attribute in windplace) {
infolist.append('<li><b>'+attribute+'</b>: '+windplace[attribute]+'</li>');
}
infowindow.setContent('<div class="infowindow">'+infolist.html()+'</div>');
infowindow.open(map, marker);
map.panTo(marker.getPosition());
});
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas"></div>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment