简体   繁体   English

Google Maps API v3航点未显示在地图上

[英]Google maps api v3 waypoints not showing on the map

I'm working on a google maps v3 project and i've come to a point where i need some help. 我正在研究Google Maps v3项目,现在我需要一些帮助。 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 ). 我有一个谷歌地图,用户可以在其中输入起点和终点,效果很好,但是当我出于某种原因要输入航路点时,它们将不起作用(最多8个航路点)。 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: 这是我的js文件:

  $(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 谢谢

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. $('#stops')为您提供<ul id="stops">元素本身而不是其子元素的jQuery对象。 The length of this object will be 1 no matter how many <li> elements you add inside it. 无论您在其中添加多少<li>元素,该对象的length均为1。 Perhaps you want $('#stops>li') instead? 也许您想要$('#stops>li')代替? That will give you a jQuery object containing all of the <li> elements. 这将为您提供一个包含所有<li>元素的jQuery对象。

(BTW you can use the .length property instead of the .size() method - the method is there only for compatibility with old code.) (顺便说一句,您可以使用.length属性代替.size()方法-该方法仅用于与旧代码兼容。)

Also, why are you adding 1 to that length? 另外,为什么还要给该长度加1? 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. 除此以外,我对代码的关注并不多,但是如果您想要<li>元素的数量,则只需采用.length

I also noticed that the <input> elements all have id="remScnt" . 我还注意到<input>元素都具有id="remScnt" You shouldn't use an id more than once; 您不应该多次使用id use a class or generate unique ids (or both). 使用class或生成唯一的ID(或同时生成两者)。

One other thing - .live() is deprecated; 另一件事.live()已弃用; use .on instead. 使用.on代替。

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? 但是为什么不尝试按原样修复此代码,为什么不利用jQuery使其变得更容易呢?

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, eg 首先,回到您的#addScnt点击处理程序中的代码,该代码将每个新的<li>附加到DOM中,并向<input>标记添加一个类名,例如

<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. 请注意,此代码不再取决于具有ID stop1stop2等的输入。除非您在其他位置需要这些ID,否则可以将其删除。

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? 您认为ii的值在这里如何? Also, later you have this: 另外,稍后您会得到:

$('<li>...</li>').appendTo(scntUl);

That can't be right. 那是不对的。 Shouldn't this be appending to #stops itself? 这不应该附加到#stops本身吗? You're nesting <li> elements now, which is not what you intended. 您现在正在嵌套<li>元素,这不是您想要的。

Finally, use the Developer Tools in Chrome or another browser to troubleshoot these problems. 最后,在Chrome或其他浏览器中使用开发人员工具来解决这些问题。 SO is a great resource, of course, and questions here are always welcome. 因此,SO是很好的资源,这里的问题总是很受欢迎。 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. 但它甚至更好时,你可以解决你碰到现在在Chrome或其他浏览器的开发者工具的问题。 It's worth spending some time exploring all the options available there. 值得花一些时间探索那里所有可用的选项。 Start here for a tutorial on the Chrome DevTools . 从此处开始,以获取有关Chrome DevTools的教程

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM