Utilizing an external link to dynamically modify the zoom level of a Google map

I've been struggling for hours to adjust the zoom level of a Google map using an onClick JavaScript function. It seems like my variable "map" is inside the initialize function of the map, which might be causing it not to work, but I'm not completely sure. Thank you in advance for any help you can provide.

Here's how it looks:

1) My initialize function (including galleries related to marker data)

  function initialize() {
      var styles = [
        {
          stylers: [
            { hue: "#486FD5" },
            { saturation: 10 },
            { lightness: 20 },
            { gamma: 1.1 }
          ]
        },{
          featureType: "road",
          elementType: "geometry",
          stylers: [
            { lightness: 40 },
            { visibility: "simplified" }
          ]
        },{
          featureType: "road",
          elementType: "labels",
          stylers: [
            { visibility: "off" }
          ]
        }
      ];

      var mapOptions = {
          zoom: 6,
          center: new google.maps.LatLng(46.8,1.7),
          mapTypeId: google.maps.MapTypeId.ROADMAP,
          disableDefaultUI: false,
          scrollwheel: false,
          styles: styles
      }

      var map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
      setMarkers(map, galeries);
  }

  function setMarkers(map, locations) {
      var image = '/wordpress/wp-content/uploads/logo-25.png';
      for (var i = 0; i < locations.length; i++) {
          var galeries = locations[i];
          var myLatLng = new google.maps.LatLng(galeries[1], galeries[2]);
          var infoWindow = new google.maps.InfoWindow();
          var marker = new google.maps.Marker({
              position: myLatLng,
              map: map,
              icon: image
          });
          (function(i) {
              google.maps.event.addListener(marker, "click", function() {
                  var galeries = locations[i];
                  infoWindow.close();
                  infoWindow.setContent(
                      "<div id='boxcontent'><a href='"+galeries[3]+"'><strong style='color:black'>"+ galeries[0] +"</strong></a><br />"+ galeries[4] +"</div>"
                  );
                  infoWindow.open(map, this);
              });
          })(i);
      }
  }

google.maps.event.addDomListener(window, 'load', initialize);

2) My onClick function (with comments indicating unsuccessful attempts):

function zoom() {
    //map_canvas.setCenter(marker.getPosition()); 
    //map.setZoom(map.getZoom() + 1);
    //map.setZoom('3');
    //$('#map_canvas').gmap({'zoom':2});
    //$('#map_canvas').setZoom(3);
    //google.maps.map.setZoom(2);
    //var carte = google.maps.Map(document.getElementById('map-canvas'));
    //carte.setZoom(2);
    //this.map.setZoom(2);
}

3) Result: nothing happens, and I receive the following error message in the console:

Uncaught TypeError: Cannot read property 'setZoom' of undefined

Answer №1

If you declare your map variable as global, it enables access in HTML click event handlers.

function zoom() {
    map.setZoom(map.getZoom() + 1);
}

var map; // declaring map variable as global

function initialize() {
  ...
  // initialize the global variable, remove the "var" keyword here
  map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
  setMarkers(map, galeries);
}

working fiddle

working code snippet:

function zoom() {
    map.setZoom(map.getZoom() + 1);
}

var map;

function initialize() {
    var styles = [{
        stylers: [{
            hue: "#486FD5"
        }, {
            saturation: 10
        }, {
            lightness: 20
        }, {
            gamma: 1.1
        }]
    }, {
        featureType: "road",
        elementType: "geometry",
        stylers: [{
            lightness: 40
        }, {
            visibility: "simplified"
        }]
    }, {
        featureType: "road",
        elementType: "labels",
        stylers: [{
            visibility: "off"
        }]
    }];

    var mapOptions = {
        zoom: 6,
        center: new google.maps.LatLng(46.8, 1.7),
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        disableDefaultUI: false,
        scrollwheel: false,
        styles: styles
    }

    map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);

    var galeries = [
        ['Bondi Beach', -33.890542, 151.274856, 4],
        ['Coogee Beach', -33.923036, 151.259052, 5],
        ['Cronulla Beach', -34.028249, 151.157507, 3],
        ['Manly Beach', -33.80010128657071, 151.28747820854187, 2],
        ['Maroubra Beach', -33.950198, 151.259302, 1]
    ];
    setMarkers(map, galeries);
}

function setMarkers(map, locations) {
    var bounds = new google.maps.LatLngBounds();
    var image = 'http://maps.google.com/mapfiles/ms/icons/blue.png';
    for (var i = 0; i < locations.length; i++) {
        var galeries = locations[i];
        var myLatLng = new google.maps.LatLng(galeries[1], galeries[2]);
        bounds.extend(myLatLng);
        var infoWindow = new google.maps.InfoWindow();
        var marker = new google.maps.Marker({
            position: myLatLng,
            map: map,
            icon: image
        });
        (function (i) {
            google.maps.event.addListener(marker, "click", function () {
                var galeries = locations[i];
                infoWindow.close();
                infoWindow.setContent(
                    "<div id='boxcontent'><a href='" + galeries[3] + "'><strong style='color:black'>" + galeries[0] + "</strong></a><br />" + galeries[4] + "</div>");
                infoWindow.open(map, this);
            });
        })(i);
    }
    map.fitBounds(bounds);
}

google.maps.event.addDomListener(window, 'load', initialize);
html, body, #map_canvas {
    height: 500px;
    width: 500px;
    margin: 0px;
    padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div id="map_canvas" style="width:750px; height:450px; border: 2px solid #3872ac;"></div>
