简体   繁体   中英

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. 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

I have two HTML text inputs to enter starting place and ending place

<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

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.

How I solve this??

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

add the .value should work.

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:

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

You can read more here: w3schools

Hope this helps :)

getting the values of input using javascript is as simple as

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

ref: 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 . 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 .

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).

DRIVING (default) indicates standard driving directions using the road network.

TRANSIT requests directions via public transit routes. This option may only be specified if the request includes an API key. 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).

 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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM