The functionality of this.clusterer is not defined when trying to add a marker using this.clusterer.addMarker(marker);

I'm encountering an error message that says this.clusterer is undefined. Below is an overview of my configuration.

Expected behavior: The page should load, then AJAX-load the markers from the controller using the query defined in #search_form. Finally, the markers should be added to the #map and clustered.

This is my js.coffee file:

$ ->
  handler = Gmaps.build('Google');
  handler.buildMap { provider: {center: new google.maps.LatLng(49.639177, 9.536133),zoom: 6}, internal: {id: 'map'}},
    ()->
      handler._createClusterer()

  markers = []
  placeMarkers = (data, textStatus, jqXHR) ->
    handler.removeMarkers(markers);
    markers = handler.addMarkers(data)  # <<--- error occurs here

  $("#search_form").submit (e) ->
    valuesToSubmit = $(this).serialize
    $.ajax({
      url: $(this).attr("action"),
      data: valuesToSubmit,
      success: placeMarkers,
      dataType: 'json'
    })
    e.preventDefault

  $("#search_form").submit()

And this is the Controller:

def index
respond_to do |format|
  format.html {}
  format.json {
    seminars = Seminar.search(params[:search])
    @markers = Gmaps4rails.build_markers(seminars) do |seminar, marker|
    return if seminar.location.is_a? String
      marker.lat seminar.location.lat
      marker.lng seminar.location.lon
      marker.infowindow render_to_string(:partial => 'seminars/seminar.html.haml', :locals => {seminar: seminar})
      marker.title seminar.course.title
      marker.json({ :id => seminar.id })
    end
    render json: @markers
  }
end

end

And the response from the controller:

[{"lat":52.517,"lng":13.3889,"marker_title":"Title1","id":1},
 {"lat":51.5114,"lng":7.46517,"marker_title":"Title2","id":3}]

Here is the stacktrace:

Gmaps.Objects.Handler.Handler.addMarker (application.js:22417)
(anonymous function) (application.js:22409)
_.map._.collect (application.js:21094)
Gmaps.Objects.Handler.Handler.addMarkers (application.js:22408)
placeMarkers (application.js:23263)
jQuery.Callbacks.fire (application.js:3049)
jQuery.Callbacks.self.fireWith (application.js:3161)
done (application.js:8236)
jQuery.ajaxTransport.send.callback (application.js:8779)

Version: gmaps4rails-2.1.1

Answer №1

It's quite peculiar, but I am unable to replicate the issue anymore...

I believe the solution was to include the $("#search_form").submit() in the onMapLoad handler.

$ ->
  handler = Gmaps.build('Google');
  handler.buildMap { provider: {center: new google.maps.LatLng(49.639177, 9.536133),zoom: 6}, internal: {id: 'map'}},
    ()->
      $("#search_form").submit()

Big thanks for your guidance @apneadiving

Answer №2

I encountered similar challenges recently. Essentially, what @apneadiving suggested was quite accurate: the issue lies in the timing when ajax calls are made before the callback handler of buildMap has completed.

Resolution: One option is to initiate ajax calls only from within the callback handler (i.e., serialized) or, alternatively, a method that I personally prefer is to utilize callbacks with setTimeout within your ajax response. This approach can enhance the responsiveness of your application by allowing calls and processing to occur more concurrently.

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

Include the JS file after finishing the control processing

I've been grappling with an issue for several days now. The view I have is populated by my controller through an API call, which works perfectly fine in rendering the HTML. $http.get(url). success(function(data, status, headers, config) { ...

How to automatically reset a form after submission in React using Ant Design?

