简体   繁体   中英

How to: Array of objects from XML file

I am trying to create a heatmap using google heatmap layer. My input data is in a XML file.

I need to create an array containing entrances like this:

var heatmapData = [
{location: new google.maps.LatLng(37.782, -122.447), weight: 0.5},
{location: new google.maps.LatLng(37.782, -122.447), weight: 0.5},
{location: new google.maps.LatLng(37.782, -122.447), weight: 0.5}
]

( https://developers.google.com/maps/documentation/javascript/heatmaplayer )

I have a function which reads longitude and latitude data from my XML file and pushes it to an array, which is then used by google heatmap layer function.

This gives me an array like this:

var heatmapData = [
new google.maps.LatLng(37.782, -122.447),
new google.maps.LatLng(37.782, -123.447),
new google.maps.LatLng(37.782, -122.447)
]

However i dont know how to append my weight data (weed_index in my XML file) to the array and my hours of searching have left me stuck at this point.

How can i do this?

My project is here

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Heatmaps</title>
    <style>
      /* Always set the map height explicitly to define the size of the div
       * element that contains the map. */
      #map {
        height: 100%;
      }
      /* Optional: Makes the sample page fill the window. */
      html, body {
        height: 100%;
        margin: 0;
        padding: 0;
      }
      #floating-panel {
        position: absolute;
        top: 10px;
        left: 25%;
        z-index: 5;
        background-color: #fff;
        padding: 5px;
        border: 1px solid #999;
        text-align: center;
        font-family: 'Roboto','sans-serif';
        line-height: 30px;
        padding-left: 10px;
      }
      #floating-panel {
        background-color: #fff;
        border: 1px solid #999;
        left: 25%;
        padding: 5px;
        position: absolute;
        top: 10px;
        z-index: 5;
      }
    </style>
  </head>

  <body>
    <div id="floating-panel">
      <button onclick="toggleHeatmap()">Toggle Heatmap</button>
      <button onclick="changeGradient()">Change gradient</button>
      <button onclick="changeRadius()">Change radius</button>
      <button onclick="changeOpacity()">Change opacity</button>
    </div>
    <div id="map"></div>

    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script>

      // This example requires the Visualization library. Include the libraries=visualization
      // parameter when you first load the API. For example:
      // <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=visualization">

      var map, heatmap;

      function initMap() {
        map = new google.maps.Map(document.getElementById('map'), {
          zoom: 30,
          center: {lat: 5622.5693*0.01, lng: 934.2757*0.01},
          mapTypeId: 'satellite'
        });



var heatmapData = []; //array to hold objects parsed form XML file
var markerCoords;

loadXMLFile();            
            function loadXMLFile(){
            //var filename = 'data.xml';
            var filename = 'markers.xml';
            $.ajax({
                type: "GET",
                url: filename ,
                dataType: "xml",
                success: parseXML,
                error : onXMLLoadFailed
            });

            function onXMLLoadFailed(){
            alert("An Error has occurred.");
            }

            function parseXML(xml){
            var bounds = new google.maps.LatLngBounds();
                  $(xml).find("location").each(function(){
                      //Read the latitude, longitude and weed indexfor each location
                      var lat = $(this).find('lat').text()*0.01;  //coordinates in XML are in wrong format. Multiply by 0.01 to fix
                      var lng = $(this).find('lng').text()*0.01;  //coordinates in XML are in wrong format. Multiply by 0.01 to fix
                      var weed_index = $(this).find('weed_index').text();

                      //markerCoords = new google.maps.LatLng(parseFloat(lat), parseFloat(lng));

                      markerCoords = {
                          location: new google.maps.LatLng(+lat, +lng),
                          weight: +weed_index
                      };

                      //itterate objects into heatmapData array
                      heatmapData.push(markerCoords);
                      bounds.extend(markerCoords);

                      //console.log(heatmapData);
                  });
                   //map.objects.add(container);
                   //map.zoomTo(container.getBoundingBox(), false);
                  map.fitBounds(bounds);
            }        
}

        /*var heatmapData = [
        {location: new google.maps.LatLng(56.225693, 9.342757), weight: 0.5},
        {location: new google.maps.LatLng(56.225694, 9.342154), weight: 3}
        ];*/

        heatmap = new google.maps.visualization.HeatmapLayer({
        data: heatmapData,
        map: map
        });
        }

function toggleHeatmap() {
        heatmap.setMap(heatmap.getMap() ? null : map);
      }

      function changeGradient() {
        var gradient = [
          'rgba(0, 255, 255, 0)',
          'rgba(0, 255, 255, 1)',
          'rgba(0, 191, 255, 1)',
          'rgba(0, 127, 255, 1)',
          'rgba(0, 63, 255, 1)',
          'rgba(0, 0, 255, 1)',
          'rgba(0, 0, 223, 1)',
          'rgba(0, 0, 191, 1)',
          'rgba(0, 0, 159, 1)',
          'rgba(0, 0, 127, 1)',
          'rgba(63, 0, 91, 1)',
          'rgba(127, 0, 63, 1)',
          'rgba(191, 0, 31, 1)',
          'rgba(255, 0, 0, 1)'
        ]
        heatmap.set('gradient', heatmap.get('gradient') ? null : gradient);
      }

      function changeRadius() {
        heatmap.set('radius', heatmap.get('radius') ? null : 20);
      }

      function changeOpacity() {
        heatmap.set('opacity', heatmap.get('opacity') ? null : 0.5);
      }


    </script>
    <script async defer
        src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDMJI8WJuBPtFqp3VVB7bkLsEWhEtU3Uco&libraries=visualization&callback=initMap">
    </script>
}

  </body>
</html>

Xml file looks like this:

<?xml version="1.0" encoding="UTF-8"?>
<locations>
   <location id="1">
      <lat>5622.5693</lat>
      <lng>934.2757</lng>
      <weed_index>21</weed_index>
   </location>
   <location id="2">
      <lat>5622.5693</lat>
      <lng>934.2757</lng>
      <weed_index>10</weed_index>
   </location>
</locations>

Where you have this:

var weed_index = $(this).find('weed_index').text();
markerCoords = new google.maps.LatLng(parseFloat(lat), parseFloat(lng));

Do this:

var weed_index = $(this).find('weed_index').text();
markerCoords = {
    location: new google.maps.LatLng(+lat, +lng),
    weight: +weed_index
};

NB: The unitary + offers a more efficient way to convert text to number.

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