Google maps with search engine on my site and with only one destination?

0

I would like to put on a website that I am developing a section that is "how to get there" which has a search engine, in which I would only search for the origin and the destination would always be the same. What I do not know is if there is a library or something similar already developed for this type of case.

What I want is something similar to the following link

Thank you very much. Greetings

    
asked by Jose Pinto 25.10.2017 в 20:59
source

1 answer

1

To find the source, you have to use the class Autocomplete , and to have it available you have to have loaded google maps specifying that you also want the library places

  <script src="https://maps.googleapis.com/maps/api/js?&v=3&libraries=places&key=<API KEY>"></script>

Since you know the destination , I assume you know its coordinates (lat and lng). Let's start by assuming that. We will also assume that you have a variable map that represents the instance of your map.

var map = new google.maps.Map(....),
    destino = new google.maps.LatLng(lat,lng);

Since you have the Autocomplete class , you have to instantiate it on a container element. For example:

var input = document.getElementById('input_buscador');
    autocomplete = new google.maps.places.Autocomplete(input);

To the instance of the autocompleter you have to add a listener that detects when the person has entered an address:

google.maps.event.addListener(autocomplete, 'place_changed', function () {
  var place = autocomplete.getPlace(),
      origen = place.geometry.location;
});

By now you know the origin and destination, so you can use the example in DirectionsService

var directionsService = new google.maps.DirectionsService(),
    directionsDisplay = new google.maps.DirectionsRenderer();

    directionsDisplay.setMap(map);

    directionsService.route({
      origin: origen
      destination: destino
      travelMode: 'DRIVING'
    }, function(response, status) {
      if (status === 'OK') {
        directionsDisplay.setDirections(response);
      } else {
        window.alert('Directions request failed due to ' + status);
      }
   });

I leave you the task of putting everything together and passing the variables from one side to the other. For example, building a function that expects as input the origin and destination;

    
answered by 25.10.2017 / 22:03
source