JSFiddle - React, Tailwind, and code Playground
by witold
HTML
<!DOCTYPE html>
<html>
<head>
<title>Snap to Road - Google Maps API v3</title>
<style type="text/css">
html, body {margin: 0; width:100%; height: 100%; }
#map_canvas { position:absolute; top:50px;bottom:0;left:0;right:0;}
</style>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var map, path = [], service = new google.maps.DirectionsService(), shiftPressed = false, poly;
google.maps.event.addDomListener(document, "keydown", function() { shiftPressed = true; });
google.maps.event.addDomListener(document, "keyup", function() { shiftPressed = false; });
function Init() {
var myOptions = {
zoom: 17,
center: new google.maps.LatLng(37.2008385157313, -93.2812106609344),
mapTypeId: google.maps.MapTypeId.ROADMAP,
//mapTypeControlOptions: {
// mapTypeIds: [google.maps.MapTypeId.ROADMAP, google.maps.MapTypeId.HYBRID, //google.maps.MapTypeId.SATELLITE]
// },
disableDoubleClickZoom: true,
scrollwheel: false,
draggableCursor: "crosshair"
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
google.maps.event.addListener(map, "click", function(evt) {
if (shiftPressed || path.length == 0) {
path.push(evt.latLng);
if (path.length == 1) {
poly = new google.maps.Polyline({ map: map });
}
poly.setPath(path);
} else {
service.route({ origin: path[path.length - 1], destination: evt.latLng, travelMode: google.maps.DirectionsTravelMode.DRIVING }, function(result, status) {
if (status == google.maps.DirectionsStatus.OK) {
path = path.concat(result.routes[0].overview_path);
poly.setPath(path);
}
});
}
});
google.maps.event.addListener(map,...