Traverse the JavaScript object and generate polylines on Google Maps

After reading some articles on JavaScript objects, I still can't seem to grasp it completely. I managed to convert a JSON string into a JavaScript object following the structure below.


public class LinePoint {
    public string Latitude { get; set; }
    public string Longitude { get; set; }
    public int Pointnumber { get; set; }
}

public class PolyLine {
    public List<LinePoint> LinePoints { get; set; }
    public int PolyLineNumBer { get; set; }
}

public class RootObject {
    public List<PolyLine> PolyLines { get; set; }
}

To plot the Latitude and Longitude properties as polylines on a Google map control, I added the code snippet below to initialize the map. However, I am struggling with looping through the object.

Here is my current code:


var line = JSON.parse(document.getElementById('hdfPolyLines').value);
var path = [];

$.each( /* Looping through list items in RootObject */ ) {
    // Parsing the array of LatLngs into Gmap points
    for(/* Looping through each latlong in the list of list items */) {
        path.push(new google.maps.LatLng( /* Accessing Latitude and Longitude properties from list item */ ));
    }
    
    var polyline = new google.maps.Polyline({
        path: path,
        strokeColor: '#ff0000',
        strokeOpacity: 1.0,
        strokeWeight: 3
    });
    
    polyline.setMap(map);
});

I'm looking for assistance on how to properly loop through the JavaScript object and extract property values. Can someone provide guidance on this?

Answer №1

If you're working with jQuery, you can utilize the $.each function for loops. Here's an example of how you can implement it:

var data = JSON.parse(document.getElementById('jsonData').value);

$.each(data.items, function(index, value) {

    var array = Array();

    $.each(value.subItems, function (subIndex, subValue) {

        array.push(new CustomObject(subValue.property1, subValue.property2));
    });

    var customArray = new CustomArray({
        items: array,
        color: 'blue',
        opacity: 0.8,
        thickness: 4
    });

    customArray.render();
});

Answer №2

I'm longing for details on the structure of the html document.

Nevertheless, I will make an attempt to assist:

$("#rootitemid").children().each(function(){
    var value= $(this).html(); 
    //..
});

The above code iterates over elements within the html document.

for(key in objs){
    var value= objs[key];
    //..
}

The above snippet loops through a javascript object.

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

The C# Access Modifier is designated as public, yet remains unattainable

Currently, I am working on a C# project that references another project with property settings. In this referenced project, the property settings have been set to public using the drop-down menu in Visual Studio. While I am able to access the properties ...

Are there any event triggers for History.pushstate?

My Google-fu is failing me. Consider the following code snippet: var stateObj = { state: "some state" }; history.pushState(stateObj, "page 2", "other.htm"); Does this trigger a window callback? I am aware of the following code: window.onpopstate = fun ...

The Allman style is not applied by ESLint in VSCode to all languages, such as JSON

My disdain for Prettier stems from the fact that it restricts my freedom to utilize my preferred brace style. In my workflow, I rely on tools like CSSComb, PHP CS Fixer, and SCSS Allman Formatter as they support Allman style. While VSCode offers native Ja ...

Submitting JSON data using JavaScript

My goal is to send a username and password to my backend server. However, I am encountering an issue where the data does not successfully reach the backend when using the following code: function register() { var text = '{"username":"admin1","pass ...

React with Redux throws an Invariant Violation error stating that it could not locate the "store" in either the context or props of the component "Connect(Body)"

I am attempting to link my component to a store utilizing the react + redux + react-redux + react-router approach. Despite encapsulating the parent with a store, I am encountering this error: [Invariant Violation: Could not find "store" in either the c ...

Query to retrieve rows from MySql where a column storing JSON information is below a certain threshold

I have a table with JSON key-value pair data stored in a column called 'charges', such as {"1":"200","2":"100","3":"600","4":"400"}. I need to retrieve rows where the ...

How can I incorporate a custom color into a preset navbar on an HTML webpage?

<div class="navbar-header"> <button aria-controls="navbar" aria-expanded="false" data-target="#navbar" data-toggle="collapse" style="color: blue;" class="navbar-toggle collapsed" type="button"> <i class="fa fa-reo ...

Trouble saving an Array with AFNetworking and AFHTTPRequestOperation

Trying to access a JSON file online, I found that the contents of the file can be retrieved in the completion block using AFHTTPRequestOperation method. However, outside the block, when trying to NSLog the data, it appears as null. I am puzzled by this beh ...

Is it possible to use the Husky "commit-msg" hook to git add new files?

I am currently setting up an automatic versioning system where if I use git commit with the message format PATCH: {message}, the app's patch version will automatically be updated (and the same for the prefixes MINOR and MAJOR as well). My approach inv ...

Ways to set a default image for an <img> tag

I am looking to set a default image to the img tag in case the user has not selected a profile picture for their account. Here is the current output: http://jsfiddle.net/LvsYc/2973/ Check out the default image here: This is the script being used: funct ...

The navigation bar is positioned with white space above it

Currently working on a website design and facing an issue with adding a clickable button to the Nav-bar. Noticed some white-space above the Nav-bar which is not desired. I had previously posted a similar question but unable to identify the CSS error causi ...

What could be causing the submit button to reactivate before all form fields have been completed?

I have implemented the code snippet below to validate each field in my contact form using bootstrap-validator and an additional check through Google reCAPTCHA. You can view and test the form here. The submit button is initially disabled with the following ...

Instructions for programmatically deleting a file from an SFTP server using SharpSSH

Looking for guidance on using Tamir Gal's SharpSSH to delete a file from a SFTP server. I have successfully implemented other features, but struggling with deletion. Any advice would be greatly appreciated. ...

Tips for solving the problem of page navigation using jquery-mobile

I have a jquery-mobile application with two actual HTML pages, but many more data-role="page" divs. The issue arises when transitioning from the first actual HTML page to the next one as the navigation stops working. I am not using any custom JavaScript, j ...

reqParam = $.getQueryParameters(); How does this request work within an ajax form

I've spent a lot of time searching, but I can't figure out what the code reqParam = $.getQueryParameters(); means and how it is used in Ajax JavaScript. I copied this Java script from a website as an example. If anyone has any insights, please he ...

When executing code in React JS, I encountered no errors, but the output did not match my expectations

I am facing a challenge with running the Hello World program in React JS using webpack. Attached below is the project structure for reference: https://i.stack.imgur.com/tQXeK.png Upon executing the npm run dev command in the CLI, the browser launches bu ...

What steps can be taken to enable users to send and receive messages on my chat website?

I just completed creating a chat website using HTML, CSS, JavaScript, and jQuery and have now published it. You can view it at However, the site still lacks the functionality that would allow users to send and receive messages through it. Can anyone prov ...

React - navigating with hash in routing parameter

I am facing an issue with my application, where I have implemented navigation between different cars. Each car has a unique ID, but some IDs contain a hash symbol, like 'test#car#1'. This hash symbol in the ID is causing problems with the navigat ...

Ways to expand CRA ESLint guidelines using the EXTEND_ESLINT environmental variable

Facebook's Create React App (CRA) recently introduced a new feature allowing users to customize the base ESLint rules. Recognizing that some cases may require further customization, it is now possible to extend the base ESLint config by setting the ...

Failure to attach entity 'XXX' due to a duplicate primary key value already existing for another entity of the same type

I've hit a roadblock with my code throwing an exception at this line: dbContext.Entry(entity).State = EntityState.Modified; This issue only started happening two days ago, even though I've been using this code for the past month. Despite readin ...