Mark West
Mark West

Reputation: 267

Access to obects in an array

Here I have a an bigArray in which I have objects. Every object have top,left,lat,lng elements.

 bigArray  [Object, Object, Object, Object, Object, Object, Object, Object, Object]
    0: Object
    lat: 33.543
    leftPosition: 54
    lng: 56.345
    topPosition: -3
    __proto__: Object
    1: Object
    lat: 32.4534
    leftPosition: 197
    lng: 45.634345
    topPosition: 57
    __proto__: Object
    2: Object
    lat: 34.6434
    leftPosition: 245
    lng: -102.324234
    topPosition: -3
    __proto__: Object
    3: Object
    lat: 23.3423
    leftPosition: 330
    lng: 57.5343
    topPosition: 57
    __proto__: Object
    4: Object
    5: Object
    6: Object
    7: Object
   // N number of array etc... ...: Object
    length: 9
    __proto__: Array[0]

Now I have this function which calculate km distance based on lat and lng beetween two places:

var loc1 = { lat: 42.672708, lon: 23.32147800000007 };
var loc2 = {lat:42.670242, lon:23.315002999999933};

function arc_distance(loc1, loc2) {
    var rad  = Math.PI / 180,
        earth_radius = 6371.009, // close enough
        lat1 = loc1.lat * rad,
        lat2 = loc2.lat * rad,
        dlon = Math.abs(loc1.lon - loc2.lon) * rad,
        M    = Math;

    return earth_radius * M.acos(
        (M.sin(lat1) * M.sin(lat2)) + (M.cos(lat1) * M.cos(lat2) * M.cos(dlon))
    );
}
alert (arc_distance(loc1,loc2));

but now I have a problem how to calculate distance beetween all objects? so object[0]---distance---object[1]---distance---object[2]---distance---object[N] , where is N number of objects in bigArray

So how I can acces to object[0].lat.lng , object[1].lat.lng , object[2].lat.lng and based on my function calculate distance beetween object and distance add to object so Object will be object{top,left,lat,lng, DISTANCE_FROM_PREVIOUS_OBJECT_LOCATION}

Upvotes: 0

Views: 107

Answers (2)

dcodesmith
dcodesmith

Reputation: 9614

Try this

for (var i = arr.length-1; i > 0; i--) {
        arr[0].DISTANCE_FROM_PREVIOUS_OBJECT_LOCATION = 0; 
        arr[i].DISTANCE_FROM_PREVIOUS_OBJECT_LOCATION = arc_distance({lat: arr[i-1].lat, lon: arr[i-1].lng}, {lat: arr[i].lat, lon: arr[i].lng});
}

JSFIDDLE

Upvotes: 1

Moazzam Khan
Moazzam Khan

Reputation: 3170

Does this work for you?

bigArray[0].DISTANCE_FROM_PREVIOUS_OBJECT_LOCATION=0;
for(var i=bigArray.length;i>0;i--){
   bigArray[i].DISTANCE_FROM_PREVIOUS_OBJECT_LOCATION=arc_distance(bigArray[i-1], bigArray[i]);
}

Upvotes: 1

Related Questions