JSFiddle - React, Tailwind, and code Playground
by bartek
HTML
<script src="http://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&.js"></script>
<p>Click on map to place markers, drag markers to change route</p>
<p>Please view comment block towards end of javascript code!</p>
<p>
<button type="button" onclick="resetMarkers();">Reset Markers</button>
</p>
<div id="map_canvas" style="width:600px; height:500px;"></div>
JavaScript
function init() {
var markers = [],
segments = [],
myOptions = {
zoom: 15,
center: new google.maps.LatLng(34.0504, -118.2444),
mapTypeId: google.maps.MapTypeId.ROADMAP,
disableDoubleClickZoom: true,
draggableCursor: "crosshair"
},
alphas = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split(''),
alphaIdx = 0,
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions),
service = new google.maps.DirectionsService(),
poly = new google.maps.Polyline({
map: map,
strokeColor: '#00FFFF',
strokeOpacity: 0.6,
strokeWeight: 5
});
window.resetMarkers = function () {
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(null);
}
alphaIdx = 0;
segments = [];
markers = [];
poly.setPath([]);
};
function getSegmentsPath() {
var a, i,
len = segments.length,
arr = [];
for (i = 0; i < len; i++) {
a = segments[i];
if (a && a.routes) {
arr = arr.concat(a.routes[0].overview_path);
}
}
return arr;
}
function rmSegment() {
var idx = this.segmentIndex,
segLen = segments.length;//segLen will always be 1 shorter than markers.length
if (idx == -1) { //this is the first marker
segments.splice(Math.abs(segLen) * -1, 1);
markers[0].setMap(null);
markers.splice(0, 1);
for (var i = 0; i < markers.length; i++) {
markers[i].segmentIndex = i - 1;
}
poly.setPath(getSegmentsPath());
} else if (idx == segLen - 1) { //this is the last marker
segments.splice(idx, 1);
markers[idx + 1].setMap(null);
markers.splice(idx + 1, 1);
poly.setPath(getSegmentsPath());
...