JavaScript How to calculate roadmap distance between 2 locations of lat longs - javascript

I Strucked while calculating RoadMap distance between 2 locations of lat longs using JavaScript.
Found answer :
with this link :
var service = new google.maps.DistanceMatrixService;
service.getDistanceMatrix({
origins: [origin1],
destinations: [destinationA],
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);
return;
}
https://jsfiddle.net/c6omLvso/

Are you using the google maps javascript api? if so u can try the "Distance Matrix Service"

You can achieve your goal using the google distance matrix like this:
google.maps.event.addDomListener(window, "load", function () {
var map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(55.53, 9.4),
zoom: 10,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var origin1 = {lat: 55.93, lng: -3.118};
var origin2 = 'Greenwich, England';
var destinationA = 'Stockholm, Sweden';
var destinationB = {lat: 50.087, lng: 14.421};
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);
return;
}
var originList = response.originAddresses;
var destinationList = response.destinationAddresses;
var output = document.getElementById("output");
output.innerHTML = "";
for (var i = 0; i < originList.length; i++) {
var results = response.rows[i].elements;
for (var j = 0; j < results.length; j++) {
output.innerHTML += originList[i] + ' to ' + destinationList[j] +
': ' + results[j].distance.text + ' in ' +
results[j].duration.text + '<br>';
}
}
});
});
body {
margin: 0;
padding: 0;
font: 12px sans-serif;
}
#map {
width: 400px;
height: 400px;
}
<script src="https://maps.googleapis.com/maps/api/js?v=3"></script>
<div id="map"></div>
<div id="output"></div>
enter code here

Related

Extract element from function result in javascript

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.

How to calculate total distance and time (getDistanceMatrix)

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>

How google map api getting result ZERO RESULT

i have try to calculate distance from 2 very far locations
and I expect that google give me a ZERO RESULT error becouse not find a right way from this 2 locations, but not give me this error And i can't intercept this error
just say me:
Uncaught TypeError: Cannot read property 'text' of undefined
Now my question is, how can i intercept this error ZERO RESULT?
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 5,
center: {
lat: -15.7942357,
lng: -47.8821945
}
});
var bounds = new google.maps.LatLngBounds;
var origin1 = {lat: -33.8688197, lng: 151.209295500000058};
var destinationB = {lat: 50.087, lng: 14.421};
var geocoder = new google.maps.Geocoder;
var service = new google.maps.DistanceMatrixService;
service.getDistanceMatrix({
origins: [origin1],
destinations: [destinationB],
travelMode: 'DRIVING',
unitSystem: google.maps.UnitSystem.METRIC,
avoidHighways: false,
avoidTolls: false
}, function(response, status) {
if (status !== 'OK') {
alert('Error was: ' + status);
} else {
var originList = response.originAddresses;
var destinationList = response.destinationAddresses;
var outputDiv = document.getElementById('output');
var showGeocodedAddressOnMap = function(asDestination) {
return function(results, status) {
if (status === 'OK') {
map.fitBounds(bounds.extend(results[0].geometry.location));
} 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));
alert(results[j].distance.text);
alert(results[j].duration.text);
}
}
}
});
}
#map{
width:100%;
height:300px;
}
<html>
<head>
</head>
<body>
<div id="map"></div>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=AIzaSpQw&libraries=places&callback=initMap">
</script>
</body>
</html>
As I've mentioned about, the request is okay, hence why it returns the status, okay, you need to check each element for its status. View the code below especially the line results[j].status !== "OK"
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 5,
center: {
lat: -15.7942357,
lng: -47.8821945
}
});
var bounds = new google.maps.LatLngBounds;
var origin1 = {
lat: -33.8688197,
lng: 151.209295500000058
};
var destinationB = {
lat: 50.087,
lng: 14.421
};
var geocoder = new google.maps.Geocoder;
var service = new google.maps.DistanceMatrixService;
service.getDistanceMatrix({
origins: [origin1],
destinations: [destinationB],
travelMode: 'DRIVING',
unitSystem: google.maps.UnitSystem.METRIC,
avoidHighways: false,
avoidTolls: false
}, function(response, status) {
if (status !== 'OK') {
alert('Error was: ' + status);
} else {
var originList = response.originAddresses;
var destinationList = response.destinationAddresses;
var outputDiv = document.getElementById('output');
var showGeocodedAddressOnMap = function(asDestination) {
return function(results, status) {
if (status === 'OK') {
map.fitBounds(bounds.extend(results[0].geometry.location));
} 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));
if (results[j].status !== "OK") {
alert("Not okay");
return;
}
alert(results[j].distance.text);
alert(results[j].duration.text);
}
}
}
});
}
#map {
width: 100%;
height: 300px;
}
<html>
<head>
</head>
<body>
<div id="map"></div>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCp5RzbQjgID4oHJYe6VRGhKGXpQTGtCmw&libraries=places&callback=initMap">
</script>
</body>
</html>
Before alert do a check something like below
// check if it has results
if(results[j].status === "OK") {
// do something with result
alert(results[j].distance.text);
alert(results[j].duration.text);
}
Google Maps API Status Code.

