簡體   English   中英

如何在JavaScript中重定向到帶有變量的網址?

[英]How do I Redirect to an url with variables in JavaScript?

我需要通過使用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';
}

當我調用此函數時,瀏覽器無法在url中找到origin和destinations參數的值。

我該如何解決?

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

添加.value應該可以。

這里:

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

您將輸入節點綁定到變量(org和dest),而不是這樣做,您想要像這樣獲取其valuet:

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

您可以在這里閱讀更多信息: w3schools

希望這可以幫助 :)

使用javascript獲取輸入值很簡單

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

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

我根據您的要求創建了此解決方案。 如果您在SO中運行此命令,則不會運行,因為API_KEY已鏈接到另一個URL 如果您想觀看現場演示,我會在此鏈接上發布

這是JSON版本的替代方法,此解決方案不需要JSON處理,而是使用google.maps.DistanceMatrixService

距離是根據“ 行駛模式”計算的,對於這個代碼示例,我將“ 駕駛”指定為運輸模式。 根據文檔,當前支持以下旅行模式:

BICYCLING要求通過自行車道和首選街道(目前僅在美國和加拿大的某些城市提供)提供騎車路線。

DRIVING(默認)表示使用道路網絡的標准行駛方向。

TRANSIT通過公共交通路線請求路線。 僅當請求包含API密鑰時才可以指定此選項。 有關此類請求中的可用選項,請參見運輸選項部分。

WALKING請求通過人行道和人行道(如果有)的步行路線。

 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> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM