JSFiddle - React, Tailwind, and code Playground
by bartek
HTML
<script src="http://maps.google.com/maps/api/js?sensor=false&.js"></script>
<div id="map_canvas"></div>
CSS
html, body {
margin: 0;
width:100%;
height: 100%;
}
#map_canvas {
position:absolute;
top:0px;
bottom:0;
left:0;
right:0;
}
JavaScript
var map,
path = [],
markers = [],
directionsService = new google.maps.DirectionsService(),
poly;
function addMarker(p) {
var marker = new google.maps.Marker({
position: p,
map: map,
draggable: true
});
markers.push(marker);
google.maps.event.addListener(marker, "drag", function () {
var request = {
origin: path[path.length - 1],
destination: marker.getPosition(),
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
marker.setPosition(response.routes[0].legs[0].end_location);
path = path.concat(response.routes[0].overview_path);
poly.setPath(path);
}
});
});
}
function initialize() {
var myOptions = {
zoom: 17,
center: new google.maps.LatLng(40.7143528, -74.00597310000001),
mapTypeId: google.maps.MapTypeId.ROADMAP,
draggableCursor: "crosshair"
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
google.maps.event.addListener(map, 'click', function (event) {
if (path.length == 0) {
path.push(event.latLng);
poly = new google.maps.Polyline({
map: map
});
poly.setPath(path);
addMarker(event.latLng);
} else {
var request = {
origin: path[path.length - 1],
destination: event.latLng,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
addMarker(response.routes[0].legs[0].end_location);
path = path.concat(response.routes[0].overview_path);
...