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

Sending an image file using AJAX and jQuery

I am currently using Mustache JS to generate a template called 'addUser1' for display purposes. However, when I execute this code, only the image location is being sent to the server, not the actual image itself. What could be causing this issue? ...

What is the best way to showcase an item from an array using a timer?

I'm currently working on a music app and I have a specific requirement to showcase content from an array object based on a start and duration time. Here's a sample of the data structure: [ { id: 1, content: 'hello how are you', start: 0 ...

Experiencing a 404 error after attempting to access an endpoint following a successful MSAL Azure AD

Incorporating the UserAgentApplication.loginPopup function to authenticate users on our Azure AD has been a challenge as we transition from an ASP.NET MVC application to a Vue.js front end and ASP.NET 'API' backend. The goal is to pass the access ...

Troubleshooting issue: Click function not responding inside Bootstrap modal

Below is the JavaScript code for my click function $(".addPizza").on("click", function(event) { event.preventDefault(); console.log("hello") let userId = $("#userId").attr("data-id"); let pizzaRecipe = $('#pizza-recipe').val().trim(); ...

Customize the appearance of a shadow-root element

Is there a way to modify the styles of a shadow element? Specifically, is it possible to extend or overwrite certain properties within a CSS class? I am currently using a Chrome extension called Beanote, which has not been updated since April 2017. There i ...

Saving functions in the localStorage API of HTML5: A step-by-step guide

I have encountered an issue while trying to store an array in local storage using JSON.stringify. The array contains functions (referred to as promises) within an object, but it seems that when I convert the array to a string, the functions are removed. Su ...

Launch the Image-Infused Modal

I am completely new to the world of Ionic development. Currently, I am working on a simple Ionic application that comprises a list of users with their respective usernames and images stored in an array. Typescript: users = [ { "name": "First ...

"Although both jQuery and PHP are capable of setting the element attribute, it is only PHP that functions successfully

I have been trying to set an element attribute to adjust the range of a slider. Initially, I used ajax to fetch data from a php file and assign it to the attribute. The slider looked good with the value but unfortunately, it wasn't functioning as expe ...

The issue with AngularJS Routing is that it fails to refresh the menu items when the URL and views are being

My current project involves implementing token-based authentication using the MEAN stack. The goal of my application is to display different menu items based on whether a user is logged in or not. When there is no token present, the menu should show option ...

There was a JSON Parsing error because the JSON array had no value assigned to it

Need help with a code that requires passing a static user ID for authentication, fetching JSON response from a URL, and displaying it in a listview. However, encountering an error "JSON Parsing error: No value in (JSON array)". Any assistance would be ap ...

Q: How can I retrieve an array of arrays containing JSON object values from an array of objects?

When given a JSON input structured like this: [ { "k1": "o1k1", "k2": "o1k2", "k_opt1": "o1k_xxx" }, { "k1": "o2k1", "k2": "o2k2", ...

Is it possible for you to generate an array containing only one element?

I've encountered an issue with my code. It functions correctly when the JSON data for "Customers" is in array form. However, if there is only one customer present, the code erroneously creates 11 table columns (corresponding to the number of keys in t ...

Can someone assist me with navigating through my SQL database?

Struggling with a script that searches multiple fields in the same table, I need it to return results even if one or three parameters are left blank. My attempts using PHP and MySql have been fruitless so far, which is why I am reaching out to the experts ...

Create dynamic and interactive content by embedding text within SVG shapes using the powerful D

How can I write text into an SVG shape created with d3.js and limit it to stay inside the shape similar to this example http://bl.ocks.org/mbostock/4063582? I attempted to use a clipPath following the example provided. However, when inspecting with firebu ...

How can React Native efficiently retrieve data from multiple APIs simultaneously?

In my current project, I am incorporating multiple APIs that are interlinked with each other by sharing the same data structure... Below is the code snippet: export default class App extends React.Component { constructor(props) { super(props); } ...

Issue with Angular controller not refreshingalternatively:Angular

I just started reading an AngularJS book by O'Reilly and I encountered a problem with the first example. Instead of seeing "hello" as expected in place of "{{greeting.text}}", it displays exactly that. I have double-checked my angular linking and even ...

Issue with symbol not functioning on different device

There seems to be a display issue with the ...

Is there a restriction on the number of strings allowed in minimist?

Here is the output received from the code provided below. Question input and i are both true as intended, but why aren't project and p? They are defined in exactly the same way as input and i. $ bin/test --input -p { _: [], update: fa ...

Tips for incorporating a spinner during content loading within AngularJS

When the user clicks on the "Search" button, content will load and the button label will change to "Searching" with a spinner shown while the content is loading. Once the content has loaded (Promise resolved), the button label will revert back to "Search" ...

Singleton pattern for iFrames sharing the same origin

I have developed a web application that runs on multiple iframes within a parent window, similar to a modified version of GWT. Rather than each individual iframe accessing our backend service separately, I am attempting to have them share the data service ...