javascript - Google Maps API Directions Service Displaying Text Directions Repeating -


i'm using google maps javascript api display routes , text directions:

js:

var geocoder; var map; var search_lat; var search_lng;  function initmap() {      var mylatlng = {         lat: 38.5803844,          lng: -121.50024189999999     };      map = new google.maps.map(document.getelementbyid('map'), {       zoom: 16,       center: mylatlng,     });      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;      (i = 0; < 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         });     }  }  function getdirectionsbyaddress() {      // search address      var 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);         } else {             alert("geocode not successful following reason: " + status);         }     });      // initialize google maps directions service       var directionsdisplay = new google.maps.directionsrenderer;     var directionsservice = new google.maps.directionsservice;      directionsdisplay.setmap(map);    directionsdisplay.setpanel(document.getelementbyid('directions'));      calculateanddisplayroute(directionsservice, directionsdisplay);      // check mode of travel       document.getelementbyid('mode').addeventlistener('change', function() {       calculateanddisplayroute(directionsservice, directionsdisplay);     });      // calculate directions based on address entered , mode of travel      function calculateanddisplayroute(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 ' + status);           }         });     }  } 

i'm having trouble getdirectionsbyaddress function. when search location , click "search button" first time, nothing happens. on second click of "search button", route drawn on map , directions displayed, directions displayed twice (it seems directions calculated on first click, on second click being displayed). if search third time, third set of directions tacked on , repeats on , over.

it seems need reset lat , lng values during each search. tried:

delete search_lat; delete search_lng; 

inside , @ end of calculateanddisplayroute function. no luck.

html:

<div id="map"></div>  <div id="directions">      <h3>directions</h3>  </div>  <div class="search_block">      <input type="text" name="address" id="address" class="address" placeholder="where coming from?" />  </div>  <div class="search_block">          <select name="travel_mode" id="mode">         <option>driving</option>         <option>walking</option>         <option>bicycle</option>         <option>transit</option>     </select>  </div>  <div class="search_block">      <button id="search_button" onclick="getdirectionsbyaddress();">search</button>  </div> 

here picture of repeating directions. want 1 set of directions show each search

question: how can make directions refreshed single set of coordinates during each search?

  • search_lat , search_lng null until geocoder returns results.
  • the geocoder asynchronous, results don't come until after place first call directions service.

a hint error in javascript console: uncaught typeerror: cannot read property 'b' of null

move call directions service callback function geocoder (where/when data exists).

fix that, , create single instance of directionsrenderer , works 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;    function initmap() {      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;      (i = 0; < 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      });    }    }    function getdirectionsbyaddress() {      // search address      var 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 not successful following reason: " + status);      }    });      // initialize google maps directions service       directionsdisplay.setmap(map);    directionsdisplay.setpanel(document.getelementbyid('directions'));          // check mode of travel       document.getelementbyid('mode').addeventlistener('change', function() {      calculateanddisplayroute(directionsservice, directionsdisplay);    });      // calculate directions based on address entered , mode of travel      function calculateanddisplayroute(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 ' + status);        }      });    }    }
html,  body,  #map {    height: 100%;    width: 100%;    margin: 0px;    padding: 0px  }
<script src="https://maps.googleapis.com/maps/api/js"></script>  <div id="directions">      <h3>directions</h3>    </div>    <div class="search_block">      <input type="text" name="address" id="address" class="address" placeholder="where coming from?" value="san franscisco, ca" />    </div>    <div class="search_block">      <select name="travel_mode" id="mode">      <option>driving</option>      <option>walking</option>      <option>bicycle</option>      <option>transit</option>    </select>    </div>    <div class="search_block">      <button id="search_button" onclick="getdirectionsbyaddress();">search</button>    </div>  <div id="map"></div>


Comments

Popular posts from this blog

javascript - Slick Slider width recalculation -

jsf - PrimeFaces Datatable - What is f:facet actually doing? -

angular2 services - Angular 2 RC 4 Http post not firing -