kinath_ru
kinath_ru

Reputation: 4678

Calling javascript object value gives me 'undefined'

I'm working on a google map application and I want some markers to load from a db and display them on a map. So I created an array and defined an object like this.

function shop_data(name,latitude,longitude,type)
    {
    this.name=name;
    this.latitude=latitude;
    this.longitude=longitude;
    this.type=type;
    }

Then I added some data retrieved from an ajax request to an array of 'shop_data' objects. The array is defined as 'all_shops'.

var i=0;
for(var o in data){
var name = data[o].name;
    var type = data[o].type;
var lat = data[o].lat;
var lng = data[o].lng;

all_shops[i]=new shop_data(name,lat,lng,type);
i++
}

Then when i call 'all_shops[i].name', it gives me the name as it is. But when I call 'all_shops[i].lat' or 'all_shops[i].lng' it gives me 'undefined'. I tried parsing the lat,lng too. Here lat, lng are double variables in MySQL database. I can get the lat,lng values without a problem from the received ajax data by calling, just name,type,lat,lng. But things go wrong when i put them all in an array and , call them from the array. Any help would be appreciated. Thanks.

Upvotes: 0

Views: 343

Answers (3)

vdbuilder
vdbuilder

Reputation: 12964

Changing variable names to match and a little cleanup gives:

function shop_data(name,latitude,longitude,type){
    this.name=name;
    this.lat=latitude;
    this.lng=longitude;
    this.type=type;
}

and:

var i=0;
for(var o in data){
    var name = data[o].name;
    var type = data[o].type;
    var lat = data[o].lat;
    var lng = data[o].lng;

    all_shops[i]=new shop_data(name,lat,lng,type);
    i++
}

Upvotes: 1

Yograj Gupta
Yograj Gupta

Reputation: 9869

You should call your latitude or longitude from all_shops[i] not lat or lng as you have your shop_data function definition like this

function shop_data(name,latitude,longitude,type)
{
   this.name=name;
   this.latitude=latitude;
   this.longitude=longitude;
   this.type=type;
}

or if want to use lat or lng then change shop_data function definition like

function shop_data(name,latitude,longitude,type)
{
   this.name=name;
   this.lat=latitude;
   this.lng=longitude;
   this.type=type;
}

Upvotes: 1

Grzegorz
Grzegorz

Reputation: 3335

Change from

this.latitude=latitude;
this.longitude=longitude;

to

this.lat=latitude;
this.lng=longitude;

You have a simple copy/paste error.

Upvotes: 1

Related Questions