Search code examples
google-mapsgoogle-maps-api-3contextmenugmaps.js

How to toggle gmaps.js setContextMenu content in google map


I am working on google-map api using gmaps.js. I have a problem with google map's setcontextmenu.

When the user right-clicks the map, the context menu will appear. I tried to change the content of context menu option from "measure distance" to "stop measure distance".

Below is the code when the user right-clicks, it displays two menus: "measure distance" and "stop measuring". I want to toggle between the two. When the user clicks "measure distance" menu, I want the "measure distance" menu to disappear and the "stop measuring" menu to appear.

How can I do this? Any help would be appreciated so much.

I tried to put flag variable inside the contextmenu but it just didn't work.

map_2.setContextMenu({
 control: 'map',
 options: [
  {
   title: 'Measure Distance',
   name: 'measure_distance',
   action: function(e) {
    // some codes here
   }
  },
  {
   title: 'Stop Measuring',
   name: 'stop_measure_distance',
   action: function(e) {
    // some codes here
   }
  }
 ]
});

Solution

  • Why isn't the flag variable solution working for you? I just tried coding this real quick and it is working on my end, please test the below code:

    <script>
        var map;
        var flag = true;
    
        function initMap() {
            map = new GMaps({
                div: '#map',
                lat: -12.043333,
                lng: -77.028333
            });
    
            toggle();
        }
    
        function toggle() {
            if (map) {
                if (flag) {
                    map.setContextMenu({
                        control: 'map',
                        options: [{
                            title: 'Measure Distance',
                            name: 'measure_distance',
                            action: function(e) {
                                flag = false;
                                toggle();
                            }
                        }]
                    });
                }
                else {
                    map.setContextMenu({
                        control: 'map',
                        options: [{
                            title: 'Stop Measuring',
                            name: 'stop_measure_distance',
                            action: function(e) {
                                flag = true;
                                toggle();
                            }
                        }]
                    });
                }
            }
        }
    </script>
    

    Hope this helps!