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>
I want to calculate driving distance between given latitudes and longitudes. On my project I'm displaying markers on road. And what I want is to calculate distance between those markers not all of the routes. Can some one explain to me how can I calculate that distance?
I know I should work on DistanceMatrixService but I couldn't figure out how to work on it.
Where I put Markers:
var pointsArray = response.routes[0].overview_path;
for (var i = 0; i < pointsArray.length; i++) {
var marker = new google.maps.Marker ({
position:pointsArray[i],
draggable:false,
map:map,
flat:true
});
}
If the pointsArray comes from the directions service, you can do something like this:
var pointsArray = response.routes[0].overview_path;
for (var i = 0; i < pointsArray.length; i++) {
var marker = new google.maps.Marker({
position: pointsArray[i],
draggable: false,
map: map,
flat: true
});
markers.push(marker);
google.maps.event.addListener(marker, 'click', (function (marker, i) {
return function (evt) {
var html = "marker #" + i + "<br />";
if (i != (markers.length - 1)) {
html += "<a href='javascript: google.maps.event.trigger(markers[" + (i + 1) + "],\"click\");'>next</a> dist:" + google.maps.geometry.spherical.computeDistanceBetween(markers[i].getPosition(), markers[i + 1].getPosition()).toFixed(2) + " meters<br />";
}
if (i !== 0) {
html += "<a href='javascript: google.maps.event.trigger(markers[" + (i - 1) + "],\"click\");'>prev</a> dist:" + google.maps.geometry.spherical.computeDistanceBetween(markers[i].getPosition(), markers[i - 1].getPosition()).toFixed(2) + " meters";
}
infowindow.setContent(html);
infowindow.open(map, marker);
}
})(marker, i))
}
Another option would be to get the distances out of the directions response.
code snippet:
var infowindow = new google.maps.InfoWindow();
var markers = [];
function initMap() {
var directionsService = new google.maps.DirectionsService();
var directionsDisplay = new google.maps.DirectionsRenderer();
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 7,
center: {
lat: 37.4419,
lng: -122.1419
}
});
directionsDisplay.setMap(map);
calculateAndDisplayRoute(new google.maps.LatLng(37.4419, -122.1419), new google.maps.LatLng(37.447597, -122.159582),
directionsService, directionsDisplay, map);
}
function calculateAndDisplayRoute(start, end, directionsService, directionsDisplay, map) {
directionsService.route({
origin: start,
destination: end,
travelMode: google.maps.TravelMode.DRIVING
}, function(response, status) {
if (status === google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(null);
}
markers = [];
var pointsArray = response.routes[0].overview_path;
for (var i = 0; i < pointsArray.length; i++) {
var marker = new google.maps.Marker({
position: pointsArray[i],
draggable: false,
map: map,
flat: true
});
markers.push(marker);
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function(evt) {
var html = "marker #" + i + "<br />";
if (i != (markers.length - 1)) {
html += "<a href='javascript: google.maps.event.trigger(markers[" + (i + 1) + "],\"click\");'>next</a> dist:" + google.maps.geometry.spherical.computeDistanceBetween(markers[i].getPosition(), markers[i + 1].getPosition()).toFixed(2) + " meters<br />";
}
if (i !== 0) {
html += "<a href='javascript: google.maps.event.trigger(markers[" + (i - 1) + "],\"click\");'>prev</a> dist:" + google.maps.geometry.spherical.computeDistanceBetween(markers[i].getPosition(), markers[i - 1].getPosition()).toFixed(2) + " meters";
}
infowindow.setContent(html);
infowindow.open(map, marker);
}
})(marker, i))
}
} else {
alert('Directions request failed due to ' + status);
}
});
}
google.maps.event.addDomListener(window, "load", initMap);
html,
body,
#map {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div id="map"></div>
I want to move 2 markers on the same google map but i can't find the problem in my code. I can move the 1st marker but i can't move the second one, it is possible to move two markers at the same time on the same map?
How i can move 2 markers at the same time?
<!DOCTYPE html>
<html>
<head>
<title>HTML5</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=650, user-scalable=yes">
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script>
<style>
html, body {
height: 100%;
margin: 0;
}
#mapcanvas {
height: 97%;
}
#info {
width: auto;
margin: 5px;
height: 3%;
}
</style>
<script>
var map;
var latLonList = [
{ lat: 45.54169245190391, lon: -73.53928729891777 },
{ lat: 45.54173002374242, lon: -73.53945091366768 },
{ lat: 45.541743173879944, lon: -73.53949382901192 },
{ lat: 45.541790138631775, lon: -73.53962525725365 },
{ lat: 45.541844617694764, lon: -73.53980496525764 },
{ lat: 45.54189721811927, lon: -73.5399578511715 },
{ lat: 45.54193666840536, lon: -73.5401026904583 },
{ lat: 45.54198363299557, lon: -73.5402475297451 },
{ lat: 45.542068169159045, lon: -73.5405720770359 },
{ lat: 45.54214706946365, lon: -73.54082688689232 },
{ lat: 45.54222221250792, lon: -73.54105487465858 },
{ lat: 45.54226729828628, lon: -73.54119434952736 },
{ lat: 45.54235746973452, lon: -73.54123994708061 },
{ lat: 45.542543447889805, lon: -73.5411112010479 },
{ lat: 45.542718154081314, lon: -73.54099586606026 },
{ lat: 45.54289661683465, lon: -73.54089394211769 },
{ lat: 45.54298866582284, lon: -73.54103341698647 },
{ lat: 45.54308071466031, lon: -73.54133650660515 },
{ lat: 45.543180277518914, lon: -73.5413445532322 },
{ lat: 45.54330050413203, lon: -73.54127749800682 },
{ lat: 45.54337001002545, lon: -73.54111924767494 }
]
$(document).ready(function () {
var mapOptions = {
zoom: 13,
center: new google.maps.LatLng(43, 0),
};
map = new google.maps.Map($('#mapcanvas')[0], mapOptions);
//*********************************************************************
// Add the layer showing the inventory
//*********************************************************************
var marker = null;
var markerTwo = null;
var i = 0;
var j = 1;
function autoUpdate() {
navigator.geolocation.getCurrentPosition(function (position) {
var newPoint = new google.maps.LatLng(latLonList[i].lat, latLonList[i].lon);
var secondPoint = new google.maps.LatLng(latLonList[j].lat, latLonList[j].lon);
if (marker) {
// Marker already created - Move it
marker.setPosition(newPoint);
}
else {
// Marker does not exist - Create it
marker = new google.maps.Marker({
position: newPoint,
map: map,
draggable: true
});
}
if (markerTwo) {
// Marker already created - Move it
markerTwo.setPosition(secondPoint);
}
else {
// Marker does not exist - Create it
markerTwo = new google.maps.Marker({
position: secondPoint,
map: map,
draggable: true
});
}
map.setCenter(newPoint);
});
// Call the autoUpdate() function every 5 seconds
setTimeout(autoUpdate, 3000);
if (i == 20) {
i = 0
}
else {
i++;
}
}
if (j == 19) {
j = 0
}
else {
j++;
}
autoUpdate();
});//end document ready
</script>
</head>
<body>
<div id="info">trying to update location every 5 secs - new latitude longitude : <span id="coordinates"></span></div>
<div id="mapcanvas">
</div>
</body>
</html>
the answer:
map=new google.maps.Map($('#mapcanvas')[0], mapOptions);
//*********************************************************************
// Add the layer showing the inventory
//*********************************************************************
var marker = null;
var marker2 = null ;
var i = 0;
function autoUpdate() {
navigator.geolocation.getCurrentPosition(function(position, pos) {
//var newPoint = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
var newPoint = new google.maps.LatLng(latLonList[i].lat, latLonList[i].lon);
var myLatlng = new google.maps.LatLng(latLonList[i+1].lat, latLonList[i+1].lon);
if (marker2) {
// Marker already created - Move it
marker2.setPosition(myLatlng);
}
else {
marker2 = new google.maps.Marker({
position: myLatlng,
map: map,
title: 'Client 2'
});
}
if (marker) {
// Marker already created - Move it
marker.setPosition(newPoint);
}
else {
// Marker does not exist - Create it
marker = new google.maps.Marker({
position: newPoint,
map: map,
title: 'Client 1'
});
}
// Center the map on the new position
map.setCenter(myLatlng);
});
// Call the autoUpdate() function every 5 seconds
setTimeout(autoUpdate, 3000);
if (i == 19)
i = 0
else
i++;
}
autoUpdate();
});//end document ready
http://geekonjava.blogspot.in/2014/10/how-to-make-animated-moving-marker-on.html
Follow This link It Will Helps You
html{height:100%;}
body{height:100%;margin:0px;font-family: Helvetica,Arial;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<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>GeekOnJava: Directions Complex</title>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type ="text/javascript" src="http://www.geocodezip.com/scripts/v3_epoly.js"></script>
<script type="text/javascript">
var map;
var directionDisplay;
var directionsService;
var stepDisplay;
var position;
var marker = [];
var polyline = [];
var poly2 = [];
var poly = null;
var startLocation = [];
var endLocation = [];
var timerHandle = [];
var speed = 0.000005, wait = 1;
var infowindow = null;
var myPano;
var panoClient;
var nextPanoId;
var startLoc = new Array();
startLoc[0] = 'rio claro, trinidad';
startLoc[1] = 'preysal, trinidad';
startLoc[2] = 'san fernando, trinidad';
startLoc[3] = 'couva, trinidad';
var endLoc = new Array();
endLoc[0] = 'princes town, trinidad';
endLoc[1] = 'tabaquite, trinidad';
endLoc[2] = 'mayaro, trinidad';
endLoc[3] = 'arima, trinidad';
var Colors = ["#FF0000", "#00FF00", "#0000FF"];
function initialize() {
infowindow = new google.maps.InfoWindow(
{
size: new google.maps.Size(150,50)
});
var myOptions = {
zoom: 16,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
address = 'Trinidad and Tobago'
geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': address}, function(results, status) {
map.fitBounds(results[0].geometry.viewport);
});
// setRoutes();
}
function createMarker(latlng, label, html) {
// alert("createMarker("+latlng+","+label+","+html+","+color+")");
var contentString = '<b>'+label+'</b><br>'+html;
var marker = new google.maps.Marker({
position: latlng,
map: map,
title: label,
zIndex: Math.round(latlng.lat()*-100000)<<5
});
marker.myname = label;
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(contentString);
infowindow.open(map,marker);
});
return marker;
}
function setRoutes(){
var directionsDisplay = new Array();
for (var i=0; i< startLoc.length; i++){
var rendererOptions = {
map: map,
suppressMarkers : true,
preserveViewport: true
}
directionsService = new google.maps.DirectionsService();
var travelMode = google.maps.DirectionsTravelMode.DRIVING;
var request = {
origin: startLoc[i],
destination: endLoc[i],
travelMode: travelMode
};
directionsService.route(request,makeRouteCallback(i,directionsDisplay[i]));
}
function makeRouteCallback(routeNum,disp){
if (polyline[routeNum] && (polyline[routeNum].getMap() != null)) {
startAnimation(routeNum);
return;
}
return function(response, status){
if (status == google.maps.DirectionsStatus.OK){
var bounds = new google.maps.LatLngBounds();
var route = response.routes[0];
startLocation[routeNum] = new Object();
endLocation[routeNum] = new Object();
polyline[routeNum] = new google.maps.Polyline({
path: [],
strokeColor: '#FFFF00',
strokeWeight: 3
});
poly2[routeNum] = new google.maps.Polyline({
path: [],
strokeColor: '#FFFF00',
strokeWeight: 3
});
// For each route, display summary information.
var path = response.routes[0].overview_path;
var legs = response.routes[0].legs;
disp = new google.maps.DirectionsRenderer(rendererOptions);
disp.setMap(map);
disp.setDirections(response);
//Markers
for (i=0;i<legs.length;i++) {
if (i == 0) {
startLocation[routeNum].latlng = legs[i].start_location;
startLocation[routeNum].address = legs[i].start_address;
// marker = google.maps.Marker({map:map,position: startLocation.latlng});
marker[routeNum] = createMarker(legs[i].start_location,"start",legs[i].start_address,"green");
}
endLocation[routeNum].latlng = legs[i].end_location;
endLocation[routeNum].address = legs[i].end_address;
var steps = legs[i].steps;
for (j=0;j<steps.length;j++) {
var nextSegment = steps[j].path;
var nextSegment = steps[j].path;
for (k=0;k<nextSegment.length;k++) {
polyline[routeNum].getPath().push(nextSegment[k]);
//bounds.extend(nextSegment[k]);
}
}
}
}
polyline[routeNum].setMap(map);
//map.fitBounds(bounds);
startAnimation(routeNum);
} // else alert("Directions request failed: "+status);
}
}
var lastVertex = 1;
var stepnum=0;
var step = 50; // 5; // metres
var tick = 100; // milliseconds
var eol= [];
//----------------------------------------------------------------------
function updatePoly(i,d) {
// Spawn a new polyline every 20 vertices, because updating a 100-vertex poly is too slow
if (poly2[i].getPath().getLength() > 20) {
poly2[i]=new google.maps.Polyline([polyline[i].getPath().getAt(lastVertex-1)]);
// map.addOverlay(poly2)
}
if (polyline[i].GetIndexAtDistance(d) < lastVertex+2) {
if (poly2[i].getPath().getLength()>1) {
poly2[i].getPath().removeAt(poly2[i].getPath().getLength()-1)
}
poly2[i].getPath().insertAt(poly2[i].getPath().getLength(),polyline[i].GetPointAtDistance(d));
} else {
poly2[i].getPath().insertAt(poly2[i].getPath().getLength(),endLocation[i].latlng);
}
}
//----------------------------------------------------------------------------
function animate(index,d) {
if (d>eol[index]) {
marker[index].setPosition(endLocation[index].latlng);
return;
}
var p = polyline[index].GetPointAtDistance(d);
//map.panTo(p);
marker[index].setPosition(p);
updatePoly(index,d);
timerHandle[index] = setTimeout("animate("+index+","+(d+step)+")", tick);
}
//-------------------------------------------------------------------------
function startAnimation(index) {
if (timerHandle[index]) clearTimeout(timerHandle[index]);
eol[index]=polyline[index].Distance();
map.setCenter(polyline[index].getPath().getAt(0));
poly2[index] = new google.maps.Polyline({path: [polyline[index].getPath().getAt(0)], strokeColor:"#FFFF00", strokeWeight:3});
timerHandle[index] = setTimeout("animate("+index+",50)",2000); // Allow time for the initial map display
}
//----------------------------------------------------------------------------
</script>
</head>
<body onload="initialize()">
<div id="tools">
<button onclick="setRoutes();">Start</button>
</div>
<div id="map_canvas" style="width:100%;height:100%;"></div>
<script src="http://www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-162157-1";
urchinTracker();
</script>
</body>
</html>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no"/>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>GeekOnJava: Directions Complex</title>
<style>
html
{
height:100%;
}
body
{
height:100%;
margin:0px;
font-family: Helvetica,Arial;
}
</style>
<script type="text/javascript">
var map;
var geocoder;
var marker;
var people = new Array();
var people2 = new Array();
var latlng;
var infowindow;
var lats=6.9271;
var markersz = new google.maps.Marker;
var markers2 = new google.maps.Marker;
$(document).ready(function() {
var mapOptions = {
center: new google.maps.LatLng(7.8731, 80.7718), // Coimbatore = (11.0168445, 76.9558321)
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
ViewCustInGoogleMap();
});
window.setInterval(function(){
ViewCustInGoogleMap();
}, 5000);
function ViewCustInGoogleMap() {
//deleting the previous set mark on the map
markersz.setMap(null);
markers2.setMap(null);
lats = lats+0.01;
// Get data from database. It should be like below format or you can alter it.
var data = '[{ "DisplayText": "DULA TEST<br/><h1>HHH</h1><a href=https://www.google.lk?st=kk target=_blank>CLICK</a>", "ADDRESS": "Coimbatore-641042", "LatitudeLongitude": "'+lats+',79.8612", "MarkerId": "Customer"}]';
people = JSON.parse(data);
for (var i = 0; i < people.length; i++) {
markersz = setMarker(people[i]);
}
//-----------------------------------------------------------------------------------------------------------------
//getting lats and longs from the controller
$.ajax({
type: 'post',
url: 'http://localhost/GPS/Login/latsAndLongs',
data: "",
dataType: 'json',
success: function(response) {
people2 = JSON.parse(response);
for (var i = 0; i < people2.length; i++) {
//setting the current mark and returning the mark object so that it can be deleted in the next iteration
markers2=setMarker2(people2[i]);
}
}
});
//var data2 = '[{ "DisplayText": "DULA TEST2", "ADDRESS": "Coimbatore-641042", "LatitudeLongitude": "6.5854,79.9607", "MarkerId": "Seller"}]';
}
//---------------------------------------------------------------------
function setMarker(people) {
geocoder = new google.maps.Geocoder();
infowindow = new google.maps.InfoWindow();
if ((people["LatitudeLongitude"] == null) || (people["LatitudeLongitude"] == 'null') || (people["LatitudeLongitude"] == '')) {
geocoder.geocode({ 'address': people["Address"] }, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
latlng = new google.maps.LatLng(results[0].geometry.location.lat(), results[0].geometry.location.lng());
marker = new google.maps.Marker({
position: latlng,
map: map,
draggable: false,
html: people["DisplayText"],
icon: "https://cdn4.iconfinder.com/data/icons/iconsimple-places/512/pin_1-128.png"
});
//marker.setPosition(latlng);
//map.setCenter(latlng);
google.maps.event.addListener(marker, 'click', function(event) {
infowindow.setContent(this.html);
infowindow.setPosition(event.latLng);
infowindow.open(map, this);
});
}
else {
//alert(people["DisplayText"] + " -- " + people["Address"] + ". This address couldn't be found");
}
});
}
else {
marker = new google.maps.Marker;
var latlngStr = people["LatitudeLongitude"].split(",");
var lat = parseFloat(latlngStr[0]);
var lng = parseFloat(latlngStr[1]);
latlng = new google.maps.LatLng(lat, lng);
marker = new google.maps.Marker({
position: latlng,
map: map,
draggable: false, // cant drag it
html: people["DisplayText"], // Content display on marker click
icon: "http://www.myiconfinder.com/uploads/iconsets/256-256-a5485b563efc4511e0cd8bd04ad0fe9e.png" // Give ur own image
});
//marker.setMap(null);
//marker.setPosition(latlng);
//map.setCenter(latlng);
google.maps.event.addListener(marker, 'click', function(event) {
infowindow.setContent(this.html);
infowindow.setPosition(event.latLng);
infowindow.open(map, this);
});
return marker;
}
}
//-----------------------------
function setMarker2(people) {
geocoder = new google.maps.Geocoder();
infowindow = new google.maps.InfoWindow();
if ((people["LatitudeLongitude"] == null) || (people["LatitudeLongitude"] == 'null') || (people["LatitudeLongitude"] == '')) {
geocoder.geocode({ 'address': people["Address"] }, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
latlng = new google.maps.LatLng(results[0].geometry.location.lat(), results[0].geometry.location.lng());
marker = new google.maps.Marker({
position: latlng,
map: map,
draggable: false,
html: people["DisplayText"],
icon: "https://cdn4.iconfinder.com/data/icons/iconsimple-places/512/pin_1-128.png"
});
//marker.setPosition(latlng);
//map.setCenter(latlng);
google.maps.event.addListener(marker, 'click', function(event) {
infowindow.setContent(this.html);
infowindow.setPosition(event.latLng);
infowindow.open(map, this);
});
}
else {
alert(people["DisplayText"] + " -- " + people["Address"] + ". This address couldn't be found");
}
});
}
else {
var latlngStr = people["LatitudeLongitude"].split(",");
var lat = parseFloat(latlngStr[0]);
var lng = parseFloat(latlngStr[1]);
latlng = new google.maps.LatLng(lat, lng);
marker = new google.maps.Marker({
position: latlng,
map: map,
draggable: false, // cant drag it
html: people["DisplayText"], // Content display on marker click
icon: "https://cdn4.iconfinder.com/data/icons/iconsimple-places/512/pin_1-128.png" // Give ur own image
});
//marker.setPosition(latlng);
//map.setCenter(latlng);
google.maps.event.addListener(marker, 'click', function(event) {
infowindow.setContent(this.html);
infowindow.setPosition(event.latLng);
infowindow.open(map, this);
});
}
return marker;
}
</script>
Move a list of marker and zoom particular marker while iterating.
1. Get Imei_no.
2. Push imei_no in variable.
3. Create Map.
4. Get details based on imei_no.
5. Create Maker.
6. Push maker in test.
7. Delete marker.
8. Return to autoUpdate.
Live Tracking Done by Sureshchan...
if (true) {
var listimei = [];
$scope.listimei = [];
$http.get('school/transport/scroute/viewIMEI?imeiNo=' + routeid).success(function(response) {
//1.
console.log(response);
if (response.viewRoute == 0) {
logger.logError("IMEI No. not available");
$state.go("app.school.scTransport.scVehicleTracking.list");
} else {
//brown
$scope.brown = response.viewRoute[0].emptveh;
//2.
for (var b = 0; b < response.viewRoute.length; b++) {
listimei.push(response.viewRoute[b].imeiNo);
}
//3.
var mapOptions = {
center: new google.maps.LatLng(13.0037, 80.1476),
zoom: 17,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('viewallmap'), mapOptions);
var infoWindow = new google.maps.InfoWindow;
var test = [];
var marker;
function autoUpdate() {
if (marker == null){
$scope.locData = [];
var y = 0;
var g = 0;
var r = 0;
var n = 0;
$http.get('school/transport/scroute/getListImei?imeiNo=' + listimei).success(function(response) {
//4.
console.log(response);
$scope.assetloader = true;
for(var l = 0;l<response.viewImeiList.length;l++){
//time
var startTime = new Date();
var endTime = new Date(response.viewImeiList[l].lastmove);
var difference = startTime.getTime() - endTime.getTime();
var resultInMinutes = difference / 60000;
var result = Math.round(resultInMinutes);
//for date
var dateObj = new Date(response.viewImeiList[l].lastmove);
var month1 = ("0" + (dateObj.getUTCMonth() + 1)).slice(-2);//months from 1-12
var day1 = ("0" + dateObj.getUTCDate()).slice(-2);
var year1 = dateObj.getUTCFullYear();
var testdate = year1 + "-" + month1 + "-" + day1;
var now = new Date();
var day = ("0" + now.getDate()).slice(-2);
var month = ("0" + (now.getMonth() + 1)).slice(-2);
var today = now.getFullYear() + "-" + (month) + "-" + (day);
if (response.viewImeiList[l].nosignal == 1) {
$scope.black = n + 1;
n++;
}else if(testdate != today){
$scope.black = n + 1;
n++;
var title = '<b>Vehicle No : </b> ' + response.viewImeiList[l].vehname + '<br> <b>IMEI No : </b> ' + response.viewImeiList[l].imeiNo + '<br> <b>Reg No : </b> ' + response.viewImeiList[l].regno + '<br> <b> Speed : </b> ' + response.viewImeiList[l].speed + ' KMPH <br> <b> Over Speed Limit : </b> 50 KMPH <br> <b> Last Movement Detected Time : </b> ' + response.viewImeiList[l].lastmove + '<br>';
$scope.view = [];
$scope.view.push(response.viewImeiList[l].vehname, title,response.viewImeiList[l].latitude, response.viewImeiList[l].longitude, "000000","FFFFFF");
$scope.locData.push($scope.view);
}
else if (response.viewImeiList[l].speed == 0) {
$scope.yellow = y + 1;
y++;
var title = '<b>Vehicle No : </b> ' + response.viewImeiList[l].vehname + '<br> <b>IMEI No : </b> ' + response.viewImeiList[l].imeiNo + '<br> <b>Reg No : </b> ' + response.viewImeiList[l].regno + '<br> <b> Speed : </b> ' + response.viewImeiList[l].speed + ' KMPH <br> <b> Over Speed Limit : </b> 50 KMPH <br> <b> Last Movement Detected Time : </b> ' + response.viewImeiList[l].lastmove + '<br>';
$scope.view = [];
$scope.view.push(response.viewImeiList[l].vehname, title,response.viewImeiList[l].latitude, response.viewImeiList[l].longitude, "e5ff00","000000");
$scope.locData.push($scope.view);
} else if (response.viewImeiList[l].speed != 0 && result > 15) {
$scope.yellow = y + 1;
y++;
var title = '<b>Vehicle No : </b> ' + response.viewImeiList[l].vehname + '<br> <b>IMEI No : </b> ' + response.viewImeiList[l].imeiNo + '<br> <b>Reg No : </b> ' + response.viewImeiList[l].regno + '<br> <b> Speed : </b> ' + response.viewImeiList[l].speed + ' KMPH <br> <b> Over Speed Limit : </b> 50 KMPH <br> <b> Last Movement Detected Time : </b> ' + response.viewImeiList[l].lastmove + '<br>';
$scope.view = [];
$scope.view.push(response.viewImeiList[l].vehname, title, response.viewImeiList[l].latitude, response.viewImeiList[l].longitude, "e5ff00","000000");
$scope.locData.push($scope.view);
} else if (response.viewImeiList[l].speed > 50 && result < 15) {
$scope.red = r + 1;
r++;
var title = '<b>Vehicle No : </b> ' + response.viewImeiList[l].vehname + '<br> <b>IMEI No : </b> ' + response.viewImeiList[l].imeiNo + '<br> <b>Reg No : </b> ' + response.viewImeiList[l].regno + '<br> <b> Speed : </b> ' + response.viewImeiList[l].speed + ' KMPH <br> <b> Over Speed Limit : </b> 50 KMPH <br> <b> Last Movement Detected Time : </b> ' + response.viewImeiList[l].lastmove + '<br>';
$scope.view = [];
$scope.view.push(response.viewImeiList[l].vehname, title, response.viewImeiList[l].latitude, response.viewImeiList[l].longitude, "FF0000","000000");
$scope.locData.push($scope.view);
} else {
$scope.green = g + 1;
g++;
var title = '<b>Vehicle No : </b> ' + response.viewImeiList[l].vehname + '<br> <b>IMEI No : </b> ' + response.viewImeiList[l].imeiNo + '<br> <b>Reg No : </b> ' + response.viewImeiList[l].regno + '<br> <b> Speed : </b> ' + response.viewImeiList[l].speed + ' KMPH <br> <b> Over Speed Limit : </b> 50 KMPH <br> <b> Last Movement Detected Time : </b> ' + response.viewImeiList[l].lastmove + '<br>';
$scope.view = [];
$scope.view.push(response.viewImeiList[l].vehname, title, response.viewImeiList[l].latitude, response.viewImeiList[l].longitude, "00ff00","000000");
$scope.locData.push($scope.view);
}
}
var locations = $scope.locData;
for (var i = 0; i < locations.length; i++) {
var city = locations[i][0];
var state = locations[i][1];
var lat = locations[i][2];
var lng = locations[i][3];
var desc = locations[i][4];
var textcol = locations[i][5];
var z = i;
var myLatLng = new google.maps.LatLng(lat, lng);
var content = '<div class="map-content"><h3>' + state +
'</h3></div>';
//5.
marker = new google.maps.Marker({
map: map,
title: state,
position: myLatLng,
icon : 'https://chart.googleapis.com/chart?chst=d_map_pin_letter&chld=' + city + '|' + desc + '|' +textcol,
draggable : true,
zIndex: z
});
//6.
test.push(marker);
//mouseover
google.maps.event.addListener(marker, 'click', (function(marker, content) {
return function() {
infoWindow.setContent(content);
infoWindow.open(map, marker);
}
})(marker, content));
// add the double-click event listener
google.maps.event.addListener(marker, 'dblclick', function(event){
map = marker.getMap();
map.setCenter(overlay.getPosition()); // set map center to marker position
smoothZoom(map, 12, map.getZoom()); // call smoothZoom, parameters map, final zoomLevel, and starting zoom level
})
// the smooth zoom function
function smoothZoom (map, max, cnt) {
if (cnt >= max) {
return;
}
else {
y = google.maps.event.addListener(map, 'zoom_changed', function(event){
google.maps.event.removeListener(y);
self.smoothZoom(map, max, cnt + 1);
});
setTimeout(function(){map.setZoom(cnt)}, 80);
}
}
}
});
myVar = setTimeout(autoUpdate, 40000);
}
if(test.length !=0){
//7.
for (var k = 0; k < test.length; k++) {
if (test[k].getMap() != null) {
test[k].setMap(null);
}
}
test1();
}
}
function test1(){
//8.
test = [];
marker = null;
autoUpdate();
}
autoUpdate();
}
});
}
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]
I'm trying to calculate the total distance for a route with a single waypoint in it, but somehow my code only returns the distance to the first waypoint instead of the total distance.
Here's my code:
function calcRoute(homebase,from,to,via){
var start = from;
var end = to;
var wypt = [ ];
wypt.push({
location:via,
stopover:true});
var request = {
origin:start,
destination:end,
waypoints:wypt,
optimizeWaypoints: true,
travelMode: google.maps.DirectionsTravelMode.DRIVING,
unitSystem: google.maps.DirectionsUnitSystem.METRIC
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
var distance = response.routes[0].legs[0].distance.text;
var time_taken = response.routes[0].legs[0].duration.text;
var calc_distance = response.routes[0].legs[0].distance.value;
}
});
}
The reason you only get the distance for legs[0] is because that is what your code is calculating. You need to sum up the distances of all the legs:
http://www.geocodezip.com/v3_GoogleEx_directions-waypoints_totalDist.html
code snippet:
var directionDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer();
var chicago = new google.maps.LatLng(41.850033, -87.6500523);
var myOptions = {
zoom: 6,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: chicago
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
directionsDisplay.setMap(map);
calcRoute();
}
google.maps.event.addDomListener(window, 'load', initialize);
function calcRoute() {
var request = {
// from: Blackpool to: Preston to: Blackburn
origin: "Blackpool,UK",
destination: "Blackburn,UK",
waypoints: [{
location: "Preston,UK",
stopover: true
}],
optimizeWaypoints: true,
travelMode: google.maps.DirectionsTravelMode.WALKING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
var route = response.routes[0];
var summaryPanel = document.getElementById("directions_panel");
summaryPanel.innerHTML = "";
// For each route, display summary information.
for (var i = 0; i < route.legs.length; i++) {
var routeSegment = i + 1;
summaryPanel.innerHTML += "<b>Route Segment: " + routeSegment + "</b><br />";
summaryPanel.innerHTML += route.legs[i].start_address + " to ";
summaryPanel.innerHTML += route.legs[i].end_address + "<br />";
summaryPanel.innerHTML += route.legs[i].distance.text + "<br /><br />";
}
computeTotalDistance(response);
} else {
alert("directions response " + status);
}
});
}
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("total").innerHTML = "total distance is: " + totalDist + " km<br>total time is: " + (totalTime / 60).toFixed(2) + " minutes";
}
html {
height: 100%
}
body {
height: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.google.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div id="map_canvas" style="float:left;width:70%;height:100%;"></div>
<div id="control_panel" style="float:right;width:30%;text-align:left;padding-top:20px">
<div id="directions_panel" style="margin:20px;background-color:#FFEE77;"></div>
<div id="total"></div>
</div>