JSFiddle - React, Tailwind, and code Playground
by Dhanck
HTML
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true"></script>
<body onload="initialize()" style="font-family: sans-serif;">
<table style="width: 400px">
<tr>
<td><input type="checkbox" id="optimize" checked />Optimize</td>
</tr>
<tr>
<td><input type="checkbox" id="highways" checked />Avoid highways</td>
<td><input type="button" value="Reset" onclick="reset()" /></td>
</tr>
<tr>
<td><input type="checkbox" id="tolls" checked />Avoid tolls</td>
<td><input type="button" value="Get Directions!" onclick="calcRoute()" /></td>
<td></td>
</tr>
</table>
<div style="position:relative; border: 1px; width: 610px; height: 400px;">
<div id="map_canvas" style="border: 1px solid black; position:absolute; width:398px; height:398px"></div>
<div id="directionsPanel" style="position:absolute; left: 410px; width:240px; height:400px; overflow: auto"></div>
</div>
</body>
JavaScript
var directionDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
var origin = null;
var destination = null;
var waypoints = [];
var markers = [];
var directionsVisible = false;
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer();
var chicago = new google.maps.LatLng(37.7749295, -122.4194155);
var myOptions = {
zoom:13,
mapTypeId: google.maps.MapTypeId.BICYCLING,
center: chicago
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById("directionsPanel"));
google.maps.event.addListener(map, 'click', function(event) {
if (origin == null) {
origin = event.latLng;
addMarker(origin);
} else if (destination == null) {
destination = event.latLng;
addMarker(destination);
} else {
if (waypoints.length < 9) {
waypoints.push({ location: destination, stopover: true });
destination = event.latLng;
addMarker(destination);
} else {
alert("Maximum number of waypoints reached");
}
}
});
}
function addMarker(latlng) {
markers.push(new google.maps.Marker({
position: latlng,
map: map,
icon: "http://maps.google.com/mapfiles/marker" + String.fromCharCode(markers.length + 65) + ".png"
}));
}
function calcRoute() {
if (origin == null) {
alert("Click on the map to add a start point");
return;
}
if (destination == null) {
alert("Click on the map to add an end point");
return;
}
var mode = google.maps.DirectionsTravelMode.BICYCLING;
var request = {
origin: origin,
destination: destination,
waypoints: waypoints,
travelMode: mode,
optimizeWaypoints: document.getElementById('optimize').checked,
...