Using gmaps4rails: A guide on extracting JSON data from the controller

I have a model named shop and I want to create a simple alert box using JavaScript that shows the name of the shop when a marker on the map is clicked.

Here's my code:

# controller
@json = Shop.all.to_gmaps4rails do |shop, marker|
  marker.json({ id: shop.id, name: shop.name })
end

# view
<%= gmaps("map_options" => { auto_zoom: false, zoom: 2, class: "homepage-map" },
      "markers" => { data: @json,
                     options: { do_clustering: true,
                                clusterer_maxZoom: 11,
                                raw: "{ animation: google.maps.Animation.DROP }" }
                    })
%>

<% content_for :scripts do %>
<script type="text/javascript" charset="utf-8">
Gmaps.map.callback = function() {
  for (var i = 0; i <  this.markers.length; ++i) {
    google.maps.event.addListener(Gmaps.map.markers[i].serviceObject, 'click', function() {
      alert(put something here);
    });
  }
};
</script>
<% end %>

This is my first experience working with JSON, so I've researched some introductory articles about it and also looked into JSON in JavaScript. I'm curious about how to achieve this with gmaps4rails.

Answer №1

You can use this code snippet to achieve the desired functionality:

<script type="text/javascript" charset="utf-8>
function handleMarkerClickClosure(marker) {
  return function() {
    alert(marker.name);
  }
}

Gmaps.map.callback = function() {
  for (var i = 0; i <  this.markers.length; ++i) {
    google.maps.event.addListener(Gmaps.map.markers[i].serviceObject, 'click', handleMarkerClickClosure(Gmaps.map.markers[i]) );
  }
};
</script>

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

Initiate activity when link is clicked

I am currently in the process of developing a website that includes 5 divs. <div class="one"></div> <div class="two"></div> <div class="three"></div> <div class="four"></div> <div class="five"></div ...

Switch the following line utilizing a regular expression

Currently, I am facing a challenge with a large file that needs translation for the WordPress LocoTranslate plugin. Specifically, I need to translate the content within the msgstr quotes based on the content in the msgid quotes. An example of this is: #: . ...

Transform this color matching game into an image matching game using JavaScript and jQuery

I have a color matching game that I would like to enhance by matching background-images instead of just background-colors. However, I am facing difficulties in making this change. For instance, instead of matching the color red with the text "red," I wan ...

Is there a way in Angular Material to consistently display both the step values and a personalized description for each step?

Is there a way to display both numerical step values and corresponding custom text in Angular Material? I prefer having the number at the top and the descriptive text at the bottom. Check out this image for reference: https://i.stack.imgur.com/LGMIO.png ...

Error in sending data to the server via the specified URL: "Http failure response for http://localhost/post.php: 0 Unknown Error" and POST request to http://localhost/post.php failed with error code

Feeling a bit stuck trying to add data to my database. As a junior with PHP and Angular, I am using PHP via XAMPP and Angular 8. Is it possible to create separate files for the post and get methods in the PHP file? app.component.ts import { Component, O ...

Angular 2: Enhancing User Experience with Pop-up Dialogs

Looking to implement a popup dialog that requests user input and returns the value. The popup component is included in the root component, positioned above the app's router outlet. Within the popup component, there is an open() method that toggles a ...

Passing variables from ExpressJS to JavaScript can be a seamless process

I am struggling with this issue; I am utilizing NodeJS to retrieve a JSON and I must transfer the variable to my page for use by JavaScript. app.get('/test', function(req, res) { res.render('testPage', { myVar: 'My Dat ...

PHP problem with encoding JSON using foreach loop

Struggling with my PHP code here! I have managed to pull database entries and store them in a multi-dimensional array just the way I need. However, when it comes to looping through this array using foreach, I am at a loss. $res = $GLOBALS["Data ...

Is it feasible to place an ordered list within a table row <tr>?

Below is a code snippet demonstrating how to create an ordered list using JavaScript: Here is the JavaScript code: <script type="text/javascript"> $(document).ready(function() { $("ul").each(function() { $(this).find("li").each(functio ...

Converting Enums to integers and back with Gson's versatile code

Currently, I am working on a unique JsonSerializer and JsonDeserializer task. The goal is to serialize JSON integers to enums and deserialize enums back to integers. To achieve this purpose, I have designed an interface with a function named fromValue tha ...

Inspection Techniques for Javascript Objects

Is there a way to display an object's properties and methods in an alert box? When I try alerting an object, it only shows the nodename: alert(document); I'm looking for a way to see all the details of the object in the alert message. Is there ...

I have been working on incorporating a menu item in React, but I keep encountering an error

I am using the MenuItem component to create a dropdown menu in my React project. Despite importing the necessary package, I am encountering an error when running the server. I have searched for solutions but haven't found a definitive me ...

Is it possible to use jQuery to refresh only a section of the page and modify the URL at the same time?

There is a page (http://myflashpics.com/picture/p9e0) that displays user information along with a small thumbnail on the side. Currently, when clicking on the image, it redirects to a different page and the sidebar reloads as well. I am curious if it' ...

What type of technology is typically utilized in creating functional platforms such as goDaddy, wix, and other web design websites?

I am currently working on a web development project that aims to allow users to edit webpages without needing any coding knowledge. Users with authorization will be able to modify not only the text but also various HTML tags on the page, similar to platfor ...

The component next/image is experiencing issues when used in conjunction with CSS

I struggled to create a border around an image because the custom CSS I wrote was being overridden by the Image component's CSS. Despite trying to leverage Tailwind and Bootstrap to solve the problem, my efforts were unsuccessful. Now, I am at a loss ...

Using Lua to access indices from a table that was generated from JSON data

Currently, I find myself in a situation where I have to use Lua to fetch weather data from the Openweathermap API. I've successfully sent an HTTP request to retrieve and save all the data, but now I'm facing a challenge with manipulating a deeply ...

The Backbone Model is producing unspecified data

Having crafted a backbone model, it looks like this: var note_model = Backbone.Model.extend({ default : { HistoryKey : "", InsertDate : "", MemberKey : "", NoteDate : "", ContactNote : "", User ...

What is the best method to calculate the total of multiple input values from various cells and display it in the final cell of an Angular table?

Hey there! I have a challenge where I need to calculate the sum of input values for each cell and display it dynamically in the last cell of the row. Take a look at the image below: https://i.stack.imgur.com/0iKEE.png In the image, you can see that the nu ...

Output a variable that is generated from invoking an asynchronous function

I'm currently in the process of developing an application that is going to leverage the capabilities of a SOAP server through the use of the https://github.com/vpulim/node-soap module. One of the main challenges I am facing is how to efficiently crea ...

The link function fails to execute

I have created a custom Directive. The issue I am facing is that the html template is not being rendered. Upon debugging, I noticed that the link function is never called because the instance function is also never called. To troubleshoot, I added "debu ...