Skip to content Skip to sidebar Skip to footer

Google Maps Api Directions Service Displaying Text Directions Repeating

I'm using the Google Maps JavaScript API to display routes and text directions: JS: var geocoder; var map; var search_lat; var search_lng; function initMap() { var myLatLng =

Solution 1:

  • search_lat and search_lng are null until the geocoder returns results.
  • the geocoder is asynchronous, its results don't come back until after you place the first call to the directions service.

a hint is this error in the javascript console: Uncaught TypeError: Cannot read property 'b' of null

Move the call to the directions service into the callback function for the geocoder (where/when the data exists).

Fix that, and create a single instance of the DirectionsRenderer and it works for me.

proof of concept fiddle

code snippet:

google.maps.event.addDomListener(window, "load", initMap);
var geocoder;
var map;
var search_lat;
var search_lng;
var directionsDisplay;
var directionsService;

functioninitMap() {

  var myLatLng = {
    lat: 38.5803844,
    lng: -121.50024189999999
  };

  map = new google.maps.Map(document.getElementById('map'), {
    zoom: 16,
    center: myLatLng,
  });
  directionsDisplay = new google.maps.DirectionsRenderer;
  directionsService = new google.maps.DirectionsService;


  geocoder = new google.maps.Geocoder();

  document.getElementById('search_button').addEventListener('click', function() {
    getDirectionsByAddress(geocoder, map);
  });

  var locations = []; //<?php echo json_encode($locations_array); ?>;var infowindow = new google.maps.InfoWindow();

  var marker, i;

  for (i = 0; i < locations.length; i++) {

    marker = new google.maps.Marker({
      position: new google.maps.LatLng(locations[i][5], locations[i][6]),
      animation: google.maps.Animation.DROP,
      icon: icon_image,
      map: map
    });
  }

}

functiongetDirectionsByAddress() {

  // GET THE SEARCH ADDRESSvar address = document.getElementById('address').value;
  console.log('search address: ' + address);

  geocoder.geocode({
    'address': address
  }, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
      search_lat = results[0].geometry.location.lat();
      search_lng = results[0].geometry.location.lng();
      console.log('search address coordinates: ' + search_lat + ', ' + search_lng);
      calculateAndDisplayRoute(directionsService, directionsDisplay);
    } else {
      alert("Geocode was not successful for the following reason: " + status);
    }
  });

  // INITIALIZE GOOGLE MAPS DIRECTIONS SERVICE 

  directionsDisplay.setMap(map);
  directionsDisplay.setPanel(document.getElementById('directions'));



  // CHECK THE MODE OF TRAVEL document.getElementById('mode').addEventListener('change', function() {
    calculateAndDisplayRoute(directionsService, directionsDisplay);
  });

  // CALCULATE THE DIRECTIONS BASED ON ADDRESS ENTERED AND MODE OF TRAVELfunctioncalculateAndDisplayRoute(directionsService, directionsDisplay) {
    console.log('search address coordinates: ' + search_lat + ', ' + search_lng);
    var selectedMode = document.getElementById('mode').value;
    directionsService.route({
      origin: {
        lat: search_lat,
        lng: search_lng
      },
      destination: {
        lat: 38.5803844,
        lng: -121.50024189999999
      },
      travelMode: google.maps.TravelMode[selectedMode]
    }, function(response, status) {
      if (status == google.maps.DirectionsStatus.OK) {
        directionsDisplay.setDirections(response);
      } else {
        window.alert('Directions request failed due to ' + status);
      }
    });
  }

}
html,
body,
#map {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}
<scriptsrc="https://maps.googleapis.com/maps/api/js"></script><divid="directions"><h3>Directions</h3></div><divclass="search_block"><inputtype="text"name="address"id="address"class="address"placeholder="Where are you coming from?"value="San Franscisco, CA" /></div><divclass="search_block"><selectname="travel_mode"id="mode"><option>DRIVING</option><option>WALKING</option><option>BICYCLE</option><option>TRANSIT</option></select></div><divclass="search_block"><buttonid="search_button"onclick="getDirectionsByAddress();">Search</button></div><divid="map"></div>

Post a Comment for "Google Maps Api Directions Service Displaying Text Directions Repeating"