简体   繁体   中英

Extracting array values from JSON in Jquery

I'm currently building a little mobile web app for a university project. The application I'm trying to build takes values from a JSON file for various species of trees and then lists these through use of Jquery on a HTML page - when one of these list items is clicked it brings the user to a google map page where the idea is to draw a polygon from the coordinate information within the JSON file.

My JSON file looks like this:

    [{ 
"forestnumber":"1",
"name":"Cork Oak" ,
"imagelocation":"img/corkoak.png" ,
"scientificname":"Cork Oak" ,
"type":"Evergreen" , 
"shortdesc":"Quercus suber, commonly called the cork oak, is a medium-sized, evergreen oak tree in the section Quercus sect. Cerris. It is the primary source of cork for wine bottle stoppers and other uses, such as cork flooring. It is native to southwest Europe and northwest Africa." ,
"coordinates": [[-35.279033, 149.079420], [-35.279240, 149.081258], [-35.283641, 149.081343], [-35.283405, 149.079024]]
},{ 
"forestnumber":"2",
"name":"Local Eucalypts And Grasses" ,
"imagelocation":"img/localeucalypts.png" ,
"scientificname":"Various" ,
"type":"Evergreen" , 
"shortdesc":"There are more than 700 species of eucalyptus and are mostly native of Australia, and a very small number are found in adjacent areas of New Guinea and Indonesia. One species, Eucalyptus deglupta, ranges as far north as the Philippines." ,
"coordinates": [[-35.279136, 149.081158], [-35.279305, 149.081193], [-35.283613, 149.081276], [-35.283405, 149.07902], [-35.284155, 149.080923], [-35.284425, 149.081320], [-35.286067, 149.081197], [-35.286094, 149.080900], [-35.286328, 149.081362], [-35.285604, 149.082060], [-35.284642, 149.082469], [-35.283257, 149.082599], [-35.281447, 149.082384], [-35.280926, 149.082163], [-35.280354, 149.081800], [-35.279764, 149.081678]]
},{ 
"forestnumber":"3",
"name":"Common Fig" ,
"imagelocation":"img/figs.png" ,
"scientificname":"Ficus Carica" ,
"type":"Deciduous" , 
"shortdesc":" Although commonly referred to as a fruit, the fig is actually the infructescence or scion of the tree, known as a false fruit or multiple fruit, in which the flowers and seeds are borne." ,
"coordinates": [[-35.285872, 149.079429], [-35.285624, 149.077371], [-35.286509, 149.078898]]
}]

Each forest is numbered and each coordinate value is another array.

My jQuery code looks like this:

    $.getJSON( "js/forests.json", function( data ) {
    for (var i = 0; i <= data.length; i++) { //loop through JSON file
      var value = data[i];//set value to represent data
      var _html; // set _html as a variable
      _html = "<li class='forestlistitem' data-val='"+value.forestnumber+"'><span class='name'>"+value.name+"</span><img src='"+value.imagelocation+"' alt='"+value.name+"' class='listimage' /></li>" ;
$('#forestlistbody ul').append(_html); //append _html to the HTML of the page
$('.forestlistitem').click(function(){ //sort of a no-no but the only way i can get it to work?
    $("#forests").hide();//hides forests div in HTML
    $("homeselect").hide();//hides homeselect div in HTML
    $("trails").hide();//hides trails div in HTML
    $("#map").show();//shows map div in HTML
    initMap();//initializes map function 
    numb = $(this).data('val'); // sets global variable numb to the forest number associated with which option was clicked
    console.log(numb); // output numb variable to console in order to test that it is sending the correct number
});

THE PROBLEM: So Basically what I want to be able to do from herein is output the coordinates array that was associated with the clicked list item into an MVCArray by pushing each coordinate value into it. The code for that looks something like this at the moment(currently not a loop for each because I don't know how to output it from JSON).

    var forest = new google.maps.MVCArray();
    forest.push ( new google.maps.LatLng(-35.285872, 149.079429) );
    forest.push ( new google.maps.LatLng(-35.285624, 149.077371) );
    forest.push ( new google.maps.LatLng(-35.286509, 149.078898) );

    var polygonOptions = {path: forest};
    var polygon = new google.maps.Polygon(polygonOptions);

    polygon.setMap(map);

If anyone could help me I'd highly appreciate it, ive been wracking my brains on this looking at various resources but I can't quite figure out how to get the array values out of the JSON and into a loop for each push item. This is only the second time ever working with code so im still a bit of a newbie =p

To parse your JSON into google.maps.Polygon objects, translate the array of arrays that currently holds the coordinates into an array of google.maps.LatLng objects (or google.maps.LatLngLiteral objects)

  for (var i = 0; i < jsonData.length; i++) {
    var coordinates = [];
    for (var j = 0; j < jsonData[i].coordinates.length; j++) {
      var pt = new google.maps.LatLng(jsonData[i].coordinates[j][0], jsonData[i].coordinates[j][1]);
      coordinates.push(pt);
    }
    var polygon = new google.maps.Polygon({
      map: map,
      paths: [coordinates]
    })
  }

fiddle

code snippet:

 function initialize() { var map = new google.maps.Map( document.getElementById("map_canvas"), { center: new google.maps.LatLng(37.4419, -122.1419), zoom: 13, mapTypeId: google.maps.MapTypeId.ROADMAP }); var bounds = new google.maps.LatLngBounds(); for (var i = 0; i < jsonData.length; i++) { var coordinates = []; for (var j = 0; j < jsonData[i].coordinates.length; j++) { var pt = new google.maps.LatLng(jsonData[i].coordinates[j][0], jsonData[i].coordinates[j][1]); coordinates.push(pt); bounds.extend(pt); } var polygon = new google.maps.Polygon({ map: map, paths: [coordinates] }) } map.fitBounds(bounds); } google.maps.event.addDomListener(window, "load", initialize); var jsonData = [{ "forestnumber": "1", "name": "Cork Oak", "imagelocation": "img/corkoak.png", "scientificname": "Cork Oak", "type": "Evergreen", "shortdesc": "Quercus suber, commonly called the cork oak, is a medium-sized, evergreen oak tree in the section Quercus sect. Cerris. It is the primary source of cork for wine bottle stoppers and other uses, such as cork flooring. It is native to southwest Europe and northwest Africa.", "coordinates": [ [-35.279033, 149.079420], [-35.279240, 149.081258], [-35.283641, 149.081343], [-35.283405, 149.079024] ] }, { "forestnumber": "2", "name": "Local Eucalypts And Grasses", "imagelocation": "img/localeucalypts.png", "scientificname": "Various", "type": "Evergreen", "shortdesc": "There are more than 700 species of eucalyptus and are mostly native of Australia, and a very small number are found in adjacent areas of New Guinea and Indonesia. One species, Eucalyptus deglupta, ranges as far north as the Philippines.", "coordinates": [ [-35.279136, 149.081158], [-35.279305, 149.081193], [-35.283613, 149.081276], [-35.283405, 149.07902], [-35.284155, 149.080923], [-35.284425, 149.081320], [-35.286067, 149.081197], [-35.286094, 149.080900], [-35.286328, 149.081362], [-35.285604, 149.082060], [-35.284642, 149.082469], [-35.283257, 149.082599], [-35.281447, 149.082384], [-35.280926, 149.082163], [-35.280354, 149.081800], [-35.279764, 149.081678] ] }, { "forestnumber": "3", "name": "Common Fig", "imagelocation": "img/figs.png", "scientificname": "Ficus Carica", "type": "Deciduous", "shortdesc": " Although commonly referred to as a fruit, the fig is actually the infructescence or scion of the tree, known as a false fruit or multiple fruit, in which the flowers and seeds are borne.", "coordinates": [ [-35.285872, 149.079429], [-35.285624, 149.077371], [-35.286509, 149.078898] ] }]; 
 html, body, #map_canvas { height: 100%; width: 100%; margin: 0px; padding: 0px } 
 <script src="https://maps.googleapis.com/maps/api/js"></script> <div id="map_canvas"></div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM