Home > Enterprise >  Google Maps Controls ID
Google Maps Controls ID

Time:12-30

I am trying to write content to a google maps control div, my prefered way being to use jquery selector with div id. The problem is that the map only seems to take the actual element referenced by variable to change it, instead of its ID.

This is exampled by the bottom control 'testcontrol_2' able to have its background changed, however 'testcontrol_1' referenced by ID remains white.

My question is why am I able to write content to the map controls with an actual html element as a jQuery selector, but not an element id.

Fiddle: screenshot of resulting map

code snippet:

<html>

  <head>
    <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <style>
      html, body {
        width: 100%;
        height: 100%;
        padding: 0px;
        margin: 0px;
      }
      .mapframe {
        width: 100%;
        height: 100%;
      }

      .mapcontrol {
        padding: 1em;
        background-color: #ffffff;
      }

    </style>
  </head>

  <body>
    <div id="mapframe" ></div>
    <script>
      var map;
      var centerControlContainer;
      var centerControlId = 'mainCenterControlFrame';
      var testControl2;

      function mapinit() {
        let mapinit = {
          center: new google.maps.LatLng(51.509865, -0.118092),
          zoom: 10,
          minzoom: 15,
          maxzoom: 21,
        };
        map = new google.maps.Map(document.getElementById('mapframe'), mapinit);
        google.maps.event.addListenerOnce(map, 'tilesloaded', function() {
          GMapready();
        });
      }

      function GMapready() {
        centerControlContainer = document.createElement('div');
        $(centerControlContainer).addClass('mapControlContainer');
        $(centerControlContainer).attr('id', centerControlId);
        $(centerControlContainer).html('<div id="testcontrol_1" >TestControl1</div>');

        testControl2 = document.createElement('div');
        $(testControl2).attr('id', 'testcontrol_2');

        $(testControl2).html('TestControl2');
        $(testControl2).addClass('mapcontrol');
        $(centerControlContainer).append(testControl2);

        this.map.controls[google.maps.ControlPosition.TOP_CENTER].push(this.centerControlContainer);

        setTimeout(function() {
          $('#testcontrol_1').css('background-color', '#ff0000');
        }, 100);
        $(testControl2).css('background-color', '#ff0000');

      }

      mapinit();

    </script>
  </body>

</html>

  • Related