简体   繁体   中英

Google API piechart javascript array

I have an array list in javascript and it pulls data from an api, it stores it in this format

anti-social-behaviour:37
burglary:20
criminal-damage-arson:12
drugs:1

the problem i am having is when trying to put it into a loop to display on a chart it isn't displaying any data, think i'm going the wrong way about it would like some guidance, i feel as if crimes may not be an array or I am reading it wrong.

var data;
 var chart;

  // Load the Visualization API and the piechart package.
  google.charts.load('current', {'packages':['corechart']});

  // Set a callback to run when the Google Visualization API is loaded.

  // Callback that creates and populates a data table,
  // instantiates the pie chart, passes in the data and
  // draws it.
  function drawChart() {

    // Create our data table.
 var data = new google.visualization.DataTable();
data.addColumn('string', 'Month');
 data.addColumn('number', 'Count');
/*global i*/
for(var i = 0; i ; i++) {
    data.addRow([crimes[i], parseInt(crimes[i])])
  }


    // Set chart options
    var options = {'title':'How Much Pizza I Ate Last Night',
                   'width':400,
                   'height':300};

    // Instantiate and draw our chart, passing in some options.
    chart = new google.visualization.PieChart(document.getElementById('chart_div'));
    google.visualization.events.addListener(chart, 'select', selectHandler);
    chart.draw(data, options);
  }

  function selectHandler() {
    var selectedItem = chart.getSelection()[0];
    var value = data.getValue(selectedItem.row, 0);
    alert('The user selected ' + value);
  }

var police_api_base_url = "https://data.police.uk/api/crimes-street/all-crime?lat=";
var completed_requests = 0;
var num_of_crimes = 0;
var crimes = {};
var committed = false;

function JSON_callback(data){
  completed_requests++;
  var data_len = data.length;
  hide_by_id("num_of_crimes_load_img");

  if (data[0] != undefined){
    for (var i = 0; i < data_len; i++){
      cat = data[i]["category"];
      lat = data[i]["location"]["latitude"];
      lng = data[i]["location"]["longitude"];

      if (cat in crimes) {
        crimes[cat]++;
      } else {
        crimes[cat] = 1;
      }

      create_marker(lat, lng, cat);
      num_of_crimes++;
      committed = true;

    }
  }

MAP.JS // UPDATE

var markers = []; // To erase markers later
var marker_positions = []; // So there aren't multiple markers in the same place
var user_lat = 52.358409; // Random default location
var user_lng = -1.549072;
/*global geocoder*/
/*global google*/
/*global map*/
/*global draggable_marker*/
/*global custom_icons*/
/*global new_lat*/
/*global navigator*/
/*global create_crime_markers*/
/*global new_lng*/
function map_callback(){
  // Without var = set to global scope
  geocoder = new google.maps.Geocoder();
  var new_location = new google.maps.LatLng(user_lat, user_lng);
  var map_properties = {center: new_location, zoom: 15, mapTypeId: "hybrid", zoomControlOptions: {style: google.maps.ZoomControlStyle.SMALL, position: google.maps.ControlPosition.LEFT_BOTTOM}, streetViewControlOptions:{position: google.maps.ControlPosition.LEFT_BOTTOM}};
  map = new google.maps.Map(document.getElementById("google_map"), map_properties);
  draggable_marker = new google.maps.Marker({
      position: new_location,
      map: map,
      draggable: true,
      title: "Drag me",
      icon: "./img/blue_marker.png"
  });
  google.maps.event.addListener(draggable_marker, "dragend", function(){draggable_callback();});
  google.maps.event.addListener(map, "click", function(event){draggable_callback(event.latLng);});
  draggable_callback(); // Trigger first load
}

function search(){
  var address = document.getElementById("search_box").value;
  if (address != ""){
    geocoder.geocode( {
        "address": address,
        componentRestrictions: {country: "UK"}
      },
      function(results, status){
        if (status == "OK") {
          var loc = results[0].geometry.location
          draggable_callback(loc);
          map.panTo(loc);
        } else {
          alert("Cannot perform search, reason: " + status);
        }
    });
  }
}

function clear_markers(){
  for (var i = 0; i < markers.length; i++){
    markers[i].setMap(null);
  }
  markers = [];
  marker_positions = [];
}

function create_marker(lat, lng, title){
  var current_lat_lng = lat.toString() + lng.toString();

  if (marker_positions.includes(current_lat_lng)){
    // Do nothing, dont need multiple markers in one place

  }

  else {
    // Default icon
    var custom_icon = "https://maps.gstatic.com/mapfiles/api-3/images/spotlight-poi.png";
    if (title in custom_icons) {custom_icon = custom_icons[title];}
    var marker = new google.maps.Marker({
        position: new google.maps.LatLng(lat, lng),
        map: map,
        icon: custom_icon,
        title: title
    });
    markers.push(marker);
    marker_positions.push(current_lat_lng);

  }
}

function draggable_callback(loc){
  if (loc != undefined) {draggable_marker.setPosition(loc);}

  new_lat = draggable_marker.getPosition().lat();
  new_lng = draggable_marker.getPosition().lng();

  console.log(new_lat, new_lng);
  clear_markers();
  create_crime_markers(new_lat, new_lng);
}

function get_my_loc(){
  if (navigator.geolocation){
    navigator.geolocation.getCurrentPosition(success_callback, error_callback);
  }
}

function success_callback(position){
  var new_location = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
  draggable_callback(new_location);
  map.panTo(new_location);

}

function error_callback(error){
  switch(error.code){
    case error.PERMISSION_DENIED:
      alert("Denied request for Geolocation");
      break;
    case error.POSITION_UNAVAILABLE:
      alert("Your location information is unavailable");
      break;
    case error.TIMEOUT:
      alert("The request to get your location timed out");
      break;
    case error.UNKNOWN_ERROR:
      alert("An unknown error in finding your location occurred");
      break;
  }
}

You are setting up your datatable object incorrectly. You need to set the number of rows with an integer, then set the cells within the for loop. There is also an issue with your loop counter.

https://developers.google.com/chart/interactive/docs/examples

Try this:

// Create our data table.
var data = new google.visualization.DataTable();
data.addColumn('string', 'Month');
data.addColumn('number', 'Count');
data.addRows(i); // global i

for (var i = 0; i <= crimes.length ; i++) {
    data.setCell(i, crimes[i].category, crimes[i].count);
}
...

Also you set up crimes as an object not an array: crimes = {}; should be crimes = []; , but this will also break your if/else incrementation in JSON_callback. You could fix this by doing something like this:

var item = crimes.filter(function(crime) {
    return crime.category == cat;
});

if(item) {
    item.count++;
} else {
    crimes.push({category: cat, count: 1});
}

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