The error "marker.setMap not a function" was not caught in the Google Maps API

Currently, I am creating a traffic jam application using MeteorJS 1.4.4.2 + ReactJS. Previously, I have utilized the atmosphere google map package and two popular Google Map npm packages (istarkov and tomchentw), which worked well but did not offer the specific feature I required. Thus, I decided to integrate the Google Maps API directly in order to access its complete set of features.

My main objective was to have the ability to remove selected markers on the map

My Attempt:

// In the same file as the mapInit function

let addMarker = (location) => {

    let marker = new google.maps.Marker({

        position: location,
        map: map,
        animation: google.maps.Animation.DROP,
        draggable: true

    }).addListener('click', (e) => removeMarkerOnClick(e));

    markers.push(marker);

};

let removeMarkerOnClick(marker) => {

    let lat = marker.latLng.lat(),
        lng = marker.latLng.ln(),
        position = {};

    markers = markers.reduce((new_markers, marker) => {

        position = marker.f.position;

        if (position.lat() !== lat && position.lng() !== lng) {
            new_markers.push(marker);
        } else {
            marker.setMap(null);
        }

        return new_markers;

    }, markers);

}

window.initMap = () => {

    //.... body hidden

    map.addListener('click', (e) => addMarker(e.latLng));

}

Error from client console:

Uncaught TypeError:
    MapFunctions.jsx:74
    marker.setMap is not a function
     at http://localhost:3000/app/app.js?hash=1f01aac45aac6af0dd009bc4623183b2511f62bf:419:20
at Array.reduce (native)
at removeMarkerOnClick (http://localhost:3000/app/app.js?hash=1f01aac45aac6af0dd009bc4623183b2511f62bf:413:23)
at _.Ge.<anonymous> (http://localhost:3000/app/app.js?hash=1f01aac45aac6af0dd009bc4623183b2511f62bf:403:16)
...

Possible Solutions Tried:

  1. Attempting to use setOnMap(null) also resulted in the same error, setOnMap() is not a function

  2. Trying marker.setVisibility(false) also led to the same issue, ... not a function

After extensive searching online for an hour and a half, I have yet to find a solution. Any assistance would be greatly appreciated. Thank you for taking the time to read this.

Answer №1

Ensure you are passing the marker instead of the event in the function call.

}).addListener( 'click', ( e )=> removeMarkerOnClick( e ) ); 

replace it with:
}).addListener( 'click', ( e )=> removeMarkerOnClick( marker ) );

Answer №2

Apologies for any inconvenience caused if you are seeking a solution to this problem. While searching for the Marker object, I experimented with a different example of the marker and examined the marker object through console log to identify any discrepancies. Ultimately, I realized that my marker object was nested within another top-level object, requiring me to navigate one level deeper in order to access the setMap function. Resolution:

let removeMarkerOnClick( marker )=> {

    let lat = marker.latLng.lat (),
        lng = marker.latLng.ln (),
        position = {};

    markers = markers.reduce(( new_markers, marker )=> {

        position = marker.f.position;

        position.lat() !== lat && position.lng() !== lng ?

        new_markers.push( marker ) : marker.f.setMap ( null ); // Change this line from marker.setMap( null ) to marker.f.setMap ( null )

        return new_markers;

    }, markers);

}

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

Special function to handle ajax requests malfunctioning