When using the antd template for form design, I encountered an issue where form input values were not getting cleared after submission. I attempted to use this.props.form.resetFields(), but it resulted in the following error: Unhandled Rejection (TypeErro ...

What is the best way to store chat messages in a React application?

My idea for a chat application using React involves saving chat messages in localStorage. Below is the code snippet that illustrates this functionality: const [textMessages, setTextMessages] = useState([]); const [textValue, setTextValue] = useState(' ...

Executing numerous tests on a single response using Node.js along with Chai, Mocha, and Should

I have a setup similar to the one below that allows me to perform a series of API tests using Mocha. While this method works well, it involves making an individual API call for each test. My goal is to streamline the process by utilizing the same API cal ...

Is there a way to manipulate a website's HTML on my local machine using code?

I am currently working on a project to create a program that can scan through a website and censor inappropriate language. While I have been able to manually edit the text using Chrome Dev tools, I am unsure of how to automate this process with code. I ha ...

What is the best way to implement a JavaScript pattern matching for both "aaaa" and "aaa aaa"?

Can anyone help me create a pattern that can accept both strings with spaces and without spaces in the same text box? I would appreciate any guidance on how to achieve this. Thanks! ...

Tips for extracting information from a JSON file using $routeParams in AngularJS

https://i.stack.imgur.com/NQCpy.png I am currently encountering an issue with retrieving data using $routeparams. Here is a description of my problem: Retrieving the URL to redirect console.log($routeParams); console.log($routeParams.json_url); $.getJS ...

Managing both clicking and hovering events on a single element, ensuring that the popup modal remains open as long as it is being hovered over

After successfully implementing click and hover functionality on an element, I was able to position the popup relative to the mouse pointer based on a previous solution. However, I am now facing an issue where I want the popup modal to be fixed in a specif ...

The issue of Ng-Route not functioning properly on a Node/Express static server

I need assistance with my app.js file that currently directs all requests to pages/index.html. Now I am attempting to utilize Angular to route user requests for '/#/media' by adding the following code: academy.config(function($routeProvider) { ...

"Exploring the world of Mean.js with Node.js background functionalities

Struggling with my mean.js app as I try to figure out how to implement background processes. I want these processes to run continuously, interacting with the mongodb database and handling tasks like cleanup, email notifications, and tweets. I need access ...

Locating specific text within an <li> element using the provided value

So, I have this set of words: <li>name</li> <li>myname</li> <li>yourname</li> Then there's also an input box input type="text" value="name" id="the_value" with the value "name", along with a submit button identif ...

Trouble with parseJSON when handling form POST in Python

I'm struggling with a javascript HTML page that has an action POST to a python file, expecting a JSON response back. Despite my efforts, I can't figure out how to catch and parse the JSON data. The HTML and python code excerpts below should show ...

Node.js sends a request to open a new GET method, querying the specific HTML file at "what.should.I.put.here.html/getAll", with the option for

After designing the majority of my website, I decided to host it on a school-based hosting service. My files are organized into two folders: a client folder with my html pages and main.js file, and a server folder containing the API that main.js accesses. ...

The Flask AJAX request is returning an empty ImmutableMultiDict, whereas the same AJAX request successfully works with http.server

Making the switch from http.server to Flask has caused issues with my image upload functionality using AJAX. This is being done in Python 3. Attempts at troubleshooting that have failed: I have ensured multipart/form-data is included in the Ajax req ...

What is the best method to verify a string against a set of approved characters using JavaScript?

I have written some code that sanitizes user input to allow only alphanumeric characters and hyphens. Here is the code snippet: https://jsfiddle.net/py4pnr0L/ const inputValue = 'GHJHlk;sxa787BVK'; const sanitizedValue = inputValue.toLowerCase( ...

I am facing an issue with TypeScript as it is preventing me from passing the prop in React and Zustand

interface ArticuloCompra { id: string; cantidad: number; titulo: string; precio: number; descuento: number; descripcion: string; imagen: string; } const enviarComprasUsuarios = ({ grupos, }: { grupos: { [key: string]: ArticuloCompra & ...

Ensuring Map Safety in Typescript

Imagine having a Map structure like the one found in file CategoryMap.ts export default new Map<number, SubCategory[]>([ [11, [100, 101]], [12, [102, 103]], ... ]) Is there a way to create a type guard for this Map? import categoryMap fro ...

Designing a custom HTML calendar

I am currently working on a school project where I am creating a calendar using HTML. So far, I have set up the basic structure of the page. What I want to achieve is a functional calendar where users can create appointments that will be displayed accordi ...

Is it possible to extend the Object class in order to automatically initialize a property when it is being modified?

My experience with various programming languages leads me to believe that the answer is likely a resounding no, except for PHP which had some peculiar cases like $someArray['nonexistentKey']++. I'm interested in creating a sparse object whe ...

Refreshing the page triggers the callback function that retrieves the checkboxes selected in a Kendo treeview component

How can I retain the selected checkboxes after refreshing the page? Is there a way to achieve this using AJAX when submitting data to a database and then reloading the page? AJAX //AJAX call for button $("#primaryTextButton").kendoButton(); va ...