Search code examples
javascriptapip5.jscodepen

JS - error: Cannot read property 'lat' of undefined


im creating an application using the P5.JS library that shows a dinamic map with each country colored by its current weather, this is what i have so far:

var colors = [];
var paises = ["AR", "BR", "CL", "CO", "GY", "PE", "PY", "UY", "BO", "VE", "EC", "GF", "SR"];

var datacoor;

var url1 = "https://chart.googleapis.com/chart?";
var arg1 = "cht=map&chs=600x500&chld="
var arg2 = "&chco=";
//var URL = url1+arguments;

var img;

function setup () {
  createCanvas(500, 600);
  img = createImg("https://chart.googleapis.com/chart?cht=map&chs=600x500&chld=AR|BR|CL|CO|GY|PE|PY|UY|BO|VE|EC|GF|SR&chco=B3BCC0|5781AE");
  img.hide();

  for (var a = 0; a < paises.length; a++){
    colors.append(colors, color(getColor(paises[a])));

  }
}

function draw  () {
  background(255);

  noStroke();
  fill(30);
  textSize(35);
  //text("zz ", 15, 45);

  if (img) {
    imageMode(CENTER);
    image(img, width/2, height/2);
  }
}

function onData (response) {
  datacoor = response;
  console.log(datacoor);
}

function getColor (loc) {
  var pais = loc;
  var lat;
  var long;

  if (data1.hasOwnProperty(pais)) {
        lat = data1.pais.lat;
        console.log(lat);
    }

}

here´s the problem:

function getColor (loc) {
  var pais = loc;
  var lat;
  var long;

//data1 is a variable with the list of all countries and their coordinates
  if (data1.hasOwnProperty(pais)) {
        lat = data1.pais.lat;
        console.log(lat);
    }

}

its looking for the object "pais" instead of the object inside of the variable "pais", how can i fix this? Any help appreciated


Solution

  • I'm going to guess you meant to do:

    lat = data1[pais].lat;
    

    pais will be interpreted as a string, and should act as you intend by getting the property with the value of the variable pais.

    This is known as "bracket notation".