I am seeking to develop a unique function for AJAX post requests. Below is the existing source code: function handleAjax(url, data) { var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function() { if (xhr.readyState == 4 && xhr.st ...

Using AngularJS, learn how to populate array objects within a JSON object

I'm trying to load array objects from a multi-select control, then populate a model object called "name" with its name and age values. After that, I want to load an array from a select element into the model object. However, the ng-model directive on ...

How can you use JavaScript to determine the width of a CSS element?

Is there a way to make the VarDisk2 element disappear when the width of VarDisk1 exceeds 70? <script> var VarDisk1 = document.querySelector("Disk1"); var VarDisk2 = document.getElementsByClassName("Disk2"); ...

Tips for implementing a confirmation dialogue box prior to submitting a form:

As a new developer, I am facing an issue that I believe you can help me with. I want to display a confirmation box before deleting. How can I achieve this in my Ajax code? HTML: <input type='button' class="btn btn-danger delete_button" id="de ...

What causes getServersideprops to return undefined?

The data I am trying to fetch is showing as undefined in the console. Here is the code snippet: export default function Home({ data }) { console.log(data); return ( <div> <h2>Welcome !!</h2> </div> ); } export a ...

Guide on invoking Objective-C function from JavaScript on iOS

I'm currently working on integrating Highchart into an iOS app. I have a requirement where I need to pass values from JavaScript (HTML file) to an Objective-C method. For example, when a user zooms in on the chart displayed in a UIWebView using Highch ...

What is the process for declaring an exported type variable in React?

I have created a unique configuration in a different file: //config.js export const config = [ { id:0, name:"Config 1", }, { id:1, name:"Config 2", }, { id:2, name ...

Extracting every other value from an array can be achieved by iterating through the

Hi, I'm looking to create a function that will log every other value from an array. For example, if we have: var myArray = [1,45,65,98,321,8578,'orange','onion']; I want the console.log output to be 45, 98, 8578, onion... Does ...

Working with Ext JS: Dynamically adjusting panel size when the browser window is resized

I am facing an issue with a side panel in Ext.js. Everything is working fine until I resize the browser, at which point some components of the panel get cut off. https://i.sstatic.net/eaEGI.png Is there a way to make the panel resize automatically when t ...

Unable to retrieve dropdown value using JavaScript and display it in a div

javaScript code: Retrieving data from a dropdown and displaying it in the inner HTML of a div. function showcost() { var days = document.getElementById("Ddays"); var Dudays = days.options[days.selectedIndex].text; var div = docu ...

Unclear outcomes from iterative loops

I have a question about this particular for loop: for (var i=0,j=0;i<4,j<20;i++,j++) { a=i+j; } console.log(a); Can someone explain why the output is 38? I initially expected it to be 6. ...

Struggling to make AngularJS routes function properly

After starting from scratch, I rebuilt it with freshly downloaded angularJS (version 1.5.8). I simply placed both angular.js and angular-route.js in the library folder following this setup: https://gyazo.com/311679bf07249109671d621bc89d2d52 Here is how in ...

Preventing page refresh when typing in a form input: Tips and tricks

I'm currently puzzled by a small issue. In my web application, I have a chat box that consists of an input[type='text'] field and a button. My goal is to send the message to the server and clear the input field whenever the user clicks the b ...

We encountered a ReferenceError stating that 'dc' is not defined, despite having already imported d3, dc, and crossfilter in

In my current angular project, I have included the necessary imports in the component.ts file in the specific order of d3, crossfilter2, dc, and leaflet. Additionally, I have added the cdn for dc-leaflet.js in the index.html file. Despite these steps, wh ...

Exploring the World of Github on Windows: Understanding the 'master' and 'gh-pages' Branches

I have developed a simple jQuery plugin and uploaded it to Github. I am using both the Github website and Github for Windows to manage this project. However, when I try to include the .js or .css files from Github using the Raw links, my browser fails due ...

AngularJS encountering unresponsive resources

When setting up my Angular App, I include various resources like this: angular.module('myApp', ['infinite-scroll', 'chieffancypants.loadingBar', 'ngResource']) Next, in the html file: <script type="text/javascr ...

Which is better for creating hover effects: CSS3 or JavaScript?

When hovering over a link, I want to highlight a specific picture and blur the rest. Here's my HTML code: <body> <div id="back"> <div id="one"></div> <div id="two"></div> </div> ...

Load only specific columns in jqGrid to enhance performance and streamline data display

When working with jqGrid, I have implemented selectable columns to display only certain columns. Now I need to figure out how to store the selected column names in a database so that when loading the grid again, only those selected columns are displayed. ...

Compare several objects or arrays based on a selected array and combine them into a single object containing all matching elements from the selected array

selection = ["A", "lv3", "large"] Data = [{ id:1, title:"this is test 1", category:"A, D", level:"lv5", size: " medium", }, id:2, title:"this is test 1", category:"C ...

Use JavaScript to dynamically add CSS styles to elements before and after a button wrapper

My code seems simple, but for some reason it's not working. I'm trying to add CSS styles to a button when there is a div with the class .wp-block-group both before and after the button. $(".btn-superimposed-wrapper").each(function () ...