PHP foreach for Javascript [duplicate]

-1

I'm in the middle of a project where I have clustering on a map. I found this algorithm found in PHP. My question is this foreach :

  foreach ($markers as $key => $target) {
        $pixels = pixelDistance($marker['lat'], $marker['lon'],
                                $target['lat'], $target['lon'],
                                $zoom);
        /* If two markers are closer than given distance remove */
        /* target marker from array and add it to cluster.      */
        if ($distance > $pixels) {
            printf("Distance between %s,%s and %s,%s is %d pixels.\n", 
                $marker['lat'], $marker['lon'],
                $target['lat'], $target['lon'],
                $pixels);
            unset($markers[$key]);
            $cluster[] = $target;
        }
    }

where

$markers   = array();
$markers[] = array('id' => 'marker_1', 
               'lat' => 59.441193, 'lon' => 24.729494);
$markers[] = array('id' => 'marker_2', 
               'lat' => 59.432365, 'lon' => 24.742992);
$markers[] = array('id' => 'marker_3', 
               'lat' => 59.431602, 'lon' => 24.757563);
$markers[] = array('id' => 'marker_4', 
               'lat' => 59.437843, 'lon' => 24.765759);
$markers[] = array('id' => 'marker_5', 
               'lat' => 59.439644, 'lon' => 24.779041);
$markers[] = array('id' => 'marker_6', 
               'lat' => 59.434776, 'lon' => 24.756681);

$clustered = cluster($markers, 20, 11);

How to "translate" to Javascript?

    
asked by anonymous 07.02.2014 / 00:58

2 answers

1

The best thing here is to create an array of objects.

So you can:

var markers   = [];
markers.push = {id : 'marker_1', lat : 59.441193, lon : 24.729494);
// etc

And then use a numeric for loop. Example:

var markers = [];
markers.push({
    id: 'marker_1',
    lat: 59.441193,
    lon: 24.729494
});
markers.push({
    id: 'marker_2',
    lat: 99.441193,
    lon: -24.729494
});
markers.push({
    id: 'marker_3',
    lat: -59.441193,
    lon: -24.729494
});
// etc

for (var i = 0; i < markers.length; i++) {
    var esteObjecto = markers[i];
    var id = esteObjecto.id;
    var lat = esteObjecto.lat;
    var lon = esteObjecto.lon;
    console.log(id, lat, lon);
}

Example

    
07.02.2014 / 08:38
1

Javascript does not yet have an equivalent to foreach of languages like PHP, Perl, etc.

One possible solution is to use for..in with an extra check:

for (var key in obj) {
    if (obj.hasOwnProperty(key)) {
        value = obj[key];
    }
}

But apparently your array has numeric indexes, so the best way is to loop through it with a for "common" loop:

for (var i = 0; i < myArray.length; i++) {
    var value = myArray[i];

    var id = value['id'];
    var lat = value['lat'];
    // e assim por diante
}

To remove an item from an array in Javascript, use the splice method of the Array object:

link

array.splice(0) // remove o primeiro elemento do array
    
07.02.2014 / 02:15