Customize Your Google Maps with Checkboxes for Style Options

Trying to make dynamic changes in the style of a Google Maps using checkboxes. Some checkboxes control colors of features, while others control visibility. Having trouble figuring out how to combine different features of styles since they are not strings.
Here's the code snippet:

<!DOCTYPE html>
<html>
  <head>
    <title>JS Bin</title>
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.7.js"></script>
    <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"> </script>
    <script type="text/javascript">

      var map;
      function initialize() {
          var myLatLng = new google.maps.LatLng(50.450, 30.522);
          myOptions = {
              zoom: 5,
              center: myLatLng,
              mapTypeId: google.maps.MapTypeId.ROADMAP
          };
          map = new google.maps.Map(document.getElementById('map-canvas'), myOptions)
      }

      //checkbox operation
      $(window).load(function(){
      $(document).ready(function () {
          $('input[type=checkbox]').change(function () {
            var checked = $(this).prop('checked');
            var selected = $("input:checked").map(function(i,el){return el.value}).get();

            //Display result in HTML
            document.getElementById("SHOW").innerHTML = selected;
          });
      });
      });
    </script>
  <body onload="initialize()">
    <div id="map-canvas" style="width:500px;height:300px"></div>
    Clear Labels<input type="checkbox" id="chkLbl" value='{"elementType": "labels", "stylers": [ { "visibility": "off" }]}'>
    <br>Clear Borders<input type="checkbox" id="chkBrd" value='featureType: "all",elementType:"geometry.stroke",stylers:[{ visibility:"on"}]'>
    <br>Change Water<input type="checkbox" id="chkBrd" value='{"featureType": "water", "stylers": [ { "visibility": "off" }]}'>

    <p id="SHOW"></p>
  </body>
</html>

Answer №1

Several issues: Avoid using $(window).load and body onload, as well as the "map" jquery function and the "get" function which may not be suitable for your needs. Additionally, you have a repeating ID for your checkboxes.

Refer to Google Maps JavaScript API documentation for guidance: https://developers.google.com/maps/documentation/javascript/3.exp/reference#Map

Here is an improved snippet of your code:

