2015-01-06 3 views
-1

Я создаю бегущее веб-приложение для отслеживания. Когда вы нажмете кнопку запуска, он начнет отслеживать вас. Красный маркер - это начальная позиция, а синий маркер отслеживает текущее местоположение, и существует полилиния, создающая путь между двумя точками.Как создать маркеры карты google и полилинию после их удаления?

Когда я нажимаю кнопку «Стоп», она удаляет маркер и полилинию, что и я хочу. Но когда я снова нажимаю кнопку «Старт», я хочу, чтобы он просто повторил то, что он сделал, когда вы сначала нажимали кнопку запуска. Например, создайте красный маркер в стартовой позиции, а затем синий маркер для отслеживания движений пользователей, а также создайте полилинию между двумя точками.

В настоящее время он создает только синий маркер и ничего больше. Как это исправить?

CodePen Demo

HTML:

<!DOCTYPE html> 
<html> 
<head> 
    <title>Runna - Track your run!</title> 
    <meta name="viewport" content="width=device-width, initial-scale=1.0 user-scalable=no"> 
    <link rel="stylesheet" type="text/css" href="css/reset.css"> 
    <link rel="stylesheet" type="text/css" href="css/style.css"> 
    <link href='http://fonts.googleapis.com/css?family=Lato:400,700,900' rel='stylesheet' type='text/css'> 
    <link href="http://maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> 
    <script src="https://maps.googleapis.com/maps/api/js?v=3&sensor=true&libraries=geometry"></script> 
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
    <script src="js/js.js"></script> 
    <script src="js/modernizr.js"></script> 


</head> 
<body> 
<div class="wrapper"> 

    <header> 
     <img src="imgs/logo-blue.png" /> 
    </header> 
    <div id="map-container"> 
     <div id="map_canvas">Press start to begin</div> 
    </div> 
    <div class="show-controls"><i class="fa fa-chevron-up"></i></div> 
    <section id="control-container"> 
     <div class="column left"> 

       <div id="left-wrapper"> 
        <div class="left-top"> 
         <ul> 
          <li><b>Distance</b></li> 
          <li class="distance-total"></li> 
         </ul> 
        </div> 

        <div class="left-bottom"> 
         <ul> 
          <li><b>Duration</b></li> 
          <li><span id="stop-watch">00:00:00</span></li> 
         </ul> 
        </div> 
       </div> 

     </div> 
     <div class="column middle"> 
      <nav> 
       <ul> 
        <li><a href="#" class="arrow"><div><i class="fa fa-chevron-down"></i></div></a> 
         <a href="#" id="start"><div>START</div></a> 
         <a href="#" id="stop"><div>STOP</div></a> 
        </li> 
       </ul> 
      </nav> 
     </div> 
     <div class="column right"> 
      <div id="right-wrapper"> 
        <div class="right-top"> 
         <ul> 
          <li><b>Speed</b></li> 
          <li class="calories-total"></li> 
         </ul> 
        </div> 

        <div class="right-bottom"> 
         <ul> 
          <li><b>Share</b></li> 
           <a href="http://www.facebook.com"><i class="fa fa-facebook-square"></i></a> 

           <a href="http://www.twitter.com"><i class="fa fa-twitter-square"></i></a> 
         </ul> 
        </div> 
       </div> 

     </div> 
    </section> 

</div> 
</body> 
</html> 

JS:

// Global Variables =========================================================================================== 

var watchID = null; 
var geo; 
var map; 
var startMarker = []; // Red Marker 
var endMarker = []; // Blue Marker 
var geo_options = { 
    enableHighAccuracy: true, 
    maximumAge: 100000, 
    timeout: 20000 
}; 
var pathLineArray = new Array(); 
var mypath; 
var lastLatLng = pathLineArray[pathLineArray.length - 1]; 

$(document).ready(function() { 

    // Show and hide the bottom bar ----------------------------------------------------------------------------- 

    var arrowButton = $('a.arrow'); 
    var controlContainer = $('#control-container'); 

    arrowButton.on('click', function(event) { 
     event.preventDefault(); 
     controlContainer.fadeOut('fast'); 
     $('.show-controls').show(); 
     $('#map-container').css('height', '87vh'); 
    }); 

    $('.show-controls').on('click', function(event) { 
     event.preventDefault(); 
     controlContainer.fadeIn('fast'); 
     $('.show-controls').hide(); 
     $('#map-container').css('height', '65vh'); 
    }); 

// Stop watch script =========================================================================================== 

    var h2 = document.getElementById('stop-watch'), 
     start = document.getElementById('start'), 
     stop = document.getElementById('stop'), 
     seconds = 0, 
     minutes = 0, 
     hours = 0, 
     t; 

    function add() { 
     seconds++; 
     if (seconds >= 60) { 
     seconds = 0; 
     minutes++; 
     if (minutes >= 60) { 
      minutes = 0; 
      hours++; 
     } 
     } 

     h2.innerHTML = (hours ? (hours > 9 ? hours : "0" + hours) : "00") + ":" + (minutes ? (minutes > 9 ? minutes : "0" + minutes) : "00") + ":" + (seconds > 9 ? seconds : "0" + seconds); 

     timer(); 
    } 

    function timer() { 
     t = setTimeout(add, 1000); 
    } 

    /* Start button */ 
    start.onclick = function() { 
     timer(); 

    } 

    // Resets the stop watch 
    function resetTimer() { 
     clearTimeout(t); 
     h2.innerHTML = "00:00:00"; 
     seconds = 0; minutes = 0; hours = 0; 
    } 

// End of Stop watch script =========================================================================================== 

    $('#start').click(startWatching); 

    if (geo = getGeoLocation()) { 
     // startWatching(); Only uncomment if you want the map to load straight away upon page load 
    } else { 
     alert('Geolocation is not supported'); 
    } 

    $('#stop').click(function() { 
     var stopQuestion = confirm("Are you sure you want to stop?"); 

     if (stopQuestion) { 
     stopWatching(); 
     mypath.setMap(null); // Deletes path/polyline that has been created 
     startMarker.setMap(null); // Deletes the start red marker 
     endMarker.setMap(null); // Deletes the end blue marker 
     resetTimer(); 
     } else { 
      return; 
     } 
    }); 
}); // Ready block finish here 

