Skip to content

Instantly share code, notes, and snippets.

@witmin
Created November 19, 2017 08:59
Show Gist options
  • Save witmin/186b2646291eb41899ffe76d80e23a76 to your computer and use it in GitHub Desktop.
Save witmin/186b2646291eb41899ffe76d80e23a76 to your computer and use it in GitHub Desktop.
Enhanced method to create multiple markers and marker clusterer with simplified code.
<!-- This is the corresponding "starter code" for 07_Markers/Infowindows in Udacity and Google's Maps
API Course, Lesson 1 -->
<html>
<head>
<!-- styles put here, but you can include a CSS file and reference it instead! -->
<style type="text/css">
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#map {
height: 100%;
}
</style>
</head>
<body>
<div id="map"></div>
<script type="text/javascript">
// Create a map variable
var map;
// Function to initialize the map within the map div
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 40.74135, lng: -73.99802},
zoom: 13
});
// Create an array of alphabetical characters used to label the markers.
var labels = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
var locations = [
{title: 'Park Ave Penthouse', location: {lat: 40.7713024, lng: -73.9632393}},
{title: 'Chelsea Loft', location: {lat: 40.7444883, lng: -73.9949465}},
{title: 'Union Square Open Floor Plan', location: {lat: 40.7347062, lng: -73.9895759}},
{title: 'East Village Hip Studio', location: {lat: 40.7281777, lng: -73.984377}},
{title: 'TriBeCa Artsy Bachelor Pad', location: {lat: 40.7195264, lng: -74.0089934}},
{title: 'Chinatown Homey Space', location: {lat: 40.7180628, lng: -73.9961237}}
];
var markers = locations.map(function (location, i) {
return new google.maps.Marker({
position: location.location,
label: labels[i % labels.len],
title: location.title
});
});
var infoWindow = new google.maps.InfoWindow();
markers.forEach(function (marker) {
marker.addListener('click', function () {
console.log(marker);
infoWindow.close();
infoWindow = new google.maps.InfoWindow({
content: marker.title
});
infoWindow.open(map, marker);
})
});
var markerCluster = new MarkerClusterer(map, markers,
{imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'});
}
</script>
<!-- inlude library of marker clusterer-->
<script src="https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/markerclusterer.js"></script>
<!--Insert your API Key in the below call to load the API.-->
<script src="https://maps.googleapis.com/maps/api/js?key={APIKEY}&callback=initMap"
async defer></script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment