Skip to content

Instantly share code, notes, and snippets.

@getsudocode
Last active July 18, 2018 09:27
Show Gist options
  • Save getsudocode/b185aab506853e8c0d5511cafa56e724 to your computer and use it in GitHub Desktop.
Save getsudocode/b185aab506853e8c0d5511cafa56e724 to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html>
<head>
<title></title>
<style>
#map {
height: 100%;
}
html, body {
height: 100%;
margin: 0;
padding: 0;
}
</style>
</head>
<body>
<div id="map"></div>
<script>
let map;
let markersArray = [];
let polyline = null;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -34.397, lng: 150.644},
zoom: 8
});
// map onclick listener
map.addListener('click', function(e) {
//console.log(e);
addMarker(e.latLng);
drawPolyline();
});
}
// define function to add marker at given lat & lng
function addMarker(latLng) {
let marker = new google.maps.Marker({
map: map,
position: latLng,
draggable: true
});
// add listener to redraw the polyline when markers position change
marker.addListener('position_changed', function() {
drawPolyline();
});
//store the marker object drawn in global array
markersArray.push(marker);
}
// define function to draw polyline that connect markers' position
function drawPolyline() {
let markersPositionArray = [];
// obtain latlng of all markers on map
markersArray.forEach(function(e) {
markersPositionArray.push(e.getPosition());
});
// check if there is already polyline drawn on map
// remove the polyline from map before we draw new one
if (polyline !== null) {
polyline.setMap(null);
}
// draw new polyline at markers' position
polyline = new google.maps.Polyline({
map: map,
path: markersPositionArray,
strokeOpacity: 0.4
});
}
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment