JavaScript conversion of arrays to JSON data structures

Here is the code snippet along with the variable 'polygon':


var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
var bermudaTriangle;
var directionsPoints;
var example;
var rez;

function initialize() {
  directionsDisplay = new google.maps.DirectionsRenderer();
  var chicago = new google.maps.LatLng(41.850033, -87.6500523);
  var mapOptions = {
    zoom:7,
    mapTypeId: google.maps.MapTypeId.ROADMAP,
    center: chicago
  }
  map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
  directionsDisplay.setMap(map);
}

function calcRoute() {
  var start = document.getElementById('start').value;
  var end = document.getElementById('end').value;
  var request = {
      origin:start,
      destination:end,
      travelMode: google.maps.DirectionsTravelMode.DRIVING
  };
  directionsService.route(request, function(response, status) {
    if (status == google.maps.DirectionsStatus.OK) {
            directionsDisplay.setDirections(response);
      directionsPoints= response.routes[0].overview_path;

//To transform directionsPoints into the desired format
      example= [[{"X":72,"Y":59.45},{"X":136,"Y":66},{"X":170,"Y":99},{"X":171,"Y":114},{"X":183,"Y":125},{"X":218,"Y":144},{"X":218,"Y":165},{"X":226,"Y":193},{"X":254,"Y":195},{"X":283,"Y":195},{"X":292,"Y":202},{"X":325,"Y":213},{"X":341,"Y":234},{"X":397,"Y":245},{"X":417,"Y":248}]]; 
      function draw() {
        var polygons = response.routes[0].overview_path; 
        var scale = 100;
        reverse_copy(polygons);
        polygons = scaleup(polygons, scale);
        var cpr = new ClipperLib.Clipper();
        var delta = 25;
        var joinType = ClipperLib.JoinType.jtRound;
        var miterLimit = 2;
        var AutoFix = true;
        var svg, offsetted_polygon,
          cont = document.getElementById('map-canvas');
        offsetted_polygon = cpr.OffsetPolygons(polygons, delta * scale, joinType, miterLimit, AutoFix);
        console.log(JSON.stringify(offsetted_polygon));

        svg = polys2path(offsetted_polygon, scale);
        rez= polys2path(offsetted_polygon, scale);

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

        bermudaTriangle.setMap(map);

    }
// helper function to scale up polygon coordinates
function scaleup(poly, scale) {
  var i, j;
  if (!scale) scale = 1;
  for(i = 0; i < poly.length; i++) {
    for(j = 0; j < poly[i].length; j++) {
      poly[i][j].lb *= scale;
      poly[i][j].mb *= scale;
    }
  }
  return poly;
}

// converts polygons to SVG path string
function polys2path (poly, scale) {
  var path = "", i, j;
  if (!scale) scale = 1;
  for(i = 0; i < poly.length; i++) {
    for(j = 0; j < poly[i].length; j++){
      if (!j) path += "M";
      else path += "L";
      path += (poly[i][j].lb / scale) + ", " + (poly[i][j].mb / scale);
    }
    path += "Z";
  }
  return path;
}

function reverse_copy(poly) {
    // Make reverse copy of polygons = convert polyline to a 'flat' polygon ...
  var k, klen = poly.length, len, j; 
  for (k = 0; k < klen; k++) {
    len = poly[k].length;
    poly[k].length = len * 2 - 2;
    for (j = 1; j <= len - 2; j++) {
      poly[k][len - 1 + j] = {
        lb: poly[k][len - 1 - j].lb,
        mb: poly[k][len - 1 - j].mb
      }
    }
  }
}


    }
  });
}

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

The task at hand involves transforming the variable polygons, defined as response.routes[0].overview_path, into a format similar to the provided example:

  example= [[{"X":72,"Y":59.45},{"X":136,"Y":66},{"X":170,"Y":99},{"X":171,"Y":114},{"X":183,"Y":125},{"X":218,"Y":144},{"X":218,"Y":165},{"X":226,"Y":193},{"X":254,"Y":195},{"X":283,"Y":195},{"X":292,"Y":202},{"X":325,"Y":213},{"X":341,"Y":234},{"X":397,"Y":245},{"X":417,"Y":248}]]; 

You can explore the complete code with an interactive demo here.

Answer №1

Explore jQuery.each() resources and gain insights from this solution on how to add elements to the example array.

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

Encountered an issue while parsing JSON data in PHP with Ionic: Unexpected token '<' at position 0 in JSON.parse

