2013-04-06 2 views
2

Google지도 v3 프로젝트에서 작업 중이며 도움이 필요한 부분을 찾으러 왔습니다. 나는 사용자가 시작과 끝 지점을 입력 할 수있는 구글 맵을 가지고 있는데, 그것은 잘 작동하지만 어떤 이유에서든 웨이 포인트를 입력하고자 할 때 (최대 8 개의 웨이 포인트까지) 작동하지 않을 것이다. 누군가가 코드를보고 나를 도울 수 있습니까? 이 내가 프로젝트와 함께 얼마나 멀리 :Google지도 api v3 웨이 포인트가지도에 표시되지 않음

<!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> 

을 그리고 이것은 내 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."); 
    } 

누군가가 알려 주시기 바랍니다 더 많은 정보를 필요로하는 경우. 고마워요

답변

1

봐야 할 코드가 많습니다. 테스트 페이지 또는 심지어 fiddle을 넣을 수 있습니까? 한편

, 나는 여기에서 문제를 볼 수 있습니까 :
var scntUl = $('#stops'); 
var ii = $('#stops').size() + 1; 

$('#stops')

는 당신에게 <ul id="stops"> 요소 자체가 아닌 그 아이들을위한 jQuery를 객체를 제공합니다. 이 개체의 length은 내부에 추가 한 요소 수에 관계없이 1이됩니다. 아마도 대신 $('#stops>li')을 원하십니까? 그러면 모든 <li> 요소를 포함하는 jQuery 객체가 생성됩니다.

은 (BTW 대신 .size() 방법의 .length 속성을 사용할 수 있습니다 -이 방법은 이전 코드와의 호환성을 위해 존재한다.)

또한, 당신은 왜 그 길이에 1을 추가? 그보다 훨씬 많은 코드는 보지 않았지만, <li> 요소를 원하면 .length 그대로 사용하십시오.

또한 <input> 요소는 모두 id="remScnt"입니다. id을 두 번 이상 사용하면 안됩니다. class을 사용하거나 고유 ID (또는 둘 다)를 생성하십시오.

또 다른 한 가지 - .live()은 더 이상 사용되지 않습니다. 대신 .on을 사용하십시오. 당신은지도 링크를 게시 한 후 업데이트

...

이 코드를 살펴 보자 :

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

적어도 서너 문제가 여기에있다. 하지만이 코드를 그대로 수정하려고 시도하지 않고 jQuery를 이용하면 더 쉽게 사용할 수 있습니다.

먼저 #addScnt 클릭 핸들러의 코드로 돌아가서 각각 새로 <li>을 DOM에 추가하고 <input> 태그에 클래스 이름을 추가합니다.

<input class="waypoint" ...and the existing attributes here... /> 

그리고 당신은 위의 그 루프가 어디 다음으로 변경 : 그 사람들을 필요로하지 않는 한이 코드는 더 이상 등 ID를 stop1, stop2를 갖는 입력에 따라 달라

var waypts = []; 
$('.waypoint').each(function(i, input) { 
    var value = $(input).val(); 
    if(value.length) waypts.push({ location: value }); 
}); 

주 다른 곳의 ID는 제거 할 수 있습니다.

var scntUl = $('#stops>li'); 
var ii = $('#stops').length; 

당신이 ii의 값이 여기에있을 것 어떻게 생각하십니까 :

또한 나는 여전히이 코드가 발견? 또한 나중에 확인해보십시오.

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

옳지 않을 수도 있습니다. 이 내용을 #stops 자체에 추가하면 안됩니까? <li> 요소를 지금 중첩하고 있습니다. 의도 한 바가 아닙니다.

마지막으로 Chrome 또는 다른 브라우저에서 개발자 도구를 사용하여 이러한 문제를 해결하십시오. 물론 SO는 훌륭한 자료입니다. 여기에있는 질문은 언제나 환영합니다. Chrome 또는 다른 브라우저에서 개발자 도구 ()으로 실행되는 문제를 해결할 수있는 것이 더 좋습니다. 가능한 모든 옵션을 살펴 보는 데 시간을 할애 할 가치가 있습니다. Start here for a tutorial on the Chrome DevTools.

+0

안녕하세요, Michael, 전 미안했습니다. [link] (http://www.motorcycleavenue.com)로 가면지도가 보입니다. 도와 줘서 고마워. – im2shae

+0

내가 왜 증분 된 ids를 원하게되는지는 그것이 내가 작동하는 웨이 포인트를 가지고 있기 때문입니다. – im2shae

+0

나는 – im2shae