im not sure what approach to take next with this, currently I have this below code which calculates the distance in miles between any 2 given locations (using long and lat), however its a straight line, and roads aren't straight... so what I want to do is calculate a distance as google maps would, for example here are some random co-ordinates:
lat1: 53.015036674593500
lat2: -2.244633982337860
long1: 52.363731052413800
long2: -1.307122733526320
and when cast into this code (JavaScript)
function distance(lat1, lon1, lat2, lon2, unit) {
var radlat1 = Math.PI * lat1 / 180
var radlat2 = Math.PI * lat2 / 180
var radlon1 = Math.PI * lon1 / 180
var radlon2 = Math.PI * lon2 / 180
var theta = lon1 - lon2
var radtheta = Math.PI * theta / 180
var dist = Math.sin(radlat1) * Math.sin(radlat2) + Math.cos(radlat1) * Math.cos(radlat2) * Math.cos(radtheta);
dist = Math.acos(dist)
dist = dist * 180 / Math.PI
dist = dist * 60 * 1.1515
if (unit == "K") { dist = dist * 1.609344 }
if (unit == "N") { dist = dist * 0.8684 }
return dist
}
var dist = distance(lata, longa, latb, longb, unit).toFixed(2);
window.alert(dist + " miles");
the value returned is 59.83 miles or there abouts... where if i was to do this in google maps:
the values range between 77.1 miles and 76.5 miles
The Question
I have the BELOW function PARTLY working to get the travel time and distance, however it randomly returns "UNDEFINED" in the alert box at the bottom, or has this error message
"Object doesn't support this action"
when using the console.log it returns this message:
"google.maps.DistanceMatrixService is not a function"
code:
var siteP = postcodearray.indexOf(screen.sitePostcode);
var StaffP = postcodearray.indexOf(screen.engineerPostcode);
sitelat = latarray[siteP];
sitelong = longarray[siteP];
stafflat = latarray[StaffP];
stafflong = longarray[StaffP];
var site = sitelat + ", " + sitelong;
var staff = stafflat + ", " + stafflong;
var distance;
var duration;
var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix({
origins: [staff],
destinations: [site],
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") {
distance = response.rows[0].elements[0].distance.text;
duration = response.rows[0].elements[0].duration.text;
//var dvDistance = document.getElementById("dvDistance");
//dvDistance.innerHTML = "";
//dvDistance.innerHTML += "Distance: " + distance + "<br />";
//dvDistance.innerHTML += "Duration:" + duration;
} else {
alert("Unable to find the distance via road.");
}
});
window.alert(distance); //UNDEFINED
Please can someone point out what I have done/am doing wrong here as im so close to getting the 2 values I need