-1

I have this piece of code wich asks origin city and destination city as user input, it makes autocomplete and calculates time and km distance between 2 points , I would like to change it as instead of only accept city it could accept adresses and places to (with autocomplete). note that in order to use it you need to provide your own google api.

here is the snippet https://codepen.io/luiscunha96/pen/GRKNYpw

 var myLatLng = { lat: 38.736946, lng: -9.142685 };
var mapOptions = {
    center: myLatLng,
    zoom: 1,
    mapTypeId: google.maps.MapTypeId.ROADMAP
};

// Hide result box
document.getElementById("output").style.display = "none";

// Create/Init map
var map = new google.maps.Map(document.getElementById('google-map'), mapOptions);

// Create a DirectionsService object to use the route method and get a result for our request
var directionsService = new google.maps.DirectionsService();

// Create a DirectionsRenderer object which we will use to display the route
var directionsDisplay = new google.maps.DirectionsRenderer();

// Bind the DirectionsRenderer to the map
directionsDisplay.setMap(map);


// Define calcRoute function
function calcRoute() {
    //create request
    var request = {
        origin: document.getElementById("location-1").value,
        destination: document.getElementById("location-2").value,
        travelMode: google.maps.TravelMode.DRIVING,
        unitSystem: google.maps.UnitSystem.METRIC
    }

    // Routing
    directionsService.route(request, function (result, status) {
        if (status == google.maps.DirectionsStatus.OK) {

            //Get distance and time            

            $("#output").html("<div class='result-table'> Driving distance: " + result.routes[0].legs[0].distance.text + ".<br />Duration: " + result.routes[0].legs[0].duration.text + ".</div>");
            document.getElementById("output").style.display = "block";

            //display route
            directionsDisplay.setDirections(result);
        } else {
            //delete route from map
            directionsDisplay.setDirections({ routes: [] });
            //center map in London
            map.setCenter(myLatLng);

            //Show error message           

            alert("Can't find road! Please try again!");
            clearRoute();
        }
    });

}

// Clear results

function clearRoute(){
    document.getElementById("output").style.display = "none";
    document.getElementById("location-1").value = "";
    document.getElementById("location-2").value = "";
    directionsDisplay.setDirections({ routes: [] });

}

// Create autocomplete objects for all inputs

var options = {
    types: ['(cities)']
    //types: ['(regions)']
    //types: ['postal-code']
}


var input1 = document.getElementById("location-1");
var autocomplete1 = new google.maps.places.Autocomplete(input1, options);

var input2 = document.getElementById("location-2");
var autocomplete2 = new google.maps.places.Autocomplete(input2, options);
deio da
  • 3
  • 1

1 Answers1

0

Remove the types: '(cities)'. Per the documentation, put that value in the type field (types is deprecated):

The (cities) type collection instructs the Places service to return results that match locality or administrative_area_level_3.

Remove the type (or types) from the options to get both establishments and addresses.

// Create autocomplete objects for all inputs
var options = {};

var input1 = document.getElementById("location-1");
var autocomplete1 = new google.maps.places.Autocomplete(input1, options);

var input2 = document.getElementById("location-2");
var autocomplete2 = new google.maps.places.Autocomplete(input2, options);

proof of concept fiddle

screenshot of resulting map

code snippet:

var myLatLng = {
  lat: 38.736946,
  lng: -9.142685
};
var mapOptions = {
  center: myLatLng,
  zoom: 1,
  mapTypeId: google.maps.MapTypeId.ROADMAP
};

// Hide result box
document.getElementById("output").style.display = "none";

// Create/Init map
var map = new google.maps.Map(document.getElementById('google-map'), mapOptions);

// Create a DirectionsService object to use the route method and get a result for our request
var directionsService = new google.maps.DirectionsService();

// Create a DirectionsRenderer object which we will use to display the route
var directionsDisplay = new google.maps.DirectionsRenderer();

// Bind the DirectionsRenderer to the map
directionsDisplay.setMap(map);


// Define calcRoute function
function calcRoute() {
  //create request
  var request = {
    origin: document.getElementById("location-1").value,
    destination: document.getElementById("location-2").value,
    travelMode: google.maps.TravelMode.DRIVING,
    unitSystem: google.maps.UnitSystem.METRIC
  }

  // Routing
  directionsService.route(request, function(result, status) {
    if (status == google.maps.DirectionsStatus.OK) {

      //Get distance and time            

      $("#output").html("<div class='result-table'> Driving distance: " + result.routes[0].legs[0].distance.text + ".<br />Duration: " + result.routes[0].legs[0].duration.text + ".</div>");
      document.getElementById("output").style.display = "block";

      //display route
      directionsDisplay.setDirections(result);
    } else {
      //delete route from map
      directionsDisplay.setDirections({
        routes: []
      });
      //center map in London
      map.setCenter(myLatLng);

      //Show error message           

      alert("Can't find road! Please try again!");
      clearRoute();
    }
  });

}

