Remove driving directions on Google Maps in AngularJS using ui-gmap

Utilizing AngularJS and the ui-gmap-google-map directive (http://angular-ui.github.io/angular-google-maps/#!/), I've successfully implemented a google map that displays driving routes. However, I'm encountering an issue where the previous route persists on the map when attempting to plot a new one. I tried using directionsDisplay.setMap(null); to remove the old route but it's not having the desired effect. Can someone offer guidance or assistance?

Below is the relevant section of code from my controller:

uiGmapIsReady.promise().then(function (map_instances) {
                $scope.mapRef = $scope.map.control.getGMap();
            });

$scope.getDirections = function (lat, long, origin, type) {
            uiGmapGoogleMapApi.then(function (maps) {
                var directionsService = new maps.DirectionsService();
                var directionsDisplay = new maps.DirectionsRenderer();

                if (origin == "" || type == "geo") {
                    origin = $scope.geoPosition.coords.latitude + ", " + $scope.geoPosition.coords.longitude;
                }

                var request = {
                    origin: origin,
                    destination: lat + ", " + long,
                    travelMode: maps.TravelMode['DRIVING'],
                    optimizeWaypoints: true
                };

                directionsService.route(request, function (response, status) {
                    if (status === google.maps.DirectionsStatus.OK) {
                        directionsDisplay.setMap(null);
                        directionsDisplay.setMap($scope.mapRef);
                        directionsDisplay.setDirections(response);

                    } else {
                        console.log('Directions request failed due to ' + status);
                    }
                });


            });
        }

Answer №1

Utilizing ui-map for your project is great, but using ngmap may result in fewer issues.

Check out this example with ngmap demonstrating two directions that can be toggled to show or hide.

http://plnkr.co/edit/Sv9Q4A?p=preview

<!doctype html>
<html ng-app="ngMap">
  <head>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&libraries=weather,visualization,panoramio"></script>
<script src="http://code.angularjs.org/1.2.25/angular.js"></script>
<script src="https://rawgit.com/allenhwkim/angularjs-google-maps/master/build/scripts/ng-map.js"></script>
<script>
angular.module('ngMap').controller('MyCtrl', function($scope){
  var vm = this;
  vm.toggle = function() {
    vm.show = !vm.show;
    $scope.map.directionsRenderers.d1.setMap(vm.show ? $scope.map : null);
  }
})
</script>
<link rel="stylesheet" href="style.css"/>
  </head>
  <body ng-controller='MyCtrl as vm'>
    <map zoom="14" center="37.7699298, -122.4469157">
      <directions id="d1" origin="toronto" destination="markham"></directions>
      <directions id="d2" origin="etobicoke" destination="vaughn, on"></directions>
    </map> 
    <a href="" ng-click="vm.toggle()">show/hide direction</a>
  </body>
</html>

In case you didn't know, I am the developer behind ngMap.

Answer №2

It seems the issue you are facing is related to repeatedly creating the variable

var directionsDisplay = new maps.DirectionsRenderer();
every time a new direction is requested. Instead, consider initializing this variable when initiating the Controller and updating it as needed. I have provided a demonstration in a plunker demo for your reference.

You can test if implementing this change in your code resolves the issue.

uiGmapIsReady.promise().then(function (map_instances) {
    $scope.mapRef = $scope.map.control.getGMap();
    uiGmapGoogleMapApi.then(function (maps) {
        $scope.directionsDisplay = new maps.DirectionsRenderer();
    });
});

$scope.getDirections = function (lat, long, origin, type) {
    uiGmapGoogleMapApi.then(function (maps) {
        var directionsService = new maps.DirectionsService();

        if (origin == "" || type == "geo") {
            origin = $scope.geoPosition.coords.latitude + ", " + $scope.geoPosition.coords.longitude;
        }

        var request = {
            origin: origin,
            destination: lat + ", " + long,
            travelMode: maps.TravelMode['DRIVING'],
            optimizeWaypoints: true
        };

        directionsService.route(request, function (response, status) {
            if (status === google.maps.DirectionsStatus.OK) {
                $scope.directionsDisplay.setMap(null);
                $scope.directionsDisplay.setMap($scope.mapRef);
                $scope.directionsDisplay.setDirections(response);

            } else {
                console.log('Directions request failed due to ' + status);
            }
        });


    });
}

I hope this solution proves helpful!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Create a PHP form that includes text and image inputs with the help of AdminLTE and integrates DropZone.js

I have been working with a template from adminLTE and you can check it out at the following link: . At this point, I am trying to upload images first and then use the image names as input text elements in my main form for submission. However, I have encou ...

Is there a way to assign or initialize a Java array as a JavaScript array without relying on JSP?

I'm currently developing in the Play framework and I'm facing a challenge with using a Java array inside Javascript. My attempt so far is as follows - var jsarray = ${javaArray}; The javaArray refers to the array stored in the Java controller ...

Updating the view in AngularJS with a service to keep users engaged even when they are offline

I'm currently developing an application that requires the ability to detect when a user loses internet connection or is unable to reach the server. Various controllers and services should be able to check and update this status easily. I have successf ...

Transforming a base64 encoded string into a byte array

I have implemented a form where users can upload images to the page using an <input id = "fileLoader" type = "file" />. With JavaScript, I convert these uploaded images to base64 and send them to the server. On the server side, I need to decode this ...

Adding objects from an existing JSON file to an empty object in Node.js is a straightforward process

Looking to extract JSON data from a separate file and transfer it into a new object using Node JS. Despite trying various methods without success, I still can't figure out how to achieve this. Can anyone provide guidance or suggestions? Add new eleme ...

Sending files through ajax with php

Hey there! I've been working on uploading files using Ajax and PHP, following a tutorial. Here's the code I have so far: upload.js: var handleUpload = function (event){ event.preventDefault(); event.stopPropagation(); var fileInput= document.ge ...

Changing the shape of a background using CSS when hovering

My Bootstrap navigation has a unique setup, as shown below. I've observed that many users tend to only interact with the headings and ignore the submenus where the actual products are located. To address this issue, I want to change the design of th ...

Waiting for a React ref to become available after being rendered in a separate container: A guide

Revised: clearer explanation The scenario: A plain HTML code is received from a third-party server, with the intention to embed in a React application make modifications to it The traditional JavaScript approach The string can be modified using reg ...

Setting the date of an input type="date" based on the ng-model value can be accomplished by utilizing the ng-model directive

I need to display a date stored in the $scope variable on an input field type="date" when the page loads. <input class="form-control" type="date" ng-model="asso.formation_of_association" placeholder="" /> However, I am only able to ...

The absence of variable declaration in a 'for...of' loop is functional in .js files but does not work in

index.js let items = [{ item: 'apple' }, { item: 'banana' }, { item: 'orange' }]; for (item of items) { console.log(item); } Execute using node $ node index.js { item: 'apple' } { item: 'banana' } { ...

Trouble with transmitting props to function

The child component is not receiving the props as expected. When printed, it displays an empty object. The problem seems to be in the News.js file specifically related to passing props to the child component from App.js. All functions are operational excep ...

How do I retain the user's color choice using jQuery cookies for future visits?

I've created a jQuery color picker that allows users to save their color selection with just one click. You can see the color picker in action here: http://prntscr.com/7rnafa . To handle the saving of color selections, I'm using a helpful jQuery ...

After implementing the msw-storybook-addon, I encountered an error stating "Unexpected character '#' in node_modules/../Emitter.js."

Seeking to utilize mock servers for my stories, I encountered an error while setting up the Storybook with msw-storybook-addon. After following the steps outlined in both this and this resources (which have different instructions for preview.js), running t ...

Disappearing Act: The Vanishing React.js Dialog Component that Lurks

Currently, I am utilizing a Dialog component from Material-UI and, overall, it is functioning correctly. However, there is an issue where if I click away from the Dialog, it disappears as expected, but occasionally it remains in the DOM with an opacity of ...

The V-snackbar fails to show up after I make changes to the Vuex state

I am facing an issue with my <v-snackbar> component not showing when I update the Vuex state. The setup is straightforward: I have a snackbar in Snackbar.js, which listens for changes in the state. This Snackbar.js is then imported as a child compo ...

Is it a CSS or Javascript quirk when a div can become the child of the div before it?

On every browser I've checked, the code in the html is exactly the same: <td class="bardisplay"> <div class="bar hot" /> <div class="bar cool" /> </td> However, in the debugger of each browser, including Chrome, the DOM ...

Encountering an undefined i18next error

When trying to initialize i18next, I encountered the following error message: Uncaught TypeError: Cannot read property 'use' of undefined Here is the code snippet that is causing the issue: import i18n from 'i18next';// Getting eslin ...

Utilizing AJAX and JQuery to Load KML Data

Attempting to integrate a KML layer into Google Maps API 3.0 using a JQuery AJAX request. Here is the current code setup (currently not functioning). <script> $(document).ready(function(){ $.ajax({ url : 'https://blahhhhhhhhhh.com/KML_Pla ...

Exploring the power of using the splice function within a 2D array in

I've been working on this 2D array and I'm facing an issue where I need to remove rows that have 5 or more instances of the number "one". I attempted to use the splice method (a.splice(j,1)), but it's not producing the desired result. I susp ...

Why does the loginStatus in Redux become undefined when the component is initially rendered?

Currently diving into Redux and encountering a problem that is new to me as I usually work with React without redux. The issue arises when I attempt to showcase a portion of my state within a component named loginStatus. Despite setting up the state in the ...