Reputation: 57
I'm working on a google maps v3 project and i've come to a point where i need some help. I have a google map where the user can enter a start and end points, which works fine but when i want to enter waypoints for some reason they wont work( up to 8 waypoints ). Could someone look at the code and help me? This is how far i have come with the project:
<!DOCTYPE html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title></title>
<link href="map_style.css" rel="stylesheet">
<script src="jquery-1.8.3.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script src="maps.js"></script>
<script type="text/javascript">
<!--
function toggle_visibility(id) {
var e = document.getElementById(id);
if(e.style.display == 'block')
e.style.display = 'none';
else
e.style.display = 'block';
}
//-->
</script>
</head>
<body onload="initialize()">
<div id="total"></div>
<div id="map-canvas"></div>
<div id="control_panel">
<div id="user_input">
<label for="start">Start :</label>
<input type="text" id="start" name="start" /><br />
<i>Add multiple Stops along the route (Optional)</i><br />
<ul id="stops">
<li>
<label for="stop1">Stop 1:</label>
<input type="text" id="stop1" name="stop1" />
</li>
</ul>
<input type="button" id="addScnt" value="Add Stop" /><br />
<label for="end">End :</label>
<input type="text" id="end" name="end" /><br />
<br />
<input type="submit" value="Create Route" onclick="calcRoute();" />
<input type="button" id="button" value="Show/Hide Directions" onclick="toggle_visibility('directions_panel');" />
</div>
</div>
<div id="directions_panel"></div>
</body>
</html>
And this is my js file:
$(document).ready(function () {
var scntUl = $('#stops');
var ii = $('#stops').size() + 1;
var MaxInputs = 8;
$('#addScnt').live('click', function () {
if (ii <= MaxInputs) {
$('<li><label for="stop' + ii +'">Stop ' + ii + ': </label><input type="text" id="stop' + ii +'" name="stop' + ii + '" /><input type="button" id="remScnt" value="X" /></li>').appendTo(scntUl);
ii++;
}
return false;
});
$('#remScnt').live('click', function () {
if (ii > 2) {
$(this).parents('li').remove();
ii--;
}
return false;
});
});
var directionDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer();
var map = new google.maps.LatLng(37.09, -95.71);
var mapOptions = {
zoom: 4,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: map
}
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById("directions_panel"));
}
function calcRoute() {
var start = document.getElementById('start').value;
var end = document.getElementById('end').value;
var waypts = [];
for (var ii = 0; ii < thisStop; ii++) {
var thisStop = document.getElementById("stop" + (ii+1)).value;
if (thisStop.length > 0) {
if (thisStop.length > 0) {
waypts[ii] = {location: thisStop};
}
}
}
var request = {
origin: start,
destination: end,
waypoints: waypts,
optimizeWaypoints: false,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
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 = '';
}
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;
}
var miles = 0.000621371192;
document.getElementById("total").innerHTML = ("Total distance is: "+ (Math.round( totalDist * miles * 10 ) / 10 ) + " miles " + " and " + " Approximate time is: " + (totalTime / 60 / 60).toFixed(1) + " hours.");
}
If someone needs more info please let me know. Thank you
Upvotes: 2
Views: 904
Reputation: 28850
That's a lot of code to look at. Can you put up a test page, or even a fiddle?
In the meantime, I do see a problem here:
var scntUl = $('#stops');
var ii = $('#stops').size() + 1;
$('#stops')
gives you a jQuery object for the <ul id="stops">
element itself, not its children. The length
of this object will be 1 no matter how many <li>
elements you add inside it. Perhaps you want $('#stops>li')
instead? That will give you a jQuery object containing all of the <li>
elements.
(BTW you can use the .length
property instead of the .size()
method - the method is there only for compatibility with old code.)
Also, why are you adding 1 to that length? I didn't look at the code much beyond that, but if you want the number of <li>
elements you would just take .length
as it is.
I also noticed that the <input>
elements all have id="remScnt"
. You shouldn't use an id
more than once; use a class
or generate unique ids (or both).
One other thing - .live()
is deprecated; use .on
instead.
Updated after you posted the map link...
Take a look at this code:
for (var ii = 0; ii < thisStop; ii++) {
var thisStop = document.getElementById("stop" + (ii+1)).value;
if (thisStop.length > 0) {
if (thisStop.length > 0) {
waypts[ii] = {location: thisStop};
}
}
}
There are at least three or four problems here. But rather than try to fix this code as it is, why not take advantage of jQuery to make it easier?
First, go back to the code in your #addScnt
click handler where it appends each new <li>
into the DOM, and add a classname to the <input>
tag, e.g.
<input class="waypoint" ...and the existing attributes here... />
And then where you have that loop above, change it to:
var waypts = [];
$('.waypoint').each( function( i, input ) {
var value = $(input).val();
if( value.length ) waypts.push({ location: value });
});
Note that this code no longer depends on the inputs having the IDs stop1
, stop2
, etc. Unless you need those IDs elsewhere, you can remove them.
Also I noticed you still have this code:
var scntUl = $('#stops>li');
var ii = $('#stops').length;
What do you think the value of ii
will be here? Also, later you have this:
$('<li>...</li>').appendTo(scntUl);
That can't be right. Shouldn't this be appending to #stops
itself? You're nesting <li>
elements now, which is not what you intended.
Finally, use the Developer Tools in Chrome or another browser to troubleshoot these problems. SO is a great resource, of course, and questions here are always welcome. But it's even better when you can troubleshoot the problems you run into right now with the Developer Tools in Chrome or other browsers. It's worth spending some time exploring all the options available there. Start here for a tutorial on the Chrome DevTools.
Upvotes: 1