Replace google maps maker A and B in the "Place autocomplete and Directions" example

Asked

Viewed 68 times

0

I’m studying the google maps api, and I’m trying to personalize this example from google itself, but I’ve already read the documentation on Google marketing but without success when trying to replace the "A" and "B" markers of this example. How can I replace the two markers "A" and "B" in this example of google maps with javascript? Thanks in advance.

    <!DOCTYPE html>
<html>
  <head>
    <title>Place Autocomplete and Directions</title>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <style>
      /* Always set the map height explicitly to define the size of the div
       * element that contains the map. */
      #map {
        height: 100%;
      }
      /* Optional: Makes the sample page fill the window. */
      html, body {
        height: 100%;
        margin: 0;
        padding: 0;
      }
      .controls {
        margin-top: 10px;
        border: 1px solid transparent;
        border-radius: 2px 0 0 2px;
        box-sizing: border-box;
        -moz-box-sizing: border-box;
        height: 32px;
        outline: none;
        box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
      }

      #origin-input,
      #destination-input {
        background-color: #fff;
        font-family: Roboto;
        font-size: 15px;
        font-weight: 300;
        margin-left: 12px;
        padding: 0 11px 0 13px;
        text-overflow: ellipsis;
        width: 200px;
      }

      #origin-input:focus,
      #destination-input:focus {
        border-color: #4d90fe;
      }

      #mode-selector {
        color: #fff;
        background-color: #4d90fe;
        margin-left: 12px;
        padding: 5px 11px 0px 11px;
      }

      #mode-selector label {
        font-family: Roboto;
        font-size: 13px;
        font-weight: 300;
      }

    </style>
  </head>
  <body>
    <div style="display: none">
        <input id="origin-input" class="controls" type="text"
            placeholder="Enter an origin location">

        <input id="destination-input" class="controls" type="text"
            placeholder="Enter a destination location">

        <div id="mode-selector" class="controls">
          <input type="radio" name="type" id="changemode-walking" checked="checked">
          <label for="changemode-walking">Walking</label>

          <input type="radio" name="type" id="changemode-transit">
          <label for="changemode-transit">Transit</label>

          <input type="radio" name="type" id="changemode-driving">
          <label for="changemode-driving">Driving</label>
        </div>
    </div>

    <div id="map"></div>

    <script>
// This example requires the Places library. Include the libraries=places
// parameter when you first load the API. For example:
// <script
// src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places">

function initMap() {
  var map = new google.maps.Map(document.getElementById('map'), {
    mapTypeControl: false,
    center: {lat: -33.8688, lng: 151.2195},
    zoom: 13
  });

  new AutocompleteDirectionsHandler(map);
}

/**
 * @constructor
 */
function AutocompleteDirectionsHandler(map) {
  this.map = map;
  this.originPlaceId = null;
  this.destinationPlaceId = null;
  this.travelMode = 'WALKING';
  this.directionsService = new google.maps.DirectionsService;
  this.directionsDisplay = new google.maps.DirectionsRenderer;
  this.directionsDisplay.setMap(map);

  var originInput = document.getElementById('origin-input');
  var destinationInput = document.getElementById('destination-input');
  var modeSelector = document.getElementById('mode-selector');

  var originAutocomplete = new google.maps.places.Autocomplete(originInput);
  // Specify just the place data fields that you need.
  originAutocomplete.setFields(['place_id']);

  var destinationAutocomplete =
      new google.maps.places.Autocomplete(destinationInput);
  // Specify just the place data fields that you need.
  destinationAutocomplete.setFields(['place_id']);

  this.setupClickListener('changemode-walking', 'WALKING');
  this.setupClickListener('changemode-transit', 'TRANSIT');
  this.setupClickListener('changemode-driving', 'DRIVING');

  this.setupPlaceChangedListener(originAutocomplete, 'ORIG');
  this.setupPlaceChangedListener(destinationAutocomplete, 'DEST');

  this.map.controls[google.maps.ControlPosition.TOP_LEFT].push(originInput);
  this.map.controls[google.maps.ControlPosition.TOP_LEFT].push(
      destinationInput);
  this.map.controls[google.maps.ControlPosition.TOP_LEFT].push(modeSelector);
}

// Sets a listener on a radio button to change the filter type on Places
// Autocomplete.
AutocompleteDirectionsHandler.prototype.setupClickListener = function(
    id, mode) {
  var radioButton = document.getElementById(id);
  var me = this;

  radioButton.addEventListener('click', function() {
    me.travelMode = mode;
    me.route();
  });
};

