Steps for transferring JSON data from the controller to JavaScript

Within my cluster Table, there is a column called description which stores cluster coordinates in JSON format. I want to draw multiple cluster polygons on Google Maps using these coordinates.

    id |       description                                                                                                                                                                                                
----+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
  1 | {"points":[{"lat":14.232437996569354,"lng":76.409912109375},{"lat":13.336175186494927,"lng":77.1185302734375},{"lat":12.961735843534294,"lng":77.596435546875},{"lat":12.511665400971031,"lng":76.904296875}]}


 2   |    {"points":[{"lat":14.232437996569354,"lng":76.409912109375},  {"lat":13.336175186494927,"lng":77.1185302734375},{"lat":12.961735843534294,"lng":77.596435546875},{"lat":12.511665400971031,"lng":76.904296875}]}

I need to draw multiple polygons but I am having trouble getting the JSON data into my Rails controller.

Controller Code:

query="select id,description from clusters";
@result=ActiveRecord::Base.connection.execute(query);

The issue is how to pass this @result to JavaScript in order to draw multiple polygons on Google Maps. If I copy the JSON data into a variable in JS, I can draw the clusters, but I'm struggling with passing this JSON data from the database in the controller to JavaScript in Rails.

My Google Maps JavaScript code works if I hard code the JSON into a variable, but I need to retrieve this JSON data from the database. How can I pass the JSON with ID from the controller to JavaScript?

var obj=i need json to store here //this how to fetch json from controller to js  
polygons = [];
for(var i = 0; i < obj.length; ++i){
   //do something with obj[i]
   for(var ind in obj[i]) {
        console.log(ind);
          var arr = new google.maps.MVCArray();
        for(var vals in obj[i][ind]){
            console.log(vals, obj[i][ind][vals].lat );
                 arr.push( new google.maps.LatLng( obj[i][ind][vals].lat, obj[i][ind][vals].lng ) );
        }
   }

polygons.push(arr);
}       

    polygons.forEach( function(polyPath) {

        var polygon = new google.maps.Polygon({
            paths: polyPath,
            strokeColor: '#FF0000',
            strokeOpacity: 0.8,
            strokeWeight: 2,
            fillColor: '#FF0000',
            fillOpacity: 0.35,
            map: map
        });
    });
}

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

Answer №1

One possible approach is to implement an ajax-load function to fetch points dynamically. The retrieved JSON data can then be used to render the desired action, like so:

render json: @result

Alternatively, if you already have the Google Maps code in your view, you can store a JSON string from the database in a JavaScript variable as follows:

var json_string = '<%= @results.raw %>';

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

Tips on interpreting JSON objects and cross-referencing them with user input

I am currently developing an application where specific values are stored in JSON format and I aim to access these values through indexes rather than hard coding them. Below is a snippet of my HTML file combined with JavaScript: <html> <head> ...

Pass a URL string to a different script using Node.js

Currently, I am delving into the world of Node.js, utilizing Express with Jade and Mongoose as my primary tools. Originating from a background in PHP, transitioning to Python, and embracing MVC principles through Django, my aspiration is to create a multip ...

Identifying memory leaks caused by rxjs in Angular applications

Is there a specific tool or technique available to identify observables and subscriptions that have been left behind or are still active? I recently encountered a significant memory leak caused by components not being unsubscribed properly. I came across ...

Failure to retrieve JSON using $.ajax in JSP

I am attempting to retrieve a JSON Array from a Servlet and populate data into a table. However, the JSON or text is not being received in the JSP despite trying various methods. Below is my JSP code: <%@ page contentType="text/html;charset=UTF-8" lan ...

Unable to access object key data from JSON-SERVER

I am currently attempting to send a GET request to json-server in order to retrieve data from a nested object. However, the response I am receiving is empty instead of containing the desired data key. After thoroughly reviewing the documentation, I could ...

There seems to be an issue with byRole as it is failing to return

Currently in the process of migrating my unit test cases from Jest and Enzyme to React Testing Library. I am working with Material UI's Select component and need to trigger the mouseDown event on the corresponding div to open the dropdown. In my previ ...

Discover the most affordable price from an array in Vue Js

One of the challenges I'm facing involves working with an array that loops through all the trips for a listing. <span v-for="price in listing.trips"> <div class="price">{{ price.cost }} </div> </span> I'm wonderin ...

How to obtain a JSON token using Newtonsoft that has a name containing a special character

I am encountering some Json files with special characters as shown below: { "someProperties" : "someValues", "$ROOT_QUERY.searchResults({\"path\":\"/some/url\"}).features": { ...

What is the optimal method for storing extracted JSON data?

One question on my mind is how to effectively store JSON data. I have a JSON file that I parse using JSON Library and now I have the data from the file. However, I want to be able to store this data for future use. I'm seeking advice on the best way ...

Text centered vertically with jQuery is only loaded after the page is resized

My jQuery script is designed to vertically center text next to an image, but it seems to only work properly after resizing the page. $(window).load(function () { $(function () { var adjustHeight = function () { $('.vertical-al ...

Trim the final digits from the arrays

I have an array that contains various strings: var arr = ['1234','23C','456','356778', '56'] My goal is to filter out array elements that are less than 3 characters or more than 4 characters. The resultin ...

Receiving data from multiple sockets in Node.js with Socket.io

I recently started working with Node.js to develop an online game that acts as a server-side application. This application serves the .html and .js files to the client while managing the game's logic. I'm utilizing Socket.io for communication bet ...

Looping through items using v-model value in v-for

My website features a small form that allows users to submit new photos and view previously submitted photos. Users begin by selecting an album for the photo and then uploading it. Currently, I am encountering an issue in retrieving photos based on the sel ...

Tips for delivering a heartfelt message when a user adds an item

import React from 'react'; import { useForm } from "react-hook-form"; import { toast } from 'react-toastify'; const AddStorage = () => { const { register, handleSubmit } = useForm(); const submitData = data => ...

Discover the specific item within an array of objects

Anyone have information like this: const info = { Title : "Banana", Quantity : 10, Location : "Everywhere", Phone : 123456, A : 987, B : 654, } and there is another array of details as: const dataArr = ["Title",&q ...

Why does the styling of the inner Span adhere to the style of the outer Span?

How can I adjust the opacity of the color "blue" to 1 in the code snippet below? <!DOCTYPE html> <html> <body> <p>My mom's eyes are <span style="color:blue;font-weight:bold;opacity:0"> <span style="color:blue;fo ...

Replacing jQuery.ajax from a different directory/domain - problem with using relative URLs

We are incorporating scripts from various sources and domains, including one that contains the definition for jQuery.ajax function. Calls to jQuery.ajax are being made from different places and domains using relative URLs, such as jQuery.ajax("my/relativ ...

Setting up AngularJS can be a pain

Greetings, my name is Rahim. While setting up AngularCLI, I ran into the following issue: 'ng' is not recognized as an internal or external command, operable program or batch file. C:\Users\ASUS ROG>ng --version 'ng' is ...

What is the best way to store a range object obtained from getSelection in order to recreate it on a separate page load?

My goal is to develop a web application that enables users to highlight selected text on a webpage with the click of a button. I want these highlights to persist even when the user returns to the page. So far, I have achieved: var selectedRange = documen ...

Ensuring Data Completeness: Mandatory Fields based on Boolean Status in JSON Schema Validation

I have searched through numerous resources, but I can't seem to find a solution to my issue. My goal is to validate the specific scenario using a json schema: If 'isRetired' equals false, then additional requirements are retirement age, sa ...