JSFiddle - React, Tailwind, and code Playground
by Alex Azuero
HTML
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyANh0YzZG-vsBwun96VJTXO6OGqnjIpzCE"></script>
<h3>Directions between two points</h3>
<p>Start Point: <input id="start">
End Point: <input id="end">
<button>Get Directions</button><p>
<div id="map"></div>
CSS
#map {
width: 500px;
height: 350px;
}
JavaScript
// global variables
var directionsDisplay;
var directionsService;
var map;
$("button").click(sendDirectionsRequest);
google.maps.event.addDomListener(window, 'load', initialize);
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer();
directionsService = new google.maps.DirectionsService();
var mapOptions = {
zoom:8,
center: new google.maps.LatLng(-30,-50)
};
map = new google.maps.Map(document.getElementById('map'), mapOptions);
directionsDisplay.setMap(map);
// connect directions to a div on the page to show text instructions
directionsDisplay.setPanel(document.getElementById('directions'));
}
function sendDirectionsRequest(){
var start = $("#start").val();
var end = $("#end").val();
var request = {
origin:start,
destination:end,
travelMode: google.maps.TravelMode.WALKING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
console.log(response); // to inspect in the console
// grab the polyline that contains the route to draw
var route = response.routes[0].overview_polyline;
var polyOptions = {
strokeColor: '#AA4588',
strokeOpacity: .8,
strokeWeight: 8,
map: map,
path: google.maps.geometry.encoding.decodePath(route)
};
// show the polyline on the map
var poly = new google.maps.Polyline(polyOptions);
// use the property bounds to change zoom
map.fitBounds(response.routes[0].bounds);
// put markers at the end and start
var start = response.routes[0].legs[0].start_location;
var end = response.routes[0].legs[0].end_location;
var startM = new google.maps.Marker(
{position: start, map: map});
var endM = new google.maps.Marker(
{position: end, map: map});
}
});
}