JSFiddle - React, Tailwind, and code Playground

by Lawrence Ross

HTML

<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyA5KqqUzvJyoC9msz_70ns-CdAF33N-6tM"></script>
<div id="map"></div>

CSS

html,
 body,
 #map {
   height: 100%;
   margin: 0px;
   padding: 0px
 }
 
 #panel {
   position: absolute;
   top: 5px;
   left: 50%;
   margin-left: -180px;
   z-index: 5;
   background-color: #fff;
   padding: 5px;
   border: 1px solid #999;
 }
 
 #bar {
   width: 240px;
   background-color: rgba(255, 255, 255, 0.75);
   margin: 8px;
   padding: 4px;
   border-radius: 4px;
 }
 
 #autoc {
   width: 100%;
   box-sizing: border-box;
 }

JavaScript

function initMap() {
  var mapOptions = {
    zoom: 13,
    center: {
      lat: 40.749481,
      lng: -73.974290
    }
  };
  map = new google.maps.Map(document.getElementById('map'), mapOptions);

  map.data.addGeoJson(data);

  var lines = data.features;
  for (var i = 0; i < lines.length; i++) {
    var coords = [];
    for (var j = 0; j < lines[i].geometry.coordinates.length; j++) {
      coords.push([lines[i].geometry.coordinates[j][1], lines[i].geometry.coordinates[j][0]]);
    }
    console.log('array: ', coords);
    runSnapToRoad(coords);
  }
}

// Snap a user-created polyline to roads and draw the snapped path
function runSnapToRoad(finalArray) {
  $.get('https://roads.googleapis.com/v1/snapToRoads', {
    interpolate: true,
    key: apiKey,
    path: finalArray.join('|')
  }, function(data) {
    processSnapToRoadResponse(data);
    drawSnappedPolyline();
  });
}

// Store snapped polyline returned by the snap-to-road service.
function processSnapToRoadResponse(data) {
  snappedCoordinates = [];
  placeIdArray = [];
  for (var i = 0; i < data.snappedPoints.length; i++) {
    var latlng = new google.maps.LatLng(
      data.snappedPoints[i].location.latitude,
      data.snappedPoints[i].location.longitude);
    snappedCoordinates.push(latlng);
    placeIdArray.push(data.snappedPoints[i].placeId);
  }
}

// Draws the snapped polyline (after processing snap-to-road response).
function drawSnappedPolyline() {
  var snappedPolyline = new google.maps.Polyline({
    path: snappedCoordinates,
    strokeColor: 'blue',
    strokeWeight: 3
  });
  snappedPolyline.setMap(map);
  polylines.push(snappedPolyline);
}

$(window).load(initMap);
var data = {
  "type": "FeatureCollection",
  "features": [{
    "type": "Feature",
    "properties": {},
    "geometry": {
      "type": "LineString",
      "coordinates": [
        [-73.97056102752686, 40.74811853855757],
        [-73.96944522857666, 40.74953279908402],
        [-73.96798610687256, 40.75135341202851],
       ...