简体   繁体   English

如何在JavaScript中重定向到带有变量的网址?

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

I need to calculate the distance between two places by using google maps API. 我需要通过使用Google Maps API计算两个地方之间的距离。 they provide the distance by this url : 他们通过以下网址提供距离:

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

I have two HTML text inputs to enter starting place and ending place 我有两个HTML文本输入可输入开始位置和结束位置

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

Then I have a JavaScript fuction to create the url 然后我有一个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';
}

when I call this function, browser can't find values for origins and destinations parameters in the url. 当我调用此函数时,浏览器无法在url中找到origin和destinations参数的值。

How I solve this?? 我该如何解决?

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

add the .value should work. 添加.value应该可以。

Here: 这里:

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

You are binding the input nodes to the variables(org and dest) Instead of doing this you want to fetch thier valuest just like this: 您将输入节点绑定到变量(org和dest),而不是这样做,您想要像这样获取其valuet:

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

You can read more here: w3schools 您可以在这里阅读更多信息: w3schools

Hope this helps :) 希望这可以帮助 :)

getting the values of input using javascript is as simple as 使用javascript获取输入值很简单

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

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

I created this solution based on your request. 我根据您的要求创建了此解决方案。 If you run this in SO will not run because the API_KEY is linked to another URL . 如果您在SO中运行此命令,则不会运行,因为API_KEY已链接到另一个URL If you want to see the live demo I posted on this link . 如果您想观看现场演示,我会在此链接上发布

This is an alternative to your JSON version, this solution doesn't require a JSON handling instead I'm using the google.maps.DistanceMatrixService . 这是JSON版本的替代方法,此解决方案不需要JSON处理,而是使用google.maps.DistanceMatrixService

The distance is calculated based on the Travel Modes , for this code sample I specified DRIVING as the transportation mode. 距离是根据“ 行驶模式”计算的,对于这个代码示例,我将“ 驾驶”指定为运输模式。 The following travel modes are currently supported according to the documentation : 根据文档,当前支持以下旅行模式:

BICYCLING requests bicycling directions via bicycle paths & preferred streets (currently only available in the US and some Canadian cities). BICYCLING要求通过自行车道和首选街道(目前仅在美国和加拿大的某些城市提供)提供骑车路线。

DRIVING (default) indicates standard driving directions using the road network. DRIVING(默认)表示使用道路网络的标准行驶方向。

TRANSIT requests directions via public transit routes. TRANSIT通过公共交通路线请求路线。 This option may only be specified if the request includes an API key. 仅当请求包含API密钥时才可以指定此选项。 See the section on transit options for the available options in this type of request. 有关此类请求中的可用选项,请参见运输选项部分。

WALKING requests walking directions via pedestrian paths & sidewalks (where available). 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