Search code examples
javascriptjqueryjquery-gmap3

Gmap3 Clear Directions


I need to recalculate the directions, when another marker is clicked or when my origin marker is dragged to another location.

at the moment, I am inserting a marker when a user inserts his/her address then when the users clicks on any existing marker it calculates the directions. Unfortunately it doesn't clear the previous directions.

Any Help at all will be greatly appreciated.

Here's the code:

jQuery(document).ready(function() {
jQuery.getJSON('./index.php', {
 option: "com_locate",
 view: "branches",
 tmpl: "component",
 format: "json",
},
 function(json){
      jQuery(function(){      
    jQuery("#googleMap").gmap3({
      map:{
        options: {
          center:[-29.8191,25.3499],
          zoom: 5,
          mapTypeId: google.maps.MapTypeId.ROADMAP,
          mapTypeControl: false,
          streetViewControl: false
        }
      },
      marker: {
        values: json,
        options: {
          icon: new google.maps.MarkerImage("http://maps.gstatic.com/mapfiles/icon_green.png")
        },
        events:{
          mouseover: function(marker, event, context){
            jQuery(this).gmap3(
              {clear:"overlay"},
              {
              overlay:{
                id: "tooltip",
                latLng: marker.getPosition(),
                options:{
                  content:  "<div class='infobulle"+(context.data.drive ? " drive" : "")+"'>" +
                              "<div class='bg'></div>" +
                              "<div class='text'>" + context.data.city + " (" + context.data.telephone + ")</div>" +
                            "</div>" +
                            "<div class='arrow'></div>",
                  offset: {
                    x:-46,
                    y:-73
                  }
                }
              }
            });
          },
          mouseout: function(){
            jQuery(this).gmap3({clear:"overlay"});
          },

          click: function(marker, event, context){
              markerSelected(context.id);
            }
           }
        }
    });
    ///////////////
    jQuery('#test-ok').click(function(){
      var addr = jQuery('#test-address').val();
      if ( !addr || !addr.length ) return;
      jQuery("#googleMap").gmap3({
        getlatlng:{
          address:  addr,
          callback: function(results){
            if ( !results ) return;
            jQuery("#googleMap").gmap3({
                clear:{id:"user"}
                },
                {
              marker:{
                latLng:results[0].geometry.location,
                id:"user",
                name:"user",
                options:{
                  draggable: true
                }
              },
                map:{
                  center: true,
                  zoom: 5
              }
            });
          }
        }
      });
    });

    jQuery('#test-address').keypress(function(e){
      if (e.keyCode == 13){
        jQuery('#test-ok').click();
      }
    });

    ///////////////
    ///////////////
    function markerSelected(id){
    var marker = jQuery('#googleMap').gmap3({get:id});
    var usermarker = jQuery('#googleMap').gmap3({get:"user"});
    jQuery("#googleMap").gmap3({
      getroute:{
        options:{
            origin:[usermarker.getPosition().lat(),usermarker.getPosition().lng()],
            destination:[marker.getPosition().lat(),marker.getPosition().lng()],
            travelMode: google.maps.DirectionsTravelMode.DRIVING
        },
        callback: function(results){
          if (!results) return;
          jQuery(this).gmap3({
            map:{
              options:{
              }
            },
            directionsrenderer:{
              container: jQuery(document.createElement("div")).addClass("googlemap").insertAfter(jQuery("#googleMap")),
              options:{
                directions:results
              }
            }
          });
        }
      }
    });

  } 
  });
  });
  });

Solution

  • The code you're using creates a new DOM element each time you do a directions request, without removing any existing such elements or replacing content in any existing elements. The pertinent part of your code is this:

        directionsrenderer:{
          container: jQuery(document.createElement("div")).addClass("googlemap").insertAfter(jQuery("#googleMap")),
            // The above creates a new DOM element every time markerSelected() is called!
          options:{
            directions:results
          }
        }
    

    You want to create that only once. If you want, you can do it directly in the HTML markup.

    Use the below as a replacement for your getroute callback function. I've plugged in a unique ID for the container element and left the "googlemap" class intact in case it's needed for CSS or other sections of code. Since you specifically want only one set of directions to be visible, though, let's select your container by ID.

    callback: function(results){
      if (!results) return;
      if (!jQuery("#dircontainer").length>0) {
        jQuery("<div id='dircontainer' class='googlemap'></div>").insertAfter("#googleMap");
      } // Creates your directions container if it doesn't already exist.
      else {
        jQuery("#dircontainer").html("");
      } /* I'm clearing the existing contents of the container in case gmap3 doesn't
           automatically clear it when the new directions are inserted.
           You can experiment with removing this else statement. */
      jQuery(this).gmap3({
        map:{
          options:{
          }
        },
        directionsrenderer:{
          container: jQuery("#dircontainer"),
          options:{
            directions:results
          }
        }
      });
    }
    

    I'm making some assumptions here about the way the gmap3 plugin works; I've worked with jQuery and the Google Maps JS API, but not with this plugin.