Despite seeing numerous discussions on the same error, I am still unable to resolve my issue. The specifics are unclear to me, so perhaps you can provide some assistance. This is the structure of my php file: if(isset($_POST)){ $username = $_POST["u ...

What is the best way to execute a group by operation on a collection of JSON objects in Python?

Currently, I am tackling a Python script that involves grouping by a key within a list of JSON objects. In my Python code, I have access to an extensive array of JSON objects structured like this: [{'name': xyz, 'territory': abc, ...

What causes Vue to only update once when there are two closely timed mutations to reactive data?

Can you take a look at this simple example? export default { data() { return { name: "Amy", age: 18, }; }, computed: { combinedDataForWatching() { return { name: this.name, age: this.age, ...

Issue with Jquery's .html() function not functioning properly when trying to select HTML

I am currently working on a piece of code that looks like this: $price = $(element) > $('.main_paket_price').attr('name'); alert($price); Basically, I am trying to select an element inside element which has the class main_paket_pri ...

Issues arise when the Slick functionality fails to load following an ajax request

I've come across a situation similar to the one on this post. I'm having trouble getting my slick carousel to work after a successful ajax call. Despite trying all the solutions provided, it's still not functioning as expected. The code for ...

Tips for transferring v-model data between components

I am working with a parent form component and a child component, both located in separate files. I am using the Quasar Framework components. How can I pass data from the parent to the child component using v-model? Parent Component <template> < ...

tips for maximizing the safari browser window during automation testing

My current setup involves using Java and Selenium WebDriver for web automation. One issue I've encountered is that for Safari browser version 10.1, I need the browser to be in full screen mode before the test starts. driver.manage().window().maximize ...

Using Javascript or ES6, you can compare a nested array object with another array of elements and generate a new array based on

I am dealing with a complicated array structure as shown below sectionInfo = [{id: 1, name:'ma'}, {id: 2, name:'na'}, {id: 3, name:'ra'}, {id: 4, name:'ka'}, {id: 5, name:'pa'}]; abc = [{id:'1' ...

What is the process of incorporating a Higher-Order-Component in React?

I've been working on setting up a Higher Order Component (HOC) in React to enable text selection detection for any Input component. However, I seem to be missing a key piece of the puzzle in putting it all together. Initially, I followed an article t ...

What should be placed in the form action field if the router.post() method includes a parameter such as :id?

I'm struggling with how to properly submit data to my update form and what needs to be entered in the action field, especially considering the router.post includes an :id parameter. Below is the relevant code snippet: router.post('/gymupdate/:id& ...

Creating an array of objects by parsing JSON using the jQuery .each() method

I am attempting to generate an array of objects by parsing a JSON file. Here is the pertinent code: //president object constructor function president(a_presName, a_presDates, a_presNick, a_presImage) { this.presName=a_presName; this.presDates=a_pr ...

What is the most efficient way to prevent duplicate items from being added to an array in a Vue 3 shopping cart

I currently have a functional shopping cart system, but I am facing an issue where it creates duplicates in the cart instead of incrementing the quantity. How can I modify it to only increment the item if it already exists in the cart? Also, I would like t ...

What should be the output when ending the process using process.exit(1)?

I need to update my code by replacing throw new Error('Unknown command.') with a log statement and process.exit(1);. Here is the example code snippet: private getCommandByName = (name: string): ICommand => { try { // try to fetch ...

Angular JS Retrieving Data in the Background with the Assistance of $timeout or $interval Service

Looking to fetch data from a webapi in the background using either the $timeout or $interval service in Angular JS. I have some concerns about how the $timeout and $interval services work. I've run into issues when incorporating these services into m ...

To achieve proper display of multiple boxes, it is essential for each box to be

My current approach involves adding boxes to the scene based on specific dimensions for height, width, and depth, and it works perfectly when the boxes are all square. https://i.sstatic.net/HdDSX.png However, the issue arises when I try to use a rectangu ...

What is the best way to bring files into your project from a different directory?

Recently, I've been working on an app that consists of a backend repo and 2 frontend repos. Now, I'm facing the challenge of sharing code between these two frontend repos. app/ mySecondApp/ Despite my efforts, I'm unable to successfully imp ...

Guidelines for forming a JSON variable using a SOAP Response

Currently using ASP.NET 4.0, I am faced with the task of sending a SOAP (XML) Response to a JSON variable in javascript on the page. The aim is to access the variable and its properties just like any other JSON variable would be accessed. The challenge lie ...

Organize Javascript objects based on their dates - group them by day, month,

I've scoured the internet for examples but haven't found a suitable one that accomplishes the simple task I need. Maybe you can assist me with it. Here is an array of objects: [ { "date": "2015-01-01T12:00:00.000Z", "photoUrl": "", ...

What are some effective methods for testing internet connectivity?

My CMS operates by pulling large amounts of data using PHP, MySQL, jQuery, Bootstrap, and AJAX. An issue arises when the internet connection is lost, causing problems with displaying and scrolling on the site. I am interested in finding a solution that c ...

"Exploring the Intersection of Meteor, NPM Packages, and Fiber Callbacks

I am currently utilizing request and cheerio to extract specific content, particularly a quote, from a website. Here is the code snippet ( server.js ) : q = new Mongo.Collection('quotelist'); postList = new Mongo.Collection('quotes&apos ...