如何动态加载路由计算?

时间:2019-07-12 11:23:31

标签: javascript jquery ajax google-maps google-maps-api-3

动态加载Google地图路线时,我需要帮助。我在未定义的控制台中看到错误:

Uncaught ReferenceError: calcularRuta is not defined
    at HTMLInputElement.onclick (index.html:1)

我尝试更改有问题的位置(calculateRuta()),但什么也没做。这是唯一失败的事情,所以我知道其余的都是正确的。 我也尝试过以不同的方式加载它,但是仍然出现相同的错误。

这是地图的功能,最后我放置了功能calcularRuta(),这是给我带来错误的原因。

var gMapsLoaded = false;
window.gMapsCallback = function() {
  gMapsLoaded = true;
  $(window).trigger('gMapsLoaded');
}

window.loadGoogleMaps = function() {
  if (gMapsLoaded) return window.gMapsCallback();
  var script_tag = document.createElement('script');
  script_tag.setAttribute("type", "text/javascript");
  script_tag.setAttribute("src", "https://maps.googleapis.com/maps/api/js?key=AIzaSyBDaeWicvigtP9xPv919E-RNoxfvC-Hqik&callback=gMapsCallback");
  (document.getElementsByTagName("head")[0] || document.documentElement).appendChild(script_tag);
}

$(document).ready(function() {
      var mapa;
      var mostrar_direcciones;

      var servicios_rutas;

      function initialize() {
        servicios_rutas = new google.maps.DirectionsService();
        mostrar_direcciones = new google.maps.DirectionsRenderer();
        var milatlng = new google.maps.LatLng(40.4450489, -3.6103049)
        var mapOptions = {
          zoom: 12,
          center: milatlng,
          mapTypeId: google.maps.MapTypeId.ROADMAP

        };
        map = new google.maps.Map(document.getElementById('mapa'), mapOptions);

        mostrar_direcciones.setMap(mapa);
        mostrar_direcciones.setPanel(document.getElementById("ruta"));

        var marker = new google.maps.Marker({
          position: milatlng,
          map: map,
        });

      }

      function calcularRuta() {
        var partida = document.getElementById("partida").value;
        var destino = document.getElementById("destino").value;
        var opciones = {
          origin: partida,
          destination: destino,
          travelMode: google.maps.DirectionsTravelMode.DRIVING
          //indicamos en este caso que hacemos el viaje en coche/moto
        };

        servicios_rutas.route(opciones, function(response, status) {
          if (status == google.maps.DirectionsStatus.OK) {
            mostrar_direcciones.setDirections(response);
          }
        });
      }

      $(window).bind('gMapsLoaded', initialize);
      window.loadGoogleMaps();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="contenedorMapa">
  <h2>ENCUÉNTRAME AQUÍ</h2>
  <div id="mapa">

    <p>Cargando, espere por favor...</p>

  </div>
  <div id="ruta" style="width: 100px; height: 100px; background-color: green;"></div>
  <input type="text" id="partida" name="partida">
  <input type="destino" id="destino" name="destino">
  <input type="button" name="button" id="button" value="aaaaaaaaaaa" onclick="calcularRuta()">
</div>

1 个答案:

答案 0 :(得分:0)

您的calcularRuta函数不在全局范围内(它在$(document).ready(function() {匿名函数的范围内)。

要用作HTML onclick侦听器函数,它必须在全局范围内。

最简单的解决方法,删除$(document).ready(function() {

proof of concept fiddle

enter image description here

代码段:

var gMapsLoaded = false;
var map;
window.gMapsCallback = function() {
  gMapsLoaded = true;
  $(window).trigger('gMapsLoaded');
}

window.loadGoogleMaps = function() {
  if (gMapsLoaded) return window.gMapsCallback();
  var script_tag = document.createElement('script');
  script_tag.setAttribute("type", "text/javascript");
  script_tag.setAttribute("src", "https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=gMapsCallback");
  (document.getElementsByTagName("head")[0] || document.documentElement).appendChild(script_tag);
}

var mapa;
var mostrar_direcciones;

var servicios_rutas;

function initialize() {
  servicios_rutas = new google.maps.DirectionsService();
  mostrar_direcciones = new google.maps.DirectionsRenderer();
  var milatlng = new google.maps.LatLng(40.4450489, -3.6103049)
  var mapOptions = {
    zoom: 12,
    center: milatlng,
    mapTypeId: google.maps.MapTypeId.ROADMAP

  };
  mapa = new google.maps.Map(document.getElementById('mapa'), mapOptions);

  mostrar_direcciones.setMap(mapa);
  mostrar_direcciones.setPanel(document.getElementById("ruta"));

  var marker = new google.maps.Marker({
    position: milatlng,
    map: map,
  });

}

function calcularRuta() {
  var partida = document.getElementById("partida").value;
  var destino = document.getElementById("destino").value;
  var opciones = {
    origin: partida,
    destination: destino,
    travelMode: google.maps.DirectionsTravelMode.DRIVING
    //indicamos en este caso que hacemos el viaje en coche/moto
  };

  servicios_rutas.route(opciones, function(response, status) {
    if (status == google.maps.DirectionsStatus.OK) {
      mostrar_direcciones.setDirections(response);
    }
  });
}

$(window).bind('gMapsLoaded', initialize);
window.loadGoogleMaps();
/* Always set the map height explicitly to define the size of the div
 * element that contains the map. */

#mapa {
  height: 100%;
}


/* Optional: Makes the sample page fill the window. */

html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="contenedorMapa" style="height:100%; width:100%;">
  <h2>ENCUÉNTRAME AQUÍ</h2>
  <div id="mapa">

    <p>Cargando, espere por favor...</p>

  </div>
  <div id="ruta" style="width: 100px; height: 100px; background-color: green;"></div>
  <input type="text" id="partida" name="partida" value="New York, NY">
  <input type="destino" id="destino" name="destino" value="Newark, NJ">
  <input type="button" name="button" id="button" value="aaaaaaaaaaa" onclick="calcularRuta()">
</div>