JSFiddle - React, Tailwind, and code Playground
by Alex
HTML
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<div id="map-canvas"></div>
CSS
html, body, #map-canvas {
margin: 0;
padding: 0;
height: 100%;
}
JavaScript
var map, directionsService;
function renderDirections(result, polylineOpts) {
var directionsRenderer = new google.maps.DirectionsRenderer();
directionsRenderer.setMap(map);
if(polylineOpts) {
directionsRenderer.setOptions({
polylineOptions: polylineOpts
});
}
directionsRenderer.setDirections(result);
}
function requestDirections(start, end, polylineOpts) {
directionsService.route({
origin: start,
destination: end,
travelMode: google.maps.DirectionsTravelMode.DRIVING
}, function(result) {
renderDirections(result, polylineOpts);
});
}
function initialize() {
var mapOptions = {
zoom: 4,
center: new google.maps.LatLng(39.5, -98.35),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
directionsService = new google.maps.DirectionsService();
requestDirections('New York', "Los Angeles", { strokeColor:'#ff0000' });
requestDirections('Kansas City', "St. Louis", { strokeColor:'#0000ff' });
setTimeout(function() {
map.setZoom(4);
}, 2000);
}
google.maps.event.addDomListener(window, 'load', initialize);