简体   繁体   English

Google API Piechart JavaScript数组

[英]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 我在javascript中有一个数组列表,它从api中提取数据,它以这种格式存储

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 MAP.JS //更新

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. 您需要使用整数设置行数,然后在for循环中设置单元格。 There is also an issue with your loop counter. 您的循环计数器也有问题。

https://developers.google.com/chart/interactive/docs/examples 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 = {}; 另外,您将犯罪设置为对象而不是数组: crimes = {}; should be crimes = []; 应该是crimes = []; , but this will also break your if/else incrementation in JSON_callback. ,但这也会破坏JSON_callback中的if / else增量。 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});
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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