// Clear results

function clearRoute() {
  document.getElementById("output").style.display = "none";
  document.getElementById("location-1").value = "";
  document.getElementById("location-2").value = "";
  directionsDisplay.setDirections({
    routes: []
  });

}

// Create autocomplete objects for all inputs
var options = {};

var input1 = document.getElementById("location-1");
var autocomplete1 = new google.maps.places.Autocomplete(input1, options);

var input2 = document.getElementById("location-2");
var autocomplete2 = new google.maps.places.Autocomplete(input2, options);
* {
  margin: auto;
  box-sizing: border-box;
}

html {
  font-size: 62.5%;
  height: 100%;
}

body {
  height: 100%;
  background-image: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  background-size: cover;
  background-position: top;
  font-family: "Lato", sans-serif;
  font-weight: 400;
  line-height: 1.7;
  color: #000;
}


/* Clearfix */

.row::after {
  content: "";
  display: table;
  clear: both;
}

.header {
  display: block;
  font-size: 1.2rem;
  font-weight: 400;
  padding: 1rem;
  margin: 2rem auto;
}

.header h1 {
  color: #19244e;
  text-align: center;
  text-transform: uppercase;
  text-decoration: none;
}

.container {
  width: 65vw;
  height: 100%;
  border-radius: 1rem;
  background-color: #fff;
  padding: 2rem;
}

.location-label {
  font-size: 1.6rem;
  float: left;
  width: 25%;
  margin-top: .6rem;
}

.location-input {
  float: left;
  width: 75%;
  margin-top: .6rem;
}

.location-input::-webkit-input-placeholder {
  color: #465caa;
}

::-moz-placeholder {
  color: #465caa;
}

::-ms-placeholder {
  color: #465caa;
}

::placeholder {
  color: #465caa;
}

.button {
  background-image: linear-gradient(to top, #48c6ef 0%, #6f86d6 100%);
  text-transform: uppercase;
  text-decoration: none;
  outline: none;
  color: white;
  padding: 1.2rem 2.2rem;
  border: none;
  border-radius: 1rem;
  cursor: pointer;
  float: right;
  margin-bottom: 1rem;
  margin-right: .5rem;
  transition: ease-in-out .1s;
}

.button:hover {
  background-image: linear-gradient(-225deg, #A445B2 0%, #D41872 52%, #FF0066 100%);
  transform: scale(1.015);
  transition: ease-in .1s;
}

.result-table {
  font-size: 1.6rem;
  border-collapse: collapse;
  border-spacing: 0;
  width: 100%;
  height: 10rem;
  /* Animation */
  animation-name: moveIn;
  animation-duration: 1s;
  animation-timing-function: ease-out;
}

.container-map {
  width: 100%;
  height: 20rem;
  margin: 1rem auto;
}


/* Animations */

@keyframes moveIn {
  0% {
    opacity: 0;
    transform: translateY(-.5rem);
  }
  100% {
    opacity: 1;
    transform: translateY(0);
  }
}
<div class="header">
  <div class="row">
    <h1>Calculate driving distance between two cities</h1>
  </div>
</div>

<div class="container">
  <form>
    <!-- Location 1 -->
    <div class="row">
      <div class="location-label">
        <label>Origin: </label>
      </div>
      <div class="location-input">
        <input type="text" id="location-1" name="origin" placeholder="Enter a start location...">
      </div>
    </div>
    <!-- Location 2 -->
    <div class="row">
      <div class="location-label">
        <label>Destination: </label>
      </div>
      <div class="location-input">
        <input type="text" id="location-2" name="destination" placeholder="Enter a last location...">
      </div>
    </div>

    <!-- Submit button -->
    <div class="row">
      <button class="button" type="button" onclick="clearRoute();">Clear</button>
      <button class="button" type="button" onclick="calcRoute();">Submit</button>
    </div>

    <!-- Stats table -->
    <div id="output" class="result-table"></div>
  </form>

  <div class="container-map" id="google-map"></div>
</div>

<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&libraries=places"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
geocodezip
  • 158,664
  • 13
  • 220
  • 245