function getGeoLocation() { 
    if (navigator.geolocation) { 
     return navigator.geolocation; 
    } else { 
     return "Undefined"; 
    } 
} 

function startWatching() { 
    watchID = geo.watchPosition(show_coords, geo_error, geo_options); 
    // watchID = geo.getCurrentPosition(show_coords, geo_error, geo_options); 
} 

function stopWatching() { 
    if (watchID != null) { 
     geo.clearWatch(watchID); 
    } 
} 

function show_coords(position) { 

    var speed = position.coords.speed; 
    var lat = position.coords.latitude; 
    var lon = position.coords.longitude; 
    var latlng = new google.maps.LatLng(lat, lon); 
    var distance = google.maps.geometry.spherical.computeLength(pathLineArray); 
    var distanceInKM = distance/1000; // Converts Meters To KM 
    var distanceRounded = distanceInKM.toFixed(2); // Allows only two decimal points 
    var speedInKPH = speed * 3.6; // Converts Meters per second (default value) to kilometers per hour 

     // Updates the text with the latest distance figure 
     $('.distance-total').text(distanceRounded + "KM"); 

     $('.calories-total').text(speedInKPH + " kph"); 

     if (map) { 

     // Makes it so that it doesnt have to reload the map everytime, it just pans to the new position 
     map.panTo(latlng); 

     } else { 
     var myOptions = { 
      zoom: 16, 
      center: latlng, 
      mapTypeId: google.maps.MapTypeId.ROADMAP 
     }; 

     map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); 

     mypath = new google.maps.Polyline({ 
      path: pathLineArray, 
      strokeColor: '#FF0000', 
      strokeOpacity: 1.0, 
      strokeWeight: 2, 
      map: map 

     }); 

     startMarker = new google.maps.Marker({ 
      position: latlng, 
      map: map 
     }); 

     } 
     // Push lat and long coords to this array 
     pathLineArray.push(latlng); 

     if (mypath) { 
     mypath.setPath(pathLineArray); 

     } else { 
     mypath = new google.maps.Polyline({ 
      path: pathLineArray, 
      strokeColor: '#FF0000', 
      strokeOpacity: 1.0, 
      strokeWeight: 4, 
      map: map, 
     }); 
     } 

     if (endMarker && endMarker.setPosition) { 
     endMarker.setPosition(latlng); 
     endMarker.setMap(map); 
     } else { 
     endMarker = new google.maps.Marker({ 
      position: latlng, 
      map: map, 
      draggable: true, 
      icon: 'http://maps.google.com/mapfiles/ms/icons/blue-dot.png' 
     }); 
     } 

} // End of show_coords(position) function 


function geo_error(error) { 
    switch (error.code) { 
     case error.TIMEOUT: 
     alert("geolocation timeout"); 
     break; 
     case error.POSITION_UNAVAILABLE: 
     alert("Gelocation position unavailable"); 
     break; 
     case error.PERMISSION_DENIED: 
     alert("Permission denied"); 
     break; 
     default: 
     alert('Unknown error'); 
    } 
} 
+0

Вы видите какие-либо ошибки JavaScript в консоли? – geocodezip

+0

Нет, нет. Я считаю, что я решил проблему, просто проверил ее atm. Как я думаю, я исправил это, я вернул переменную 'map' обратно в пустую переменную в моем событии click. – ifusion

ответ

0

Я установил вопрос:

Мне нужно было установить переменную map обратно в пустую переменную.

Код:

$('#stop').click(function() { 
     var stopQuestion = confirm("Are you sure you want to stop?"); 

     if (stopQuestion) { 
     stopWatching(); 
     mypath.setMap(null); 
     startMarker.setMap(null); 
     endMarker.setMap(null); 
     map = ''; // Added this in to set it back to empty 
     pathLineArray = []; 
     resetTimer(); 
     } 
}); 
Смежные вопросы