<!DOCTYPE html>
<html>
  <head>
    <title>JS Bin</title>
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.7.js"></script>
    <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"> </script>
    <script type="text/javascript">

      var map;
      function initialize() {
          var myLatLng = new google.maps.LatLng(50.450, 30.522);
          myOptions = {
              zoom: 5,
              center: myLatLng,
              mapTypeId: google.maps.MapTypeId.ROADMAP
          };
          map = new google.maps.Map(document.getElementById('map-canvas'), myOptions)
      }

      function setMapStyle(id) {
            var selected = $('#'+id).prop('checked');
            // Define style object based on "chkLbl","chkBrd","chkH2O" and invoke map.setStyle();
            $('#SHOW').html(/* insert desired content here*/);
      }

      //Checkbox behavior
      $(document).ready(function () {
          initialize();
          $('input[type=checkbox]').change(function () {
            setMapStyle($(this).attr('id');
          });
      });
    </script>
  </head>

  <body>
    <div id="map-canvas" style="width:500px;height:300px"></div>
    Clear Labels<input type="checkbox" id="chkLbl" value='{"elementType": "labels", "stylers": [ { "visibility": "off" }]}'>
    <br>Clear Borders<input type="checkbox" id="chkBrd" value='featureType: "all",elementType:"geometry.stroke",stylers:[{ visibility:"on"}]'>
    <br>Change Water<input type="checkbox" id="chkH2O" value='{"featureType": "water", "stylers": [ { "visibility": "off" }]}'>
    <p id="SHOW"></p>
  </body>
</html>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Struggling with implementing nested for loops

I am struggling to find a solution for this issue. I need to compare the content of two arrays with each other. If they are exactly the same, I want to execute the if statement; otherwise, I want the else statement to be executed. The current setup is ca ...

I'm having trouble grasping the sequence of events in this async example

Currently, I'm delving into the world of JavaScript and Node.js, but I find myself facing challenges with asynchronous execution. I have a piece of code that may not be following best practices, but I am eager to understand why the file remains open w ...

Ways to determine if the property of a document has been altered?

Currently, I am in the process of writing tests for an Express CRUD application. The specific route I am focused on is the account recovery route. This route accepts POST requests with an email included in the body. Essentially, the application will search ...

What is the best way to connect to my shop through RTK-Query API?

Is there a way to access my redux-toolkit store data from within the rtk-query endpoints? How can I retrieve information from my store in the query or transformResponse methods? import { createApi } from '@reduxjs/toolkit/query/react' import cus ...

passing arguments during deferred resolve() and when() operations

I am currently working on a flash card website and I need to determine the status of preloaded images once they have finished loading or if there was an error. After obtaining the status of each image, I will proceed with further actions. My code is inspi ...

What could be causing the issue with Hindi text not displaying properly on Safari?

I'm having trouble with displaying Hindi text on my website. I tried pasting the text in a new file and it worked, so why is it not loading correctly in this case? The Hindi script is within the second span with the class word w2. "use strict"; le ...

Firebase Issue in Next JS Authentication Flow: Unconfirmed Email Causes "auth/email-already-in-use" Error to Trigger

I have encountered a perplexing issue while setting up user registration with Firebase Authentication in my Next.js application. The problem arises when I try to register a new user with an unverified email address. Instead of following the correct flow to ...

Unspecified variable in AngularJS data binding with Onsen UI

I am new to Onsen UI and AngularJS, and I have a simple question about data binding. When I use the variable $scope.name with ng-model in an Onsen UI template, it returns as UNDEFINED. Here is my code: <!doctype html> <html lang="en" ng-app="simp ...

React: Issue with array rendering order after initial render

After the initial rendering of my array in the correct order, any subsequent changes to it result in the same rendered order. Let's consider this scenario: initializeArray() { this.state = { test_array: [1,2,3,4] } let self = t ...

Converting constants into JavaScript code

I've been diving into typescript recently and came across a simple code snippet that defines a constant variable and logs it to the console. const versionNuber : number = 1.3; console.log(versionNuber); Upon running the tsc command on the file, I no ...

Embedding a string within an image source attribute in VueJS

My goal is to extract the name of a job department as data for a Vue component, convert it to lowercase, and then use it to dynamically render the correct image based on the department's name. The images are named after the departments. The current c ...

What is causing the error message "Uncaught TypeError: Cannot read properties of null (reading 'push')" to be displayed when running this code?

I encountered an issue while trying to run this code which resulted in an Uncaught TypeError: Cannot read properties of null (reading 'push') console.log("HI"); let addbtn = document.getElementById("addbtn"); addbtn.addEventLi ...

Strategies for managing the "ref" property of Material-UI component props within our custom components

I have a unique custom component setup as shown below: // ... import { PaperProps, styled } from '@mui/material'; type ComponentProps = PaperProps & { a: string, b: string }; export const MyPaper = styled(Paper)(/* ... */); const Compo ...

Updating a specific element within an array using MongoDB

When looking to update a specific element in an array within a MongoDB collection. Here is an example of some MongoDB data: { _id: new ObjectId("63608e3c3b74ed27b5bdf703"), placename: "khulna", frnds: [ { name: "osama&qu ...

php script within a literal .tpl file

Is there a way to perform a json_encode within a literal javascript block in the context of a Smarty template? {literal} <script> function openWin() { var O = {php} echo json_encode($obj);{/php}; // syntax error ...

Making a Request on Behalf of a Component in Vue.js Using Interceptors

Within my Vue application, I've implemented a response interceptor: axios.interceptors.response.use(function (config) { return config; }, error => { if (error.response.status !== 401) { return new Promise((resolve, ...

Simple Mobile-Friendly Tabs - mobile tabs are always visible

My JavaScript skills are not the best. I have been using Easy Responsive tabs and encountered an issue on the mobile version where clicking does not hide content, but only removes the "d_active" class and adds it to another element. I believe that if the ...

Ways to access PromiseValue in XMLHttpRequest with JSON

Is there a way to access an array that is within the PromiseValue instead of receiving Promise {<pending>} When I use .then(data => console.log(data)), I can see the array in the console log. However, my requirement is to display this array on an ...

Tips for Preserving the HTML Page State After Making jQuery Changes

Hi there! I am currently working on developing a card game using HTML5, CSS3, and Javascript. This game will communicate with a server built on node.js, facilitated by socket.io for data transmission. One of the key features I am trying to implement is th ...

Swapping out pages with JSON outcomes is a common practice when utilizing ASP.Net MVC in conjunction with JQuery Ajax

When making an ajax call to update an entity and returning the success state in the MVC controller, I encountered a problem that resulted in the page changing with the URL becoming that of the MVC controller action and displaying the JSON result as content ...