Uncaught InvalidValueError: unknown property origin - javascript

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

Related

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.

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

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

How do I get Google Maps Directions API to choose the correct Airport?

When I ask google for directions, both "MMU" and "MMU Airport" work fine, but when I use the API it keeps going to MLU airport... what gives?
Code:
var directionService = new google.maps.DirectionsService;
var geocoder = new google.maps.Geocoder;
directionService.route({
origin: $('#selAirport').val() + ' Airport',
destination: $('#selZIPZone').val(),
travelMode: google.maps.TravelMode.DRIVING
},
function(response, status) {
console.log(response, status);
...
dev-tools photo showing it received "MMU Airport" as the origin, but set the Start Address to MLU Airport instead
That looks like a data problem. The directions service/geocoder recognize Morristown Municipal Airport, but not MMU. I reported that through the Google Maps "report an error" (lower right hand corner of the map), not sure if it will be accepted.
code snippet:
var geocoder;
var map;
function initialize() {
var map = new google.maps.Map(
document.getElementById("map_canvas"), {
center: new google.maps.LatLng(37.4419, -122.1419),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var directionService = new google.maps.DirectionsService();
var directionsDisplay = new google.maps.DirectionsRenderer({
map: map
});
directionService.route({
origin: 'Morristown Airport',
destination: "Florham Park , NJ",
travelMode: google.maps.TravelMode.DRIVING
},
function(response, status) {
if (status === google.maps.DirectionsStatus.OK) {
console.log(response);
directionsDisplay.setDirections(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
}
google.maps.event.addDomListener(window, "load", initialize);
html,
body,
#map_canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div id="map_canvas"></div>
Taking into account your last comment it looks like you have an autocomplete of places library. In this case you can retrieve the place ID from the autocomplete element and pass it to directions service. This way you will be sure that directions service is working with an exact choice of the user.
Please look at this example and use autocomplete to search your route:
http://jsbin.com/xuyisem/edit?html,output
code snippet:
var directionsDisplay;
var directionsService;
var map;
var placeId1, placeId2;
function initialize() {
directionsService = new google.maps.DirectionsService();
directionsDisplay = new google.maps.DirectionsRenderer({
draggable: true
});
var mapOptions = {
zoom:10,
center: new google.maps.LatLng(32.5101466,-92.0436835)
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
directionsDisplay.setMap(map);
var inputFrom = document.getElementById('from');
var autocompleteFrom = new google.maps.places.Autocomplete(inputFrom, {});
autocompleteFrom.bindTo('bounds', map);
autocompleteFrom.addListener('place_changed', function() {
var place = autocompleteFrom.getPlace();
placeId1 = place.place_id;
});
var inputTo = document.getElementById('to');
var autocompleteTo = new google.maps.places.Autocomplete(inputTo, {});
autocompleteTo.bindTo('bounds', map);
autocompleteTo.addListener('place_changed', function() {
var place = autocompleteTo.getPlace();
placeId2 = place.place_id;
});
}
function calcRoute() {
if (!placeId1) {
alert("Please select origin");
return;
}
if (!placeId2) {
alert("Please select destination");
return;
}
var start = {
placeId: placeId1
};
var end = {
placeId: placeId2
};
var request = {
origin: start,
destination:end,
travelMode: google.maps.TravelMode.DRIVING,
provideRouteAlternatives: false
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
html,
body,
#map-canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<input type="text" name="from" id="from" placeholder="Select origin" />
<input type="text" name="to" id="to" placeholder="Select destination" />
<input type="button" name="calcroute" value="Get route" onclick="calcRoute();return false;" />
<div id="map-canvas"></div>
<script async defer src="https://maps.googleapis.com/maps/api/js?v=3&libraries=places&callback=initialize"></script>

How to get all latitudes and longitudes from source place to destination place

I want to get all the latitudes and longitudes from google map.
For Example : suppose i have enter lat and lon of source and destination and the path is drawn on the map as below:
so now i want all the lat and lon between this A source and B destination. and that all lat and lon have to store in the database.
so when i track my car and that car are not moving on this path/way then at that it will fire some action like send me email etc.
i am developing with asp.net c#.
so how can i get the all the lat and lon ?
i am using below script
<script>
function initialize() {
var map = new google.maps.Map(document.getElementById('map_canvas'), {
zoom: 8,
center: new google.maps.LatLng(22.304634, 73.161070),
mapTypeId: google.maps.MapTypeId.ROADMAP
}),
directions = new google.maps.DirectionsService(),
displayer = new google.maps.DirectionsRenderer({
draggable: true
});
displayer.setMap(map);
directions.route({
origin: new google.maps.LatLng(22.304634, 73.161070),
destination: new google.maps.LatLng(23.022242, 72.548844),
travelMode: google.maps.DirectionsTravelMode.DRIVING
}, function (result) {
displayer.setDirections(result);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
google.maps.event.addListener(displayer, 'directions_changed', some_method);
</script>
You have to loop over the overview_path property of the google.maps.DirectionsRoute object. Then create your object (or just serialize overview_path) to send it to the server and stock it in the data base.
Chek out this example for how to loop over the overview_path:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Geocoding service</title>
<style>
html, body, #map-canvas { height: 100%; min-height: 600px; min-width: 700px; margin: 0px; padding: 0px }
#map-canvas { height: 50%; }
#panel { position: absolute; top: 5px; left: 50%; margin-left: -180px; z-index: 5; background-color: #fff; padding: 5px; border: 1px solid #999; }
</style>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
</head>
<body>
<div id="panel">
<label>Origin
<input id="origin" type="text" value="">
</label>
<label>Destination
<input id="destination" type="text" value="">
</label>
<input type="button" value="GetDirections" onclick="calcRoute()">
</div>
<div id="map-canvas"></div>
<div id="vertex-container">
<label>Points</label>
<ul id="vertex">
</ul>
</div>
<script type="text/javascript">
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer();
var mapOptions = {
zoom: 7,
center: new google.maps.LatLng(48.85727000, 2.35238)
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
directionsDisplay.setMap(map);
}
function calcRoute() {
var start = document.getElementById('origin').value;
var end = document.getElementById('destination').value;
var request = {
origin: start,
destination: end,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
if (response.routes && response.routes.length > 0) {
var routes = response.routes;
for (var j = 0; j < routes.length; j++) {
var points = routes[j].overview_path;
var ul = document.getElementById("vertex");
for (var i = 0; i < points.length; i++) {
var li = document.createElement('li');
li.innerHTML = getLiText(points[i]);
ul.appendChild(li);
}
}
}
}
});
}
function getLiText(point) {
var lat = point.lat(),
lng = point.lng();
return "lat: " + lat + " lng: " + lng;
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</body>
</html>

calculate distance before submitting form

I am trying to calculate a distance from my workplace to a destination that varies.
I have a form with 3 fields:
date
destination
distance
I would like get the distance by just typing in the destination address - this should happen before I submit the form (for best user experience).
I am trying to use google maps api but can't get the input in the destination field into the js code var DestinationA. I am also using the "onchange" to get the inout before submitting.
My next step is then to get the distance result into the form field distance.
Any help is much appreciated.
Here is my test-site: www.e-kl.dk/s/_kort.asp
Here is my code:
<%#LANGUAGE="VBSCRIPT" CODEPAGE="1252"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>test</title>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script>
<style>
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#map-canvas {
height: 200px;
width: 200px;
position: absolute;
left: 3px;
top: 92px;
z-index: 1;
}
#content-pane {
float:right;
width:48%;
padding-left: 2%;
}
#outputDiv {
font-size: 11px;
height: 50px;
width: 876px;
position: absolute;
left: 0px;
}
</style>
</head>
<script>
var map;
var geocoder;
var bounds = new google.maps.LatLngBounds();
var markersArray = [];
var origin1 = 'Gl. Hovedgade 10, Denmark';
// var destinationA = 'ballerup'; //THIS WORKS but I need the user input....
// var destinationA = document.form1.destination; //did not work
// var addressField = document.getElementById('destination'); //did not work
// var destinationA = addressField.value;
// var destinationA = $("#destination").val(); //did not work
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.876, 12.5),
zoom: 15
};
map = new google.maps.Map(document.getElementById('map-canvas'), opts);
geocoder = new google.maps.Geocoder();
}
function calculateDistances() {
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
}, 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 = '';
deleteOverlays();
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);
outputDiv.innerHTML += 'Tegnestuen' + ' til ' + destinations[j]
+ ': ' + results[j].distance.text;
}
}
}
}
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() {
for (var i = 0; i < markersArray.length; i++) {
markersArray[i].setMap(null);
}
markersArray = [];
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
<body>
<div id="outputDiv">
<form id="form1" name="form1" method="post" action="">
date
<input name="date" type="text" value="" id="date"/>
destination
<input name="destination" type="text" value="" id="destination" onchange="calculateDistances();"/>
distance
<input name="distance" type="text" value="" id="distance" />
</form>
</div>
<div id="map-canvas"></div>
</body>
</html>
You can't access document.getElementById('destination') until the onload event has fired. Best to get that value in the calculateDistances function (when it is needed):
function calculateDistances() {
var addressField = document.getElementById('destination'); //did not work
var destinationA = addressField.value;
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
}, callback);
}
working fiddle

Categories

Resources