行程改变时如何清除折线?

问题描述 投票:0回答:1

我正在加载一个已加载地图和路线的页面。

我们可以通过此表格更改出发地、目的地和运输方式:

<div id="formulaire" class="box">

    <input id="start" type="text" value="$4DTEXT($vo_personne.origine)" class="input my-1">
    <input id="end" type="text" value="$4DTEXT($vo_personne.destination)" class="input my-1">
    
    <div class="select my-1">
    <select id="mode_transport">
        <option value="DRIVING">Voiture</option>
        <option value="TRANSIT">Transports</option>
    </select>
    </div>
    
    <input type="submit" value="Actualiser le trajet" class="button my-1">
    
</div>

当我更改表单中的某些内容时,地图会发生变化,路线也会发生变化,但我没有找到清除上一张地图上的旧路线(折线)的方法。

这是我的JS代码

<script>

// onglets jquery UI
$( function() {
    $( "#tabs" ).tabs();
} );

// Google Maps
function initMap() {
    directionsRenderer = new google.maps.DirectionsRenderer({
        polylineOptions : { // works only on the active path
            strokeColor: '#0047b3',
            strokeOpacity: 1.0,
            strokeWeight: 7
        }
    });
    
    directionsService = new google.maps.DirectionsService();
    
    map = new google.maps.Map(document.getElementById("carte"), {
        zoom: 5,  
        center: { lat : 46.603354, lng: 1.888334}, // france
    });

    directionsRenderer.setMap(map);
    
    calculateAndDisplayRoute(directionsService, directionsRenderer);

    document.getElementById("mode_transport").addEventListener("change", () => {
        calculateAndDisplayRoute(directionsService, directionsRenderer);
    }); 
    document.getElementById("start").addEventListener("change", () => {
        calculateAndDisplayRoute(directionsService, directionsRenderer);
    }); 
    document.getElementById("end").addEventListener("change", () => {
        calculateAndDisplayRoute(directionsService, directionsRenderer);
    });
    
}

function calculateAndDisplayRoute(directionsService, directionsRenderer) {
    
    start = document.getElementById("start").value;
    end = document.getElementById("end").value; 
    selectedMode = document.getElementById("mode_transport").value;
    
    directionsRenderer.setMap(map); 
    
    directionsRenderer.setPanel(document.getElementById("itineraire"));

    directionsRequest = {
        origin: start,
        destination: end,
        travelMode: google.maps.TravelMode[selectedMode],
        provideRouteAlternatives: true,
        optimizeWaypoints: true,
    };

    directionsService
        .route(directionsRequest)
        .then((response) => {
            directionsRenderer.setDirections(response);
            
        //  console.log (response);
        //  console.log (response.routes.length + ' routes');
        //  status = (response.status);

            if (status === 'OK') {
                // les routes trouvées
                for (var i = 0, len = response.routes.length; i < len; i++) {
                    new google.maps.DirectionsRenderer({
                        map: map,
                        directions: response,
                        routeIndex: i
                    });
                    
                    // route sélectionnée par défaut ?
                    // lui attribuer un ID ?
                    var polyline = response.routes[i] ;
                }   
                    
                console.log (polyline);
            }

        })
        .catch((e) => window.alert("Directions request failed due to " + e));
}

// création de la carte à l'ouverture de la page
window.initMap = initMap;

</script>

我是初学者,这是我的第一张地图,所以我没有找到更新折线的解决方案。

新的很好,但最旧的应该删除或隐藏。

我尝试通过添加 polyline.remove() 来更改事件侦听器,但它会产生此错误: 未捕获(承诺中)ReferenceError:polyLinePath 未定义

document.getElementById("mode_transport").addEventListener("change", () => {
        polyline.remove();
        calculateAndDisplayRoute(directionsService, directionsRenderer);
    }); 
    document.getElementById("start").addEventListener("change", () => {
        polyline.remove();
        calculateAndDisplayRoute(directionsService, directionsRenderer);
    }); 
    document.getElementById("end").addEventListener("change", () => {
        polyline.remove();
        calculateAndDisplayRoute(directionsService, directionsRenderer);
    });

感谢您的帮助

javascript google-maps google-maps-api-3
1个回答
0
投票

您需要保留对用于显示路线的 DirectionRenderer 对象的引用。

全球范围内:

let renderer = [];

然后,当您创建渲染器时,将它们推送到该数组上:

for (var i = 0, len = response.routes.length; i < len; i++) {
  renderer.push(new google.maps.DirectionsRenderer({
    map: map,
    directions: response,
    routeIndex: i
  }));
}   

然后要从地图中删除路线,请将这些渲染器上的地图设置为 null:

function removeOldRoutes() {
  for (var i=0; i < renderer.length; i++) {
    renderer[i].setMap(null);
  }
  renderer = [];
}

概念证明小提琴

代码片段

let map;
let renderer = [];
// Google Maps
function initMap() {
    directionsRenderer = new google.maps.DirectionsRenderer({
        polylineOptions : { // works only on the active path
            strokeColor: '#0047b3',
            strokeOpacity: 1.0,
            strokeWeight: 7
        }
    });
    
    directionsService = new google.maps.DirectionsService();
    
    map = new google.maps.Map(document.getElementById("carte"), {
        zoom: 5,  
        center: { lat : 46.603354, lng: 1.888334}, // france
    });

    directionsRenderer.setMap(map);
    
    calculateAndDisplayRoute(directionsService, directionsRenderer);

    document.getElementById("mode_transport").addEventListener("change", () => {
        removeOldRoutes()
        calculateAndDisplayRoute(directionsService, directionsRenderer);
    }); 
    document.getElementById("start").addEventListener("change", () => {
        removeOldRoutes()
        calculateAndDisplayRoute(directionsService, directionsRenderer);
    }); 
    document.getElementById("end").addEventListener("change", () => {
        removeOldRoutes()
        calculateAndDisplayRoute(directionsService, directionsRenderer);
    });
    
}
function removeOldRoutes() {
  for (var i=0; i < renderer.length; i++) {
    renderer[i].setMap(null);
  }
  renderer = [];
}
function calculateAndDisplayRoute(directionsService, directionsRenderer) {
    
    start = document.getElementById("start").value;
    end = document.getElementById("end").value; 
    selectedMode = document.getElementById("mode_transport").value;
    
    directionsRenderer.setMap(map); 
    
    directionsRenderer.setPanel(document.getElementById("itineraire"));

    directionsRequest = {
        origin: start,
        destination: end,
        travelMode: google.maps.TravelMode[selectedMode],
        provideRouteAlternatives: true,
        optimizeWaypoints: true,
    };

    directionsService
        .route(directionsRequest)
        .then((response) => {
            directionsRenderer.setDirections(response);
            
            console.log (response);
            console.log (response.routes.length + ' routes');
            status = (response.status);

            if (status === 'OK') {
                // les routes trouvées
                for (var i = 0, len = response.routes.length; i < len; i++) {
                    console.log("rendering route "+i);
                    renderer.push(new google.maps.DirectionsRenderer({
                        map: map,
                        directions: response,
                        routeIndex: i
                    }));
                }   
            }

        })
        .catch((e) => window.alert("Directions request failed due to " + e));
}

// création de la carte à l'ouverture de la page
window.initMap = initMap;
/* 
 * Always set the map height explicitly to define the size of the div element
 * that contains the map. 
 */
#carte {
  height: 80%;
}

/* 
 * Optional: Makes the sample page fill the window. 
 */
html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
}
<!doctype html>
<html>
  <head>
    <title>StackSnippet</title>
  </head>
  <body>
    <div id="carte"></div>
<div id="formulaire" class="box">

    <input id="start" type="text" value="Paris" class="input my-1">
    <input id="end" type="text" value="Marseille" class="input my-1">
    
    <div class="select my-1">
    <select id="mode_transport">
        <option value="DRIVING">Voiture</option>
        <option value="TRANSIT">Transports</option>
    </select>
    </div>
    
    <input type="submit" value="Actualiser le trajet" class="button my-1">
    
</div>
    <!-- 
      The `defer` attribute causes the script to execute after the full HTML
      document has been parsed. For non-blocking uses, avoiding race conditions,
      and consistent behavior across browsers, consider loading using Promises. See
      https://developers.google.com/maps/documentation/javascript/load-maps-js-api
      for more information.
      -->
    <script
      src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap&v=weekly"
      defer
    ></script>
  </body>
</html>

© www.soinside.com 2019 - 2024. All rights reserved.