I'm trying to get the value from the element(?) named 'price' in this block of code into another script to use as the amount to charge on a custom Stripe Checkout page.
function CalculatedRecommendedDistance() {
CalculateDistanceforAllAlternativeRoutes();
var origin = document.getElementById('pick_up_address').value;
var destination = document.getElementById('drop_off_address').value;
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,
avoidFerries: false
}, function(response, status) {
var originList = response.originAddresses;
var destinationList = response.destinationAddresses;
var outputDiv = document.getElementById('outputRecommended');
outputDiv.innerHTML = '';
//Display distance recommended value
for (var i = 0; i < originList.length; i++) {
var results = response.rows[i].elements;
for (var j = 0; j < results.length; j++) {
outputDiv.innerHTML += originList[i] + ' to ' + destinationList[j] +
': ' + results[j].distance.text + ' in ' +
results[j].duration.text + '<br>';
//Convert driving distance to price
document.getElementById("price").innerHTML = booking_fee + base_fare + (rate_per_km * parseFloat(results[j].distance.text));
// The value that this statement produces is what I need ==> parseFloat(document.getElementById("price").innerHTML);
}
}
});
}
Or more specifically, the value that this statement produces:
parseFloat(document.getElementById("price").innerHTML);
I've tried putting the following, and many variations besides, in the same script to create a variable, but the result returned in the console is always either NaN or undefined.
var solution = document.getElementById("price").innerHTML = booking_fee + base_fare + (rate_per_km * parseFloat(results[j].distance.text));
Here's the full script:
<script>
var booking_fee = 0.50;
var base_fare = 1.50;
var rate_per_km = 1.30;
var outputDiv = document.getElementById('output');
var text = '3.14someRandomStuff';
var placeSearch, originautocomplete;
var componentForm = {
street_number: 'short_name',
route: 'long_name',
locality: 'long_name',
administrative_area_level_1: 'short_name',
country: 'long_name',
postal_code: 'short_name'
};
function initAutocomplete() {
// Create the autocomplete object, restricting the search to geographical
// location types.
originautocomplete = new google.maps.places.Autocomplete(
/** #type {!HTMLInputElement} */
(document.getElementById('pick_up_address')), {
types: ['geocode']
});
// Set initial restrict to the greater list of countries.
originautocomplete.setComponentRestrictions({
'country': ['nz']
});
destinationautocomplete = new google.maps.places.Autocomplete(
(document.getElementById('drop_off_address')), {
types: ['geocode']
});
destinationautocomplete.setComponentRestrictions({
'country': ['nz']
});
}
// Bias the autocomplete object to the user's geographical location,
// as supplied by the browser's 'navigator.geolocation' object.
function geolocate() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var geolocation = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
var circle = new google.maps.Circle({
center: geolocation,
radius: position.coords.accuracy
});
autocomplete.setBounds(circle.getBounds());
});
}
}
function CalculatedRecommendedDistance() {
CalculateDistanceforAllAlternativeRoutes();
var origin = document.getElementById('pick_up_address').value;
var destination = document.getElementById('drop_off_address').value;
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,
avoidFerries: false
}, function(response, status) {
var originList = response.originAddresses;
var destinationList = response.destinationAddresses;
var outputDiv = document.getElementById('outputRecommended');
outputDiv.innerHTML = '';
//Display distance recommended value
for (var i = 0; i < originList.length; i++) {
var results = response.rows[i].elements;
for (var j = 0; j < results.length; j++) {
outputDiv.innerHTML += originList[i] + ' to ' + destinationList[j] +
': ' + results[j].distance.text + ' in ' +
results[j].duration.text + '<br>';
//Convert driving distance to price
document.getElementById("price").innerHTML = booking_fee + base_fare + (rate_per_km * parseFloat(results[j].distance.text));
// The value that this statement produces is what I need ==> parseFloat(document.getElementById("price").innerHTML);
}
}
});
}
function CalculateDistanceforAllAlternativeRoutes() {
var directionsService = new google.maps.DirectionsService();
var start = document.getElementById('pick_up_address').value;
var end = document.getElementById('drop_off_address').value;
var method = 'DRIVING';
var request = {
origin: start,
destination: end,
travelMode: google.maps.DirectionsTravelMode[method],
provideRouteAlternatives: true,
unitSystem: google.maps.UnitSystem.METRIC,
optimizeWaypoints: true
};
directionsService.route(request, function(response, status) {
var routes = response.routes;
var distances = [];
for (var i = 0; i < routes.length; i++) {
var distance = 0;
for (j = 0; j < routes[i].legs.length; j++) {
distance = parseInt(routes[i].legs[j].distance.value) + parseInt(distance);
//for each 'leg'(route between two waypoints) we get the distance and add it to
}
//Convert into kilometer
distances.push(distance / 1000);
}
var maxDistance = distances.sort(function(a, b) {
return a - b;
});
//Display distance having highest value.
outputDiv.innerHTML = Math.round(maxDistance[routes.length - 1]) + " KM";
});
}
</script>
Many thanks for any help you're able to provide.
Related
I need to get total distance and travel time with service.getDistanceMatrix({, sum A + B + C + D = total distance.
The way that i try, only i get the first calculate, but I need to get the sum alls points for show to user total-distance
The below attach the image with sample of web
SAMPLE IMAGE
My JavaScript code
var source, destination;
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
google.maps.event.addDomListener(window, 'load', function () {
directionsDisplay = new google.maps.DirectionsRenderer({ 'draggable': true });
});
// P1
var stop;
var markers = [];
var waypts = [];
var pardas = ["6.347033,-75.559017","6.348764,-75.562970","6.334624,-75.556157"];
stop = new google.maps.LatLng(6.347033, -75.559017)
waypts.push({
location: stop,
stopover: true
});
stop = new google.maps.LatLng(6.348764, -75.562970)
waypts.push({
location: stop,
stopover: true
});
directionsDisplay = new google.maps.DirectionsRenderer({
suppressMarkers: false,
});
window.onload=function(){
function initialize() {
//P2
var mapOptions = {
zoom: 15,
//center: new google.maps.LatLng(6.3490548, -75.55802080000001),
mapTypeId: google.maps.MapTypeId.ROADMAP,
}
var map = new google.maps.Map(document.getElementById('dvMap'), mapOptions);
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById('dvPanel'));
//calcRoute();
}
source = new google.maps.LatLng(6.3490548, -75.55802080000001);
destination = new google.maps.LatLng(6.334624, -75.556157);
//P3
function calcRoute() {
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(null);
}
createMarker(source, 'source', false);
createMarker(destination, 'destination', false);
var route = response.routes[0];
for (var i = 1; i < route['legs'].length; i++) {
console.log(route['legs'][i].start_location.toString(), waypts[i - 1].location.toString());
waypts[i - 1].location = route['legs'][i].start_location
}
for (var i = 0; i < waypts.length; i++) {
createMarker(waypts[i].location, i, true);
}
}
var request = {
origin: source,
destination: destination,
waypoints: waypts,
optimizeWaypoints: true,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix({
origins: [source],
destinations: pardas,
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.METRIC,
avoidHighways: false,
avoidTolls: false
}, function (response, status) {
if (status == google.maps.DistanceMatrixStatus.OK && response.rows[0].elements[0].status != "ZERO_RESULTS") {
var distance = response.rows[0].elements[0].distance.text;
var duration = response.rows[0].elements[0].duration.text;
var dvDistance = document.getElementById("dvDistance");
dvDistance.innerHTML = "";
dvDistance.innerHTML += "Distance: " + distance + "<br />";
dvDistance.innerHTML += "Duration:" + duration;
The DirectionsService returns all the information you need to calculate the total time and distance, you don't need to use the DistanceMatrix.
Per this related question: Google Maps API: Total distance with waypoints
function computeTotalDistance(result) {
var totalDist = 0;
var totalTime = 0;
var myroute = result.routes[0];
for (i = 0; i < myroute.legs.length; i++) {
totalDist += myroute.legs[i].distance.value;
totalTime += myroute.legs[i].duration.value;
}
totalDist = totalDist / 1000.
document.getElementById("dvDistance").innerHTML = "total distance is: " + totalDist + " km<br>total time is: " + (totalTime / 60).toFixed(2) + " minutes";
}
proof of concept fiddle
code snippet:
var source, destination;
var directionsService = new google.maps.DirectionsService();
var stop;
var markers = [];
var waypts = [];
stop = new google.maps.LatLng(6.347033, -75.559017)
waypts.push({
location: stop,
stopover: true
});
stop = new google.maps.LatLng(6.348764, -75.562970)
waypts.push({
location: stop,
stopover: true
});
var directionsDisplay = new google.maps.DirectionsRenderer({
suppressMarkers: false,
});
window.onload = function() {
var mapOptions = {
zoom: 15,
//center: new google.maps.LatLng(6.3490548, -75.55802080000001),
mapTypeId: google.maps.MapTypeId.ROADMAP,
}
var map = new google.maps.Map(document.getElementById('dvMap'), mapOptions);
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById('dvPanel'));
source = new google.maps.LatLng(6.3490548, -75.55802080000001);
destination = new google.maps.LatLng(6.334624, -75.556157);
var request = {
origin: source,
destination: destination,
waypoints: waypts,
optimizeWaypoints: true,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
computeTotalDistance(response);
}
});
}
function computeTotalDistance(result) {
var totalDist = 0;
var totalTime = 0;
var myroute = result.routes[0];
for (i = 0; i < myroute.legs.length; i++) {
totalDist += myroute.legs[i].distance.value;
totalTime += myroute.legs[i].duration.value;
}
totalDist = totalDist / 1000.
document.getElementById("dvDistance").innerHTML = "total distance is: " + totalDist + " km<br>total time is: " + (totalTime / 60).toFixed(2) + " minutes";
}
html,
body {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px;
}
#dvMap {
height: 100%;
width: 50%;
margin: 0px;
padding: 0px;
}
#dvPanel {
height: 100%;
width: 50%;
margin: 0px;
padding: 0px;
float: right;
}
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div id="dvDistance"></div>
<div id="dvPanel"></div>
<div id="dvMap"></div>
Basically I want to use the Test.java to call the initMap method from index.js, in order to get the shortest distance from originlist to the destination.
However, when I run the Test.class,
it shows ReferenceError: "Google" is not defined in <eval> at line number 10.
The line is var bounds = new google.maps.LatLngBounds;
public class Test {
public static void main(String []args) throws ScriptException, IOException, NoSuchMethodException {
String[] addres = new String[3];
call("Airport Blvd, Singapore",new String[]{"50 Nanyang Ave, 639798 Singapore","21 Lower Kent Ridge Rd, 119077, Singapore","81 Victoria St, Singapore"});
}
public static void call(String s, String [] sarr)throws ScriptException, IOException, NoSuchMethodException{
StringBuilder sb = new StringBuilder();
sb.append(s+"*");
for(String element:sarr){
sb.append(element + "*");
}
System.out.println(sb.toString().substring(0, sb.toString().length()-1));
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("JavaScript");
// read script file
engine.eval(Files.newBufferedReader(Paths.get("/Projects/GetShortestDistance/index.js"), StandardCharsets.UTF_8));
Invocable inv = (Invocable) engine;
// call function from script file
System.out.println("Testing:"+ inv.invokeFunction("initMap", sb.toString()));
}
}
Here is my javascript refer to the Google Developer
function initMap(longstr) {
var bounds = new google.maps.LatLngBounds;
var markersArray = [];
// longstr ='Airport Blvd, Singapore*21 Lower Kent Ridge Rd, 119077, Singapore*50 Nanyang Ave, 639798 Singapore*80 Mandai Lake Rd, 729826*551 bukit timah road'
var array = longstr.split('*');
var destination = array[0];
var origins1 = [];
for(var i =1; i<array.length;i++){
origins1.push(array[i]);
}
var min = "";
var minAddress = null;
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: [origin1, origin2],
destinations: [destinationA, destinationB],
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.METRIC,
avoidHighways: false,
avoidTolls: false
}, function(response, status) {
if (status !== google.maps.DistanceMatrixStatus.OK) {
alert('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 === google.maps.GeocoderStatus.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 {
alert('Geocode was not successful due to: ' + status);
}
};
};
for (var i = 0; i < originList.length; i++) {
var results = response.rows[i].elements;
geocoder.geocode({'address': originList[i]},
showGeocodedAddressOnMap(false));
for (var j = 0; j < results.length; j++) {
geocoder.geocode({'address': destinationList[j]},
showGeocodedAddressOnMap(true));
outputDiv.innerHTML += originList[i] + ' to ' + destinationList[j] +
': ' + results[j].distance.text + ' in ' +
results[j].duration.text + '<br>';
if(min > parseFloat(results[j].duration.text.slice(0, -5))){
min = parseFloat(results[j].duration.text.slice(0, -5));
minAddress = originList[i];
}
}
}
}
});
return longstr;
}
function deleteMarkers(markersArray) {
for (var i = 0; i < markersArray.length; i++) {
markersArray[i].setMap(null);
}
markersArray = [];
}
The js works fine in index.html which are able to show the distance and map.
I need to display the results of a distance matrix request without geocoding. The problem is my locations are too close together and thus the resultant geocoded addresses are the same.
If I could display the results with the variable names or even the original lat/lon coordinate pairs I would be able to distinguish between the locations.
I checked the documentation for the Distance Matrix Response Elements and I did not see this functionality.
The javascript is below.
function initMap() {
var bounds = new google.maps.LatLngBounds;
var markersArray = [];
var origin1 = {lat: 37.2692332704, lng: -81.7261622975};
var origin2 = {lat: 37.2625193371, lng: -81.7183645359};
var origin3 = {lat: 37.1315998981, lng: -81.8552666961};
var destinationA = {lat: 37.1854557602, lng: -81.7946133276};
var destinationB = {lat: 37.1751720467, lng: -81.792833926};
var destinationC = {lat: 37.1595851233, lng: -81.8570206921};
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: 37.2692332704, lng: -81.7261622975},
zoom: 8
});
var geocoder = new google.maps.Geocoder;
var service = new google.maps.DistanceMatrixService;
service.getDistanceMatrix({
origins: [origin1, origin2,origin3],
destinations: [destinationA, destinationB,destinationC],
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.IMPERIAL,
avoidHighways: false,
avoidTolls: false
}, function(response, status) {
if (status !== google.maps.DistanceMatrixStatus.OK) {
alert('Error was: ' + status);
} else {
var originList = response.originAddresses;
var destinationList = response.destinationAddresses;
var outputDiv = document.getElementById('output');
outputDiv.innerHTML = '';
var showGeocodedAddressOnMap = function(asDestination) {
var icon = asDestination ? destinationIcon : originIcon;
return function(results, status) {
if (status === google.maps.GeocoderStatus.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 {
alert('Geocode was not successful due to: ' + status);
}
};
};
for (var i = 0; i < originList.length; i++) {
var results = response.rows[i].elements;
//geocoder.geocode({'address': originList[i]},
//showGeocodedAddressOnMap(false));
for (var j = 0; j < results.length; j++) {
//geocoder.geocode({'address': destinationList[j]},
//showGeocodedAddressOnMap(true));
outputDiv.innerHTML += originList[i] + ' to ' + destinationList[j] +
': ' + results[j].distance.text + ' in ' +
results[j].duration.text + '<br>';
}
}
}
});
}
Thanks in advance.
The results are returned in the order requested.
origin1 - destination1
origin1 - destination2
origin1 - destination3
origin2 - destination1
---
origin3 - destination3
You can use your original request to identify the exact coordinates used to calculate the result.
proof of concept fiddle
code snippet:
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: 37.2692332704,
lng: -81.7261622975
},
zoom: 8
});
var originArray = [origin1, origin2, origin3];
var destinationArray = [destinationA, destinationB, destinationC];
for (var i = 0; i < originArray.length; i++) {
var oMarker = new google.maps.Marker({
position: originArray[i],
map: map,
label: "" + i,
icon: originIcon
});
bounds.extend(oMarker.getPosition());
}
for (var i = 0; i < destinationArray.length; i++) {
var dMarker = new google.maps.Marker({
position: destinationArray[i],
map: map,
label: "" + i,
icon: destinationIcon
});
bounds.extend(dMarker.getPosition());
}
map.fitBounds(bounds);
var service = new google.maps.DistanceMatrixService;
service.getDistanceMatrix({
origins: originArray,
destinations: destinationArray,
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.IMPERIAL,
avoidHighways: false,
avoidTolls: false
}, function(response, status) {
if (status !== google.maps.DistanceMatrixStatus.OK) {
alert('Error was: ' + status);
} else {
var originList = response.originAddresses;
var destinationList = response.destinationAddresses;
var outputDiv = document.getElementById('output');
outputDiv.innerHTML = '';
outputHTML = "";
outputHTML += "<table border='1'><thead><tr><th>Oi</th><th>origin</th><th></th><th>Di</th><th>destination</th><th>distance</th><th>duration</th></tr></thead><tbody>";
for (var i = 0; i < originList.length; i++) {
var results = response.rows[i].elements;
for (var j = 0; j < results.length; j++) {
outputHTML += "<tr><td>O" + i + "</td><td>" + originArray[i].lat + "," + originArray[i].lng + "</td><td> to </td><td>D" + j + "</td><td>" + destinationArray[j].lat + "," + destinationArray[j].lng +
"</td><td>" + results[j].distance.text + "</td><td> in " +
results[j].duration.text + "</td></tr>";
}
}
outputHTML += "</tbody></table>";
outputDiv.innerHTML = outputHTML;
}
});
}
google.maps.event.addDomListener(window, "load", initMap);
var origin1 = {
lat: 37.2692332704,
lng: -81.7261622975
};
var origin2 = {
lat: 37.2625193371,
lng: -81.7183645359
};
var origin3 = {
lat: 37.1315998981,
lng: -81.8552666961
};
var destinationA = {
lat: 37.1854557602,
lng: -81.7946133276
};
var destinationB = {
lat: 37.1751720467,
lng: -81.792833926
};
var destinationC = {
lat: 37.1595851233,
lng: -81.8570206921
};
html,
body,
#map {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="output"></div>
<div id="map"></div>
I am trying to use getlocation's position.coords.latitude/longitude as on the input for DistanceMatrixService. When I try to use these as input variable on DistanceMatrixService it brakes, doesn’t return anything. I get error saying "TypeError: element.distance is undefined"
Here is the full code.
function getLocation() {
var options = null;
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
alert("Geolocation is not supported by this browser.");
}
}
function showPosition(position) {
Currentlat = position.coords.latitude;
Currentlon = position.coords.longitude;
var YourLatLong = "45.4049,-122.797997";
var DestLatLong1 = Currentlat + ',' + Currentlon;
var DestLatLong2 = "61.221274,-149.831545";
alert(DestLatLong1);
GoogleMapDistance(YourLatLong,DestLatLong1);
}
function GoogleMapDistance(YourLatLong,DestLatLong)
{
var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix(
{
origins: [YourLatLong],
destinations: [DestLatLong],
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.IMPERIAL,
avoidHighways: false,
avoidTolls: false
}, callback);
}
function callback(response, status)
{
if (status == google.maps.DistanceMatrixStatus.OK)
{
var origins = response.originAddresses;
var destinations = response.destinationAddresses;
for (var i = 0; i < origins.length; i++)
{
var results = response.rows[i].elements;
for (var j = 0; j < results.length; j++)
{
var distance = element.distance.text;
var duration = element.duration.text;
var ResultStr = distance + " (<i>" + duration + "</i>)";
}
}
document.getElementById("Results1").innerHTML = ResultStr;
}
}
getLocation();
I have defined couple of variables just for test purpose.
var YourLatLong = "45.4049,-122.797997";
var DestLatLong1 = Currentlat + ',' + Currentlon;
var DestLatLong2 = "61.221274,-149.831545";
alert(DestLatLong1);
When I use YourLatLong/DestLatLong2 as input it works great.
I can see the the correct data in "DestLatLong1", but when I use as input it doesn’t work. Any idea what I am doing wrong?
Thank you very much for any help.
I was able to get it done this way, by changing the call back function.
It might help someone else.
function getDistance(position){
origin = new google.maps.LatLng(parseFloat(position.coords.latitude),parseFloat(position.coords.longitude));
var mylocs = [ ["12.014675", "74.760964"], ["12.019265", "78.766434"], ["15.026083", "79.758464"] ];
for (var i=0; i < mylocs.length; i++){
destination = new google.maps.LatLng(mylocs[i][0], mylocs[i][1]);
service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix(
{
origins: [origin],
destinations: [destination],
travelMode: google.maps.TravelMode.DRIVING,
avoidHighways: false,
avoidTolls: false
},
callback(i)
);
}
}
var distance, duration;
function callback(j){
return function(response, status) {
if(status == "OK"){
distance = response.rows[0].elements[0].distance.text;
duration = response.rows[0].elements[0].duration.text;
var ResultStr = distance + " (<i>" + duration + "</i>)";
document.getElementById("Results1").innerHTML = ResultStr;
} else {
alert("Error: " + status);
}
}
}
I am using the Google Distance Matrix https://developers.google.com/maps/documentation/distancematrix/
to calculate some delivery charges. When it outputs the results in the for loop it puts them onto a new line each time, so I end up with :
1
25
26
1
Is it possible to store each result in a variable so I can call each individual result elsewhere in the code for some maths to work out costs etc, so.....
$result1
$result2
$result3
$result4
As later on I would like to do things like result1 * result3 = etc etc.
<script>
var map;
var geocoder;
var bounds = new google.maps.LatLngBounds();
var markersArray = [];
var base = new google.maps.LatLng(55.930385, -3.118425);
var start = 'Greenwich, England';
var destinationA = 'Stockholm, Sweden';
var end = new google.maps.LatLng(55.930385, -3.118425);
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';
function initialize() {
var opts = {
center: new google.maps.LatLng(55.53, 9.4),
zoom: 10,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map'), opts);
geocoder = new google.maps.Geocoder();
calculateDistances();
}
function calculateDistances() {
var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix(
{
origins: [base],
destinations: [start, end],
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.IMPERIAL,
avoidHighways: false,
avoidTolls: false
}, callback);
}
function callback(response, status) {
if (status != google.maps.DistanceMatrixStatus.OK) {
alert('Error was: ' + status);
} else {
var origins = response.originAddresses;
var destinations = response.destinationAddresses;
var outputDiv = document.getElementById('outputDiv');
outputDiv.innerHTML = '<table border="1">';
deleteOverlays();
var stringArray = ['$runinPickup','$runinDestination'];
var htmlString = '<table border="1">';
for (var i = 0; i < origins.length; i++) {
var results = response.rows[i].elements;
addMarker(origins[i], false);
for (var j = 0; j < results.length; j++) {
addMarker(destinations[j], true);
htmlString += '<tr><td>'+stringArray[j]+'</td><td>' + results[j].distance.text +'</td></tr>';
outputDiv.innerHTML += '<tr><td>'+stringArray[j]+'</td><td>' + results[j].distance.text +'</td></tr>';
}
}
htmlString += '</table>';
// outputDiv.innerHTML += '</table>';
outputDiv.innerHTML = htmlString;
// alert(htmlString);
}
}
function addMarker(location, isDestination) {
var icon;
if (isDestination) {
icon = destinationIcon;
} else {
icon = originIcon;
}
geocoder.geocode({'address': location}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
bounds.extend(results[0].geometry.location);
map.fitBounds(bounds);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
icon: icon
});
markersArray.push(marker);
} else {
alert('Geocode was not successful for the following reason: '
+ status);
}
});
}
function deleteOverlays() {
if (markersArray) {
for (i in markersArray) {
markersArray[i].setMap(null);
}
markersArray.length = 0;
}
}
</script>
Well that shouldn't be too hard. Where you output the value, e.g.
htmlString += '<tr><td>'+stringArray[j]+'</td><td>' + results[j].distance.text +'</td></tr>';
Simply add an additional line assigning that value into a variable. I'd be inclined to add them into an array which you can loop over later.
arrResults.push(results[j].distance.text);
If you're confident you always know what each value will be, then you can simply refer to them like arrResults[0] * arrResults[2]