2017-02-09 4 views
-1

У меня есть небольшой скрипт с API Карт Google - получите адрес от пользователя (начало и место назначения), и скрипт показывает мне гео координаты и расстояние от Google Matrix Service. Проблема в том, что: когда я нажимаю кнопку «Вычислить координаты и расстояние», мне нужно дважды щелкнуть ее - сначала показать координаты, а затем показать расстояние между ними. Может быть, вы знаете решение для этого?Необходимо дважды щелкнуть по кнопке Javascript - Google Maps

 var firstCityLocationLtd = ""; 
 
\t \t var secondCityLocationLtd = ""; 
 
     var distanceKm = ""; 
 

 
     document.getElementById('submit').addEventListener('click', function() { 
 
      initGeocoder(); 
 
     }); 
 
\t 
 
\t  function initGeocoder() { 
 
\t \t var geocoder = new google.maps.Geocoder(); 
 
     var firstCityLocation = document.getElementById('firstLocation').value; 
 
\t \t var secondCityLocation = document.getElementById('secondLocation').value; \t \t 
 
\t \t 
 
\t \t 
 
     geocoder.geocode({'address': firstCityLocation}, function(results, status) { 
 
      if (status === 'OK') { 
 
\t \t  firstCityLocationLtd = results[0].geometry.location; 
 
      document.getElementById("result1").innerHTML = firstCityLocationLtd; 
 
      } else { 
 
      alert('Error: ' + status); 
 
      } 
 
     }); 
 
\t \t 
 
\t \t geocoder.geocode({'address': secondCityLocation}, function(results, status) { 
 
      if (status === 'OK') { 
 
\t \t  secondCityLocationLtd = results[0].geometry.location; 
 
      document.getElementById("result2").innerHTML = secondCityLocationLtd; 
 
      } else { 
 
      alert('Error: ' + status); 
 
      } 
 
     }); 
 
\t \t var service = new google.maps.DistanceMatrixService; 
 
     service.getDistanceMatrix({ 
 
      origins: [firstCityLocationLtd], 
 
      destinations: [secondCityLocationLtd], 
 
      travelMode: 'DRIVING', 
 
      unitSystem: google.maps.UnitSystem.METRIC, 
 
      avoidHighways: false, 
 
      avoidTolls: false 
 
     }, function callback(response, status) { 
 
      if (status !== 'OK') { 
 
      alert('Error was: ' + status); 
 
      } else { 
 
      var originList = response.originAddresses; 
 
      var destinationList = response.destinationAddresses; 
 
      //var outputDiv = document.getElementById('output'); 
 
      //outputDiv.innerHTML = ''; 
 

 
      for (var i = 0; i < originList.length; i++) { 
 
       var results = response.rows[i].elements; 
 
       geocoder.geocode({'address': originList[i]}); 
 
       for (var j = 0; j < results.length; j++) { 
 
       geocoder.geocode({'address': destinationList[j]}); 
 
       distanceKm += results[j].distance.value; \t \t \t \t 
 
       } 
 
\t \t \t 
 
      } 
 
\t \t \t showRoadDetails(firstCityLocationLtd, secondCityLocationLtd, distanceKm); 
 
      } 
 
     }) 
 
\t \t } 
 
\t \t 
 
\t \t function showRoadDetails(start, end, distance){ 
 
\t \t \t document.getElementById("result1").innerHTML = start; 
 
\t \t \t document.getElementById("result2").innerHTML = end; 
 
\t \t \t document.getElementById("output").innerHTML = distance/1000; 
 
\t \t 
 
\t \t }
body { 
 
height:100%; 
 
} 
 

 
.jumbotron { 
 
\t margin-top:20%; 
 
\t background-color: rgba(238,238,238,0.9); 
 
} 
 

 
.game p.labels { 
 
\t margin-bottom:2px; 
 
\t font-size:14px; 
 
\t text-transform:uppercase; 
 
} 
 

 
.inputForm { 
 
\t margin-bottom:10px; 
 
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/> 
 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<nav class="navbar navbar-default navbar-fixed-top"> 
 
     <div class="container"> 
 
     <div class="navbar-header"> 
 
      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar"> 
 
      <span class="sr-only">Toggle navigation</span> 
 
      <span class="icon-bar"></span> 
 
      <span class="icon-bar"></span> 
 
      <span class="icon-bar"></span> 
 
      </button> 
 
      <a class="navbar-brand" href="#">Brand</a> 
 
     </div> 
 
     <div id="navbar" class="navbar-collapse collapse"> 
 
      <ul class="nav navbar-nav"> 
 
      <li><a href="#">1</a></li> 
 
      <li class="active"><a href="#">2</a></li> 
 
      <li><a href="#">3</a></li> 
 
      </ul> 
 
     </div><!--/.nav-collapse --> 
 
     </div> 
 
    </nav> 
 

 
    <div class="container-fluid main"> 
 
\t \t <div class="container"> 
 

 
     <!-- Main component for a primary marketing message or call to action --> 
 
     <div class="jumbotron"> 
 
\t <div class="game"> 
 
\t <div class="row"> 
 
\t <div class="col-md-4"> 
 
     <h3>Your road</h3> 
 
     
 
\t \t \t <p class="labels">From</p><input id="firstLocation" type="textbox" value="Wrocław, Poland" class="inputForm"> 
 
\t \t \t <p class="labels">To</p><input id="secondLocation" type="textbox" value="Warszawa, Poland" class="inputForm"><br/> 
 
\t \t \t 
 
\t \t </div> 
 
     </div> 
 
\t <div class="row"> 
 
\t \t <div class="col-md-12 text-center"> 
 
\t \t \t \t <input id="submit" type="button" value="Calculate it"> 
 
\t \t \t <div id="result1"></div> 
 
\t \t \t <div id="result2"></div> 
 
\t \t \t <div id="output"></div> 
 
\t \t </div> 
 
\t </div> 
 
\t \t </div> 
 
    </div> <!-- /container --> 
 
\t </div> 
 
\t </div> 
 
    <script async defer 
 
    src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBU2QyOcVY_qoDykdLzX4ywANyPbXJVfZI&callback=initGeocoder&libraries=geometry"> 
 
    </script>

+0

Почему вы называете геокодер внутри обратного вызова в distanceMatrix? Это, безусловно, усложняет вопросы (и вызов не имеет функции обратного вызова, поэтому он не делает ничего полезного, но использует вашу квоту) – geocodezip

+0

Матрица расстояния также будет работать для адреса пользователя. Есть ли причина, по которой вы используете Geocoder для получения координат и передачи их в матрицу расстояний? – Coder

+0

@geocodezip Я видел это решение на сайте API Карт Google, я не знал, что это не нужно. Благодаря! – Adrian

ответ

1

Вы должны ждать результата Геокодер услуг перед вызовом DistanceMatrixService. Вы можете сделать это с помощью Promises (взгляните на сильфоне сниппета)

// Code goes here 
 

 
var firstCityLocationLtd = ""; 
 
var secondCityLocationLtd = ""; 
 
var distanceKm = ""; 
 

 
document.getElementById('submit').addEventListener('click', function() { 
 
    initGeocoder(); 
 
}); 
 

 
function initGeocoder() { 
 
    var geocoder = new google.maps.Geocoder(); 
 
    var firstCityLocation = document.getElementById('firstLocation').value; 
 
    var secondCityLocation = document.getElementById('secondLocation').value; 
 

 
    var deferFistLocation = $.Deferred(); 
 
    var deferSecondLocation = $.Deferred(); 
 
    geocoder.geocode({ 
 
    'address': firstCityLocation 
 
    }, function(results, status) { 
 
    if (status === 'OK') { 
 
     firstCityLocationLtd = results[0].geometry.location; 
 
     document.getElementById("result1").innerHTML = firstCityLocationLtd; 
 
     deferFistLocation.resolve(); 
 

 
    } else { 
 
     deferFistLocation.reject(); 
 
     alert('Error: ' + status); 
 
    } 
 
    }); 
 

 
    geocoder.geocode({ 
 
    'address': secondCityLocation 
 
    }, function(results, status) { 
 
    if (status === 'OK') { 
 
     secondCityLocationLtd = results[0].geometry.location; 
 
     document.getElementById("result2").innerHTML = secondCityLocationLtd; 
 
     deferSecondLocation.resolve(); 
 
    } else { 
 
     deferSecondLocation.reject(); 
 
     alert('Error: ' + status); 
 
    } 
 
    }); 
 

 
    $.when(deferFistLocation, deferSecondLocation).done(function() { 
 
     var service = new google.maps.DistanceMatrixService; 
 
     service.getDistanceMatrix({ 
 
     origins: [firstCityLocationLtd], 
 
     destinations: [secondCityLocationLtd], 
 
     travelMode: 'DRIVING', 
 
     unitSystem: google.maps.UnitSystem.METRIC, 
 
     avoidHighways: false, 
 
     avoidTolls: false 
 
     }, function callback(response, status) { 
 
     if (status !== 'OK') { 
 
      alert('Error was: ' + status); 
 
     } else { 
 
      var originList = response.originAddresses; 
 
      var destinationList = response.destinationAddresses; 
 
      //var outputDiv = document.getElementById('output'); 
 
      //outputDiv.innerHTML = ''; 
 

 
      for (var i = 0; i < originList.length; i++) { 
 
      var results = response.rows[i].elements; 
 
      geocoder.geocode({ 
 
       'address': originList[i] 
 
      }); 
 
      for (var j = 0; j < results.length; j++) { 
 
       geocoder.geocode({ 
 
       'address': destinationList[j] 
 
       }); 
 
       distanceKm += results[j].distance.value; 
 
      } 
 

 
      } 
 
      showRoadDetails(firstCityLocationLtd, secondCityLocationLtd, distanceKm); 
 
     } 
 
     }) 
 
    }); 
 
} 
 

 
function showRoadDetails(start, end, distance) { 
 
    document.getElementById("result1").innerHTML = start; 
 
    document.getElementById("result2").innerHTML = end; 
 
    document.getElementById("output").innerHTML = distance/1000; 
 

 
}
body { 
 
height:100%; 
 
} 
 

 
.jumbotron { 
 
\t margin-top:20%; 
 
\t background-color: rgba(238,238,238,0.9); 
 
} 
 

 
.game p.labels { 
 
\t margin-bottom:2px; 
 
\t font-size:14px; 
 
\t text-transform:uppercase; 
 
} 
 

 
.inputForm { 
 
\t margin-bottom:10px; 
 
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/> 
 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<nav class="navbar navbar-default navbar-fixed-top"> 
 
     <div class="container"> 
 
     <div class="navbar-header"> 
 
      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar"> 
 
      <span class="sr-only">Toggle navigation</span> 
 
      <span class="icon-bar"></span> 
 
      <span class="icon-bar"></span> 
 
      <span class="icon-bar"></span> 
 
      </button> 
 
      <a class="navbar-brand" href="#">Brand</a> 
 
     </div> 
 
     <div id="navbar" class="navbar-collapse collapse"> 
 
      <ul class="nav navbar-nav"> 
 
      <li><a href="#">1</a></li> 
 
      <li class="active"><a href="#">2</a></li> 
 
      <li><a href="#">3</a></li> 
 
      </ul> 
 
     </div><!--/.nav-collapse --> 
 
     </div> 
 
    </nav> 
 

 
    <div class="container-fluid main"> 
 
\t \t <div class="container"> 
 

 
     <!-- Main component for a primary marketing message or call to action --> 
 
     <div class="jumbotron"> 
 
\t <div class="game"> 
 
\t <div class="row"> 
 
\t <div class="col-md-4"> 
 
     <h3>Your road</h3> 
 
     
 
\t \t \t <p class="labels">From</p><input id="firstLocation" type="textbox" value="Wrocław, Poland" class="inputForm"> 
 
\t \t \t <p class="labels">To</p><input id="secondLocation" type="textbox" value="Warszawa, Poland" class="inputForm"><br/> 
 
\t \t \t 
 
\t \t </div> 
 
     </div> 
 
\t <div class="row"> 
 
\t \t <div class="col-md-12 text-center"> 
 
\t \t \t \t <input id="submit" type="button" value="Calculate it"> 
 
\t \t \t <div id="result1"></div> 
 
\t \t \t <div id="result2"></div> 
 
\t \t \t <div id="output"></div> 
 
\t \t </div> 
 
\t </div> 
 
\t \t </div> 
 
    </div> <!-- /container --> 
 
\t </div> 
 
\t </div> 
 
    <script async defer 
 
    src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBU2QyOcVY_qoDykdLzX4ywANyPbXJVfZI&callback=initGeocoder&libraries=geometry"> 
 
    </script>

+0

Это решение, которое я искал, очень полезная вещь, спасибо! – Adrian

+0

добро пожаловать. Вы можете отметить как решить вопрос -> http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work –