Question

I'm having issues setting the visibility of custom Google Maps API v3 overlays. I have a gmaps API page with various overlay, such as polygons, polylines and symbols. Each has an associated text label, made using a custom overlay I adapted from the answer to [this Stack Overflow post][1]

On page load, the actual overlays (polylines, polygons, markers etc - the built in API objects) work correctly. They are displayed based on the default checkbox states. However, the labels are all displayed, regardless if their check box was set by default. If I cycle the checkboxes, everything works correctly.

The overlays are stored as an object called 'overlays' with layout 'description: [polyline, customoverlaylabel]'

Checkbox example code:

<input type="checkbox" id="sun" onclick="refreshCheck('sun')">Sun</input>

This is how I sync whether a display is hidden or visible to the checkbox:

  function refreshCheck(overlay) {
                var box = document.getElementById(overlay).checked
                var lines = overlays[overlay][0]
                var text = overlays[overlay][1]
                lines.setVisible(box, overlay)
                if (box === true) {
                    text.show()
                }
                else {
                    text.hide()
                }
            }

This code refreshes all the checkmarks, at the end of the javascript head.

var overlayNames = []
for (var k in overlays) overlayNames.push(k)
for (var o in overlayNames) refreshCheck(overlayNames[o])

Here's the hide method of the custom text overlay:

       TxtOverlay.prototype.hide = function(){
            if (this.div_) {
                this.div_.style.visibility = "hidden";
            }
        }

It's failing the if (this.div_) check, and not doing anything. If I remove the check, it produces an error since this.div_ doesn't exist.

One way to work around it would be to automatically cycle all checkbox states once the page loads (manually doing to solves it). There might be a more fundamental fix. No matter where I attempt to .hide() or .show() a label in my javascript, it doesn't work - it only works when referenced by the checkbox being clicked.

Was it helpful?

Solution

The issue is the moment when you call refreshChecks() .

You assume that the TxtOverlay's already have been added at this time, but that's not the case(that's why the div_'s are still null).

The TXToverlay's (like any object/shape) on a map will be added when the projection of the map is ready.

A possible approach would be:

Instead of using the visible-property of the shapes/markers/etc. to toggle their visibility use the map-property.

The TXTOverlay's are also MVCObject's, you only have to bind the map-property of the TXTOverlay's to the map-property of the related shape.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top