remove route with google map

后端 未结 8 1941
半阙折子戏
半阙折子戏 2020-12-03 20:29

I got a small app that use the Direction Service feature of Google Map. It is working well, I can change routes, but I have a small problem, where a user could go back to a

相关标签:
8条回答
  • 2020-12-03 21:03

    You could also use:

    directionsDisplay.setDirections({routes: []});
    

    In this way, you can keep using one map with one renderer for all routes.

    0 讨论(0)
  • 2020-12-03 21:03

    The other answers did not work for me. I found a solution from this question

    define directionsDisplay only 1 time(outside of the click-handler)

    0 讨论(0)
  • 2020-12-03 21:03

    I had similar problem, I tried with directionsDisplay.setMap(null); but it didn’t work.

    The problem was the directionsDisplay object which I created was declared locally.

    I changed it to global and every time the function is called, it will use the same global directionsDisplay object and make changes to it. This will definitely remove the previous route displayed on same object.

    0 讨论(0)
  • 2020-12-03 21:11

    It's important - at least it was in my case - that while directionsDisplay can be declared globally the instance has to be created after the map object otherwise it gave a reference error

        var map;
        var directionsDisplay;
    
        function initMap() { 
    
            map = new google.maps.Map(...);
    
            directionsDisplay = new google.maps.DirectionsRenderer(...);
    
         }
    
         function yourFunction() {
    
            // your code
    
            directionsDisplay.addListener(...);
    
         }
    
    0 讨论(0)
  • 2020-12-03 21:12

    This is the fix

    // Clear past routes
    if (directionsDisplay != null) {
        directionsDisplay.setMap(null);
        directionsDisplay = null;
    }
    
    0 讨论(0)
  • 2020-12-03 21:15

    Since on each call, new instance of DirectionRenderer created thats why each new instance is unaware of previous instance.

    Move

    var directionsDisplay = new google.maps.DirectionsRenderer();
    

    to the global(at the top where all other Global variables have been initialized.)

    By doing so, each time you would be using single instance of DirectionRenderer.

    0 讨论(0)
提交回复
热议问题