Google Maps Javascript API - Results Formatting

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>

Uncaught InvalidValueError: unknown property origin

The code uses google maps api and draws the route between the selected points. But it is unable to calculate the distance between those two points on clicking the 'Calculate distances' button.
The error returned is:
Uncaught InvalidValueError: unknown property origin main.js:12 in the console log.
Code:
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Trying Hard Now!</title>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript" src="util.js"></script>
<style>
html, body{
height: 100%;
margin: 0px;
padding: 0px
}
#map_canvas {
height: 100%;
width: 100%;
}
#panel {
position: absolute;
height : 30%;
width: 20%
top: 30px;
left: 15%;
margin-left: -180px;
z-index: 5;
background-color: rgba(255,255,255,0);
padding: 5px;
}
#outputDiv {
font-size: 11px;
}
</style>
<script type="text/javascript">
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var infowindow;
var map;
var origin = null;
var destination = null;
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer();
var myLatlng = new google.maps.LatLng(19.1264,72.8790);
var myOptions = {
zoom: 13,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
directionsDisplay.setMap(map);
downloadUrl("xmltaxi.php", function(data) {
var markers = data.documentElement.getElementsByTagName("marker");
for (var i = 6; i < 16; i=i+8) {
var latlng = new google.maps.LatLng(parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
//var marker = createMarker(latlng);
if (i == 6)
origin = latlng;
else
destination = latlng;
}
});
//calcRoute();
}
/*function createMarker(latlng) {
var marker = new google.maps.Marker({position: latlng, map: map});
google.maps.event.addListener(marker, "click", function() {
if (infowindow) infowindow.close();
//infowindow = new google.maps.InfoWindow({content: name});
infowindow.open(map, marker);
});
return marker;
}*/
//calcRoute();
function calcRoute() {
var selectedMode = document.getElementById('mode').value;
//var start = document.getElementById('start').value;
//var end = document.getElementById('end').value;
var request = {
origin:origin,
destination:destination,
travelMode: google.maps.TravelMode[selectedMode]
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
function calculateDistances() {
var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix(
{
origin: origin,
destination: destination,
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.METRIC,
avoidHighways: false,
avoidTolls: false
}, callback);
}
function callback(response, status) {
if (status != google.maps.DistanceMatrixStatus.OK) {
alert('Error was: ' + status);
} else {
//var origin = response.originAddresses;
//var destination = response.destinationAddresses;
var outputDiv = document.getElementById('outputDiv');
outputDiv.innerHTML = '';
// deleteOverlays();
//for (var i = 0; i < origin.length; i++) {
var results = response.rows[0].elements;
//addMarker(origins[i], false);
//for (var j = 0; j < results.length; j++) {
//addMarker(destinations[j], true);
outputDiv.innerHTML += results[0].distance.text + ' in '
+ results[0].duration.text + '<br>';
//}
//}
}
}
//}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="panel">
<b>Search: </b>
<select onchange="calcRoute();">
<option></option>
<option id="mode" value="DRIVING">Route</option>
</select>
<div id="inputs">
<p><button type="button" onclick="calculateDistances();">Calculate
distances</button></p>
</div>
<div id="outputDiv"></div>
</div>
<div id="map_canvas"></div>
</body>
</html>
It may be an extremely trivial mistake, so please help me out.
The DistanceMatrixRequest has no property origin, it should be origins. Likewise destination should be destinations. And it expects to receive these as arrays, not single LatLng objects.
service.getDistanceMatrix(
{
origin: origin,
destination: destination,
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.METRIC,
avoidHighways: false,
avoidTolls: false
}, callback);
Should be
service.getDistanceMatrix(
{
origins: [origin],
destinations: [destination],
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.METRIC,
avoidHighways: false,
avoidTolls: false
}, callback);

Categories

Resources