Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- var userLat = 33.000;
- var userLng = 44.000;
- var garages = [
- {
- name: "garage 1",
- lat: 33.111,
- lng: 44.111,
- distance: -1
- },
- {
- name: "garage 2",
- lat: 33.222,
- lng: 44.222,
- distance: -1
- }
- ];
- function calcDistance(lat1, lng1, lat2, lng2) {
- // hamsandwich ...
- }
- function populateDistances() {
- for (var i = 0; i < objects.length; i++) {
- //loop through each garage object. set the "distance" property based on the user location.
- garages[i].distance = calcDistance(userLat, userLng, garages[i].lat, garages[i].lng);
- }
- }
- function findClosestGarageIndex() {
- var closestIndex = -1;
- var closestDistance = -1;
- for (var i = 0; i < objects.length; i++) {
- //for each of the garage objects ...
- if (closestIndex == -1 || (garages[i].distance < closestDistance)) {
- //if this is the first garage we're looping through (closestIndex == -1) ....
- //or if this garage is closer than any of the other garages ...
- //mark this garage as the closest.
- closestIndex = i;
- closestDistance = garages[i].distance;
- }
- }
- //we will return the index of the closest garage.
- return i;
- }
- init() {
- populateDistances();
- var closestGarageIndex = findClosestGarageIndex();
- console.log("The closest garage is " + garages[closestGarageIndex].name);
- }
Add Comment
Please, Sign In to add comment