<input type="button" value="zoom" onclick="zoom()" />

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

Issue with Vue.js: The input value text is not being updated

In my current setup, I am dealing with an input component that is linked to a variable called 'searchText' in the parent component. This variable stores the text value of the search input. The {{searchText}} in the template updates accurately bas ...

Guidelines for transferring data when a button is held down or pressed

I am looking to continuously send values while a button is pressed. Currently, a value is only sent with each click. Below is the current code: my_custom_script.js $(document).ready(function() { $('#left').mousedown(function() { var left ...

Achieving consistent outcomes across various devices: What's the secret?

Hey there, I am facing an issue with my form page that I created using HTML, CSS, and Javascript. It looks good on my computer but appears messy on a mobile phone. The elements are getting out of the white box (div) making the entire page look chaotic. Sin ...

Organize data in a Vue.js table

Currently facing an issue with sorting my table in vue.js. Looking to organize the table so that campaigns with the highest spend are displayed at the top in descending order. Here is the code I'm working with: <template> <div class=" ...

How to Retrieve the Current div's ID in VueJS

When using the v-for directive to dynamically generate an id for my div, I need to pass this unique id to a specific function. <div v-for="(item, index) in items" :key="index" :id="'form' + index" > ...

Step-by-step guide on how to include the "content-based-recommender" package in a Reactjs project

I recently started learning React.js and I'm interested in using the "Content-Based Recommender" package from npm. However, after downloading it, I encountered an issue with importing it. The documentation suggests the following: const ContentBasedRec ...

The 'Cross domain jQuery Ajax request using JSONP' triggered an error: SyntaxError - Unexpected token : appeared on the screen

I've been struggling to extract information from the steam api, encountering persistent difficulties due to the error mentioned above. Below is the snippet of code I have been utilizing: var steamurl = "https://api.steampowered.com/IDOTA2Match_570/Ge ...

default choice in dropdown menus

I need to populate my option fields with data retrieved from a database. I encountered an error in the console: Error: [$compile:ctreq] Controller 'select', required by directive 'ngOptions', can't be found! I am confident that t ...

Leveraging the power of async to streamline the serialization of operations with numerous layers of callbacks in Node

I'm relatively new to working with node.js and I'm encountering difficulties in understanding callback functions. The issue arises when I need to execute a series of complex operations that involve a lot of code divided into modules with numerous ...

Activate a modal component in ReactJS when a click event occurs

I'm having trouble integrating ReactStrap Modal into my NavBar and I haven't found a solution yet. I created a handler function to be triggered on a click event, but I can't figure out how to call my login component from this handler functio ...

Is it possible to sort by two properties where one takes precedence, even if they share common values?

Query: Can you guide me on sorting my data array based on two criteria: Ensure that the type is prioritized at the top. Arrange the counts from smallest to largest. Here's what I've tried so far: var data = [ {type: 'first', count ...

Delay the closure of a window by utilizing a straightforward method when selecting the "X - CLOSE" option with the following code: `<a href="javascript:window.open('', '_self').close();">X - CLOSE</a>`

I need to implement a delay when users click on the link to close a window. The purpose of this delay is to allow time for playing random "signoff" audio files, such as "Thanks!" or "See you next time!". Currently, without the delay, the audio stops abrupt ...

Parsing JSON data in JavaScript with multiple objects

I just received a JSON Object from an HTTP request [ { "location": { "name": "Seattle, WA", "lat": "47.604", "long": "-122.329", "timezone": "-7", "alert": "", "degreetype": "F", "imagerelativeurl": "http:&b ...

Creating a specialized feature for saving form data with React Admin

Within my react-admin application, I am faced with a scenario where I have a list of items accompanied by two separate buttons: "Create using email" and simply "Create". The "create" button utilizes the functionality provided by the data provider, which is ...

Shadowing jQuery variables involves declaring a new variable with the

There seems to be an unusual pattern used in jQuery: var jQuery = (function() { // This local copy of jQuery is defined within a closure var jQuery = function( selector, context ) { ... return jQuery; })(); Why was this approach chosen? Instead of exp ...

Dynamically loading JQuery causes highcharts to encounter errors

I have limited experience with JavaScript programming, and I've been encountering a persistent issue for quite some time now. Any assistance on this matter would be greatly appreciated. In the provided jsfiddle example, when jQuery is selected from t ...

What is the functionality of Mongoose for handling multiple updates?

Array; arr=[ { id: [ '5e6e9b0668fcbc7bce2097ac', '5e6e9b0e68fcbc7bce2097af' ], color: [ 'a', 'b' ] } ] Models; const varyant = Models.varyant function; Promise.all( arr.map((item)=>{ return var ...

Error encountered while exporting TypeScript module

While I am working with Angular, TypeScript, and Gulp, my module system is CommonJS. However, I encountered an error when trying to import a module into my main.ts file: Error: Cannot find external module 'modules.ts'. Here is the snippet from ...

Sending DOM values to React components as properties

Forgive me if this question seems basic, as I am still learning ReactJs. I have a react component that displays the user's sign-in status: <AccountStatus iconsize="medium" activate={[true,false,true]}/> Image 1 //or using <AccountStatus i ...

Extract particular information from the JSON reply

When working with a JSON response in JavaScript, I use the following code to convert it to a string: var myObject = JSON.stringify(data); Although this code successfully prints out the results, I am having trouble extracting specific data such as myObjec ...