2015-03-26 6 views
0

Я пытаюсь создать страницу ASP.NET, где можно отслеживать маршрут от текущего пользователя с помощью API Карт Google. Проблема заключается в том, что всякий раз, когда я использую интервал для рисования полилинии, все обновления Google Map обновляются, что приводит к мигающей странице.Обновление только полилинии не всей карты

Вот мой код:

<script> 
    //declare variables 
    var interval; 
    var coordinates = []; 
    var x = document.getElementById("exception"); 

    //Get current position and loop this 
    function getLocation() { 
     //Check if the user has a geolocation 
     if (navigator.geolocation) { 
      interval = setInterval(function() { navigator.geolocation.getCurrentPosition(showPosition); }, 500); 
     } else { 
      x.innerHTML = "Geolocation is not supported by this browser."; 
     } 
    } 

    //Get the latitude and longitude and draw a polylin 
    function showPosition(position) { 
     console.log(position.coords.latitude + " " + position.coords.longitude); 

     //Map options for the Google map and center the current position 
     var mapOptions = { 
      zoom: 15, 
      center: new google.maps.LatLng(position.coords.latitude, position.coords.longitude) 
     } 

     //Add the options to the google map and display it 
     var map = new google.maps.Map(document.getElementById("mapDiv"), mapOptions); 

     //Create a marker for the current position 
     var marker = new google.maps.Marker({ 
      position: new google.maps.LatLng(position.coords.latitude, position.coords.longitude), 
      title: "Current position!" 
     }); 

     // To add the marker to the map, call setMap(); 
     marker.setMap(map); 

     //Add the current coordinates to the array 
     coordinates.push(new google.maps.LatLng(position.coords.latitude, position.coords.longitude)); 

     //Create a polyline with the coordinates array 
     var flightPath = new google.maps.Polyline({ 
      path: coordinates, 
      geodesic: true, 
      strokeColor: '#FF0000', 
      strokeOpacity: 1.0, 
      strokeWeight: 2 
     }); 

     //To add the polylin to the map, call setMap(); 
     flightPath.setMap(map); 
    } 

    //Stop the interval 
    $("#stop").click(function() { 
     clearInterval(interval); 
     coordinates = []; 
    }); 
</script> 

Спасибо заранее, Brent

ответ

1

Карта мерцает, потому что вы воссоздавать его каждый раз, когда вы запускаете showPosition. вы должны сделать свою переменную map global и только установить ее один раз при загрузке страницы. Аналогичным образом вы должны сделать свой маркер и переменную flightPath глобальной и убедитесь, что вы либо удаляете их с карты, прежде чем воссоздать их, используя marker.setMap (null) и flightPath.setMap (null), или даже лучше просто обновите их с новой позицией Информация.

Смежные вопросы