AutocompleteDirectionsHandler.prototype.setupPlaceChangedListener = function(
    autocomplete, mode) {
  var me = this;
  autocomplete.bindTo('bounds', this.map);

  autocomplete.addListener('place_changed', function() {
    var place = autocomplete.getPlace();

    if (!place.place_id) {
      window.alert('Please select an option from the dropdown list.');
      return;
    }
    if (mode === 'ORIG') {
      me.originPlaceId = place.place_id;
    } else {
      me.destinationPlaceId = place.place_id;
    }
    me.route();
  });
};

AutocompleteDirectionsHandler.prototype.route = function() {
  if (!this.originPlaceId || !this.destinationPlaceId) {
    return;
  }
  var me = this;

  this.directionsService.route(
      {
        origin: {'placeId': this.originPlaceId},
        destination: {'placeId': this.destinationPlaceId},
        travelMode: this.travelMode
      },
      function(response, status) {
        if (status === 'OK') {
          me.directionsDisplay.setDirections(response);
        } else {
          window.alert('Directions request failed due to ' + status);
        }
      });
};

    </script>
    <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places&callback=initMap"
        async defer></script>
  </body>
</html>

Example link working

1 answer

1


To Google Maps API is enough rich and complex, then I suggest you know plenty javascript and love reading documentation. With this I strongly suggest that "start at the beginning", which the link is this. Let’s have the answer to your question...

Assuming you have one intermediate/advanced level in javascript and in the Google Maps API, I will provide a basic code for the understanding of how "BOOKMARK".

There is no mystery in creating a simple marker (Marker), they depend only on the LAT(LATITUDE) and LNG(LONGITUDE)).

What is Latitude?

Latitude is the angle between the plane of the equator and the reference surface. The latitude is north and south of the equator, between 90º south, at the South Pole and 90º north, at the North Pole.

What is longitude?

Longitude, sometimes represented by the Greek letter λ (lambda), describes the location of a place on Earth measured in degrees, from zero to 180 due east or west, from the Greenwich meridian.

How I get them through the API?

As I said, you need to read carefully from the beginning of the documentation, because in this case you need a lot of knowledge of several different "sectors" from within the Google Maps API, but one of the ways to get it is in this link (Place Autocomplete).

Now, giving example in algorithm...

I will use two (2) coordinates for two (2) different locations, that they have been withdrawn of this link for the purpose of rapid prototyping of the algorithm below:

Location (1) - BAIRRO TIJUCA, RIO DE JANEIRO:

var myLatLngTijuca = {lat: -20.514690, lng: -54.664059};

Location (2) - BAIRRO BARRA, RIO DE JANEIRO:

var myLatLngBarra = {lat: -22.996309, lng: -43.400200};

Now that we already have the two coordinates for the two locations, you must create two(2) Simple Marker to be displayed on them, and how to do this? We need to create a new object of the type Marker and add some properties to this object, you can read more about it at this link.

var marker = new google.maps.Marker({
    position: AQUI VOCÊ DEVE INSERIR O OBJETO COM A LAT E LNG,
    map: AQUI VOCÊ DEVE INSERIR O OBJETO DO MAPA,
    title: AQUI VOCÊ DEVE INSERIR UM TÍTULO PARA O MARKER'
});

Now, to finalize our basic prototyping code, we will generally develop the same:

  function initMap() {
    var myLatLng = {lat: -25.363, lng: 131.044};
    var myLatLngTijuca = {lat: -20.514690, lng: -54.664059};
    var myLatLngBarra = {lat: -22.996309, lng: -43.400200};

    var map = new google.maps.Map(document.getElementById('map'), {
      zoom: 4,
      center: myLatLng
    });

    var marker = new google.maps.Marker({
      position: myLatLngTijuca ,
      map: map,
      title: 'TIJUCA!'
    });

    var marker = new google.maps.Marker({
      position: myLatLngBarra ,
      map: map,
      title: 'BARRA!'
    });
  }
  • I understood and very good the explanation! I managed to execute your example successfully. But the question is to put this inside the code of the example "Place autocomplete and Directions" google maps replacing the markers "A" and "B" that appear on the map. Putting markers on the map I can according to your example, but I can’t replace the markers "A" and "B" from the example "Place autocomplete and Directions" (From the question code).

  • @Cristy then, it was as I said, unfortunately this Api is complex, and you will have to learn it all.. Because the "Place Autocomplete." is a junction of several other techniques of google maps, for example the "Bounds", then you would have to know what this is also among dozens of other things, understand?

  • I understand. I will continue reading the documentation.

  • 1

    @Cristy starts with the link I left in the answer, doing it slowly and testing each function and property to see how it works.. There is a documentation area that tells you what each object, class does as well.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.