-2

I've got a simple Google Map with two polygons defined and visible when a page loads.

I've tried adding buttons to turn off a polygon using ".setMap(null)", but it doesn't work for me.

Can you suggest a fix? I feel like I don't quite know enough without help. (you'll need a Google Maps API Key - sorry!).

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<title>Triangles</title>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?key=<MAPS KEY GOES HERE>"></script>
<script type="text/javascript">

function initialize() {
// Initialize a new map:
   const myLatLng = new google.maps.LatLng(55.73,-6.25);  // Center Point of map
   const myOptions = { zoom: 10, center: myLatLng, mapTypeId: google.maps.MapTypeId.HYBRID }; // Map options
   const map = new google.maps.Map(document.getElementById('map'), myOptions); // create "map"
// Define & draw a yellow triangle polygon:
   var yellowCoords = [ { lat: 55.828897, lng: -6.398249 }, { lat: 55.835067, lng: -6.126337 }, { lat: 55.674712, lng: -6.305552 } ];
   var yellowPolygon = new google.maps.Polygon({ paths: yellowCoords, strokeColor: 'yellow', strokeOpacity: .7, strokeWeight: 2, fillColor: 'yellow', fillOpacity: 0.2 });
   yellowPolygon.setMap(map);
// Define & draw a red triangle polygon:
   var redCoords = [ { lat: 55.668897, lng: -6.198249 }, { lat: 55.835067, lng: -6.026337 }, { lat: 55.674712, lng: -6.005552 } ];
   var redPolygon = new google.maps.Polygon({ paths: redCoords, strokeColor: 'red', strokeOpacity: .7, strokeWeight: 2, fillColor: 'red', fillOpacity: 0.2 });
   redPolygon.setMap(map);

} // end function initialize

function yellowOff() {
  yellowPolygon.setMap(null);
}
function redOff() {
  redPolygon.setMap(null);
}

</script>
<style> #map { height: 800px; width: 800px; }</style>
</head>

<body onLoad="initialize();">

<div id="map"></div>
<button onClick="javascript:yellowOff();" value="Click">Yellow Off</button>
<button onClick="javascript:redOff();" value="Click">Red Off</button>
</body>
</html>

Thank you!

user2571504
  • 53
  • 1
  • 6
  • 3
    You have an obvious scope issue. Your Javascript console tells you that. *Uncaught ReferenceError: redPolygon is not defined* (same for the yellow one). You cannot declare variables within the `initialize` function and use these variables outside of it (in your other functions). – MrUpsidown Nov 22 '22 at 09:01
  • https://stackoverflow.com/questions/500431/what-is-the-scope-of-variables-in-javascript – MrUpsidown Nov 22 '22 at 12:04

1 Answers1

-1

As per the comment by @MrUpsideDown regarding "Scope" You could either define these variables as globals and populate within the initialize function or keep everything contained within that initialize function as below. Further to that, by maintaining a single variable ( object literal in this case ) that contains references to the various polygons ( or other elements ) will allow easier manipulation of them when calling a function which is triggered by the buttons.

The buttons here will toggle the display of the polygons rather than simply hiding forever but to accomplish permanent hiding requires only a small change within the clickhandler callback.

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="content-type" content="text/html; charset=UTF-8" />
        <title>Triangles</title>
        <style>
            #map{
                width:100%;height:90vh
            }
        </style>
    </head>
    <body>
        <div id="map"></div>
        <button type='button' data-colour='yellow'>Yellow Off</button>
        <button type='button' data-colour='red'>Red Off</button>
        
        <script>
            function initialize(){
                const polygons={};
                const myLatLng=new google.maps.LatLng(55.73,-6.25);
                const myOptions = { 
                    zoom: 10,
                    center: myLatLng,
                    mapTypeId: google.maps.MapTypeId.HYBRID
                };
                const map = new google.maps.Map( document.getElementById('map'), myOptions );
                
                let yellowCoords = [ { lat: 55.828897, lng: -6.398249 }, { lat: 55.835067, lng: -6.126337 }, { lat: 55.674712, lng: -6.305552 } ];
                let yellowPolygon = new google.maps.Polygon({ paths: yellowCoords, strokeColor: 'yellow', strokeOpacity: .7, strokeWeight: 2, fillColor: 'yellow', fillOpacity: 0.2 });
                    yellowPolygon.setMap( map );

                let redCoords = [ { lat: 55.668897, lng: -6.198249 }, { lat: 55.835067, lng: -6.026337 }, { lat: 55.674712, lng: -6.005552 } ];
                let redPolygon = new google.maps.Polygon({ paths: redCoords, strokeColor: 'red', strokeOpacity: .7, strokeWeight: 2, fillColor: 'red', fillOpacity: 0.2 });
                    redPolygon.setMap(map);
                    
                polygons.yellow=yellowPolygon;
                polygons.red=redPolygon;
                
                const clickhandler=(e)=>{
                    let poly=polygons[e.target.dataset.colour]
                        poly.setMap( poly.getMap() ? null : map )
                }
                
                document.querySelectorAll('button[type="button"][data-colour]').forEach( bttn=>bttn.addEventListener('click',clickhandler) )
            }
        </script>
        <script src="//maps.google.com/maps/api/js?key=KEY&callback=initialize"></script>       
    </body>
</html>

jsFiddle to show result

Professor Abronsius
  • 33,063
  • 5
  • 32
  • 46