如何使用JavaScript中的变量重定向到URL?

时间:2017-04-23 13:53:35

标签: javascript google-maps url

我需要使用Google Maps API计算两个地方之间的距离。 他们通过这个网址提供距离:

https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins=STARTING_PLACE&destinations=ENDING_PLACE&key=YOUR_KEY

我有两个HTML文本输入来输入起始位置和结束位置

<input id="origin-input" type="text" placeholder="Enter an origin location">
<input id="destination-input" type="text" placeholder="Enter a destination location">

然后我有一个JavaScript函数来创建url

function distcalc()
{
var org = document.getElementById('origin-input');
var dest = document.getElementById('destination-input');
window.location = 'https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins='+org+'&destinations='+dest+'&key=YOUR_KEY';
}

当我调用此函数时,浏览器无法在网址中找到原点和目的地参数的值。

我如何解决这个问题?

4 个答案:

答案 0 :(得分:2)

var org = document.getElementById('origin-input').value;
var dest = document.getElementById('destination-input').value;

添加.value应该有效。

答案 1 :(得分:2)

这里:

event.setArtistSupplier((name) -> {
    Artist artist = ...; // convert name to Artist (e. g. load artist based on name)
    return artist;

});

您将输入节点绑定到变量(org和dest) 而不是这样做你想要获取他们的价值:

var org = document.getElementById('origin-input');
var dest = document.getElementById('destination-input');

您可以在此处阅读更多内容:w3schools

希望这会有所帮助:)

答案 2 :(得分:1)

使用javascript获取输入值就像

一样简单

var org = document.getElementById('origin-input').value; var dest = document.getElementById('destination-input').value;

参考:https://www.w3schools.com/jsref/prop_text_value.asp

答案 3 :(得分:1)

我根据您的要求创建了此解决方案。如果您在SO中运行此功能将无法运行,因为 API_KEY 链接到另一个网址。如果您想查看live demo I posted on this link

这是您的JSON版本的替代方案,此解决方案不需要JSON处理,而是使用google.maps.DistanceMatrixService

距离是根据旅行模式计算的,对于此代码示例,我指定 DRIVING 作为运输模式。目前支持以下旅行模式according to the documentation

  

BICYCLING要求通过自行车道和骑行路线骑自行车。首选街道(目前仅在美国和一些加拿大城市提供)。

     

驾驶(默认)表示使用道路网络的标准行车路线。

     

TRANSIT通过公共交通路线请求路线。仅当请求包含API密钥时,才可以指定此选项。请参阅此类请求中可用选项的转接选项部分。

     

步行通过人行道和步行道要求步行路线。人行道(如果有的话)。

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

var origin = 'Atlanta, United States';
var destination = 'Dallas, Unated States';

originInput.value = origin;
destinationInput.value = destination;

var clicker = document.getElementById('clicker');
clicker.addEventListener('click', distcalc);

function distcalc() {
  console.log(originInput.value + ' ' + destinationInput.value)
  origin = originInput.value;
  destination = destinationInput.value;
  initMap();
}

function init() {
  console.log('The map is ready');
}

function initMap() {
  var bounds = new google.maps.LatLngBounds;
  var markersArray = [];

  var destinationIcon = 'https://chart.googleapis.com/chart?' +
    'chst=d_map_pin_letter&chld=D|FF0000|000000';
  var originIcon = 'https://chart.googleapis.com/chart?' +
    'chst=d_map_pin_letter&chld=O|FFFF00|000000';
  var map = new google.maps.Map(document.getElementById('map'), {
    center: {
      lat: 55.53,
      lng: 9.4
    },
    zoom: 10
  });

  var geocoder = new google.maps.Geocoder;

  var service = new google.maps.DistanceMatrixService;
  service.getDistanceMatrix({
    origins: [origin],
    destinations: [destination],
    travelMode: 'DRIVING',
    unitSystem: google.maps.UnitSystem.METRIC,
    avoidHighways: false,
    avoidTolls: false
  }, function(response, status) {
    if (status !== 'OK') {
      console.log('Error was: ' + status);
    } else {
      var originList = response.originAddresses;
      var destinationList = response.destinationAddresses;
      var outputDiv = document.getElementById('output');
      outputDiv.innerHTML = '';
      deleteMarkers(markersArray);

      var showGeocodedAddressOnMap = function(asDestination) {
        var icon = asDestination ? destinationIcon : originIcon;
        return function(results, status) {
          if (status === 'OK') {
            map.fitBounds(bounds.extend(results[0].geometry.location));
            markersArray.push(new google.maps.Marker({
              map: map,
              position: results[0].geometry.location,
              icon: icon
            }));
          } else {
            console.log('Geocode was not successful due to: ' + status);
          }
        };
      };

      var indexOrgn = 0;
      originList.forEach(function(orgn) {
        var results = response.rows[indexOrgn].elements;
        geocoder.geocode({
            'address': orgn
          },
          showGeocodedAddressOnMap(false));

        var indexDest = 0;
        results.forEach(function(result) {
          if (result.status === 'OK') {
            geocoder.geocode({
                'address': destinationList[indexDest]
              },
              showGeocodedAddressOnMap(true));
            outputDiv.innerHTML += orgn + ' to ' + destinationList[indexDest] +
              ': ' + result.distance.text + ' in ' +
              result.duration.text + '<br>';
            indexDest++;
          } else {
            if (result.status == 'ZERO_RESULTS') {
              console.log('ZERO_RESULTS');
              outputDiv.innerHTML += 'There are not driving paths.';
            }
          }
        });
        indexOrgn++;
      });
    }
  });
}

function deleteMarkers(markersArray) {
  for (var i = 0; i < markersArray.length; i++) {
    markersArray[i].setMap(null);
  }
  markersArray = [];
}
#right-panel {
  font-family: 'Roboto', 'sans-serif';
  line-height: 30px;
  padding-left: 10px;
}

#right-panel select,
#right-panel input {
  font-size: 15px;
}

#right-panel select {
  width: 100%;
}

#right-panel i {
  font-size: 12px;
}

html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
}

#map {
  height: 100%;
  width: 50%;
}

#right-panel {
  float: right;
  width: 48%;
  padding-left: 2%;
}

#output {
  font-size: 11px;
}
<body>
  <h1>Distance Matrix service</h1>

  <div id="right-panel">
    <div id="inputs">
      <div id="clicker">Click to Calculate Distance</div>
      <p></p>
      <input id="origin-input" type="text" placeholder="Enter an origin location">
      <input id="destination-input" type="text" placeholder="Enter a destination location">
    </div>
    <div>
      <strong>Results</strong>
    </div>
    <div id="output"></div>
  </div>
  <div id="map"></div>

  <script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBu-916DdpKAjTmJNIgngS6HL_kDIKU0aU&callback=init"></script>