0

I'm developing a map that uses the distance between points on a Google Maps.

Now I run into a problem since my knowledge about javascript is a beginner. I cannot calculate all the distances and have it in an array. (needed to check all the distances and pick the closest.)

Here is my code so far: (first lat1,lng1 are my geolocations) (live: http://www.cosound.nl/index-v01.html)

    var locations = [
    ['ArtEZ Institute of the Arts', 51.983776, 5.893732, 5],
    ['Renssenstraat 9-12', 51.984874, 5.897199, 4],
    ['Utrechtsestraat 53', 51.983703, 5.897809, 3],
    ['Oude Kraan', 51.982593, 5.898420, 2],
    ['Montevia Studenthousing', 51.981833, 5.901081, 1 ]
    ];

    // The above ones is my array of locations

    var currentDist;

    // This is the code I'm using to try and get back the distances.

    // Assuming that I need to put some counter in the function....

    function distance(lat1,lng1,lat2,lng2) {
    var R = 6371; // km (change this constant to get miles)
    var dLat = (lat2-lat1) * Math.PI / 180;
    var dLon = (lng2-lng1) * Math.PI / 180;
    var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
        Math.cos(lat1 * Math.PI / 180 ) * Math.cos(lat2 * Math.PI / 180 ) *
        Math.sin(dLon/2) * Math.sin(dLon/2);
    var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
    var d = R * c;
    if (d>1) return d;
    else if (d<=1) return Math.round(d*1000);
    return d;
    }

Maybe I can use a for loop?

    for (count = 0; count < locations.length; count++) {  

    }

Tried this myself:

    for (count = 0; count < locations.length; count++) {  
            currentDist = distance(lat1,lng1,locations[count][1],locations[count][2]);
        }

Would like to store them in the array, or at least be able to use them somewhere else.

  • possible duplicate of [Google Maps API - Closest marker function change to closest n markers](https://stackoverflow.com/questions/27905570/google-maps-api-closest-marker-function-change-to-closest-n-markers) – geocodezip Apr 01 '18 at 01:48

1 Answers1

0

You can use a for loop and push the distance in your array:

for (var i = 0; i < locations.length; i++) {

  locations[i].push(distance(lat1, lng1, locations[i][1], locations[i][2]));
}
MrUpsidown
  • 21,592
  • 15
  • 77
  • 131