JSFiddle - React, Tailwind, and code Playground

by ArchersFiddle

JavaScript

var _stores = [{
    storeName: "StoreName1",
    latitude: -26.01672,
    longitude: 28.127379,
    storeNum: "0113675700"
}, {
    storeName: "StoreName2",
    latitude: -26.018744,
    longitude: 28.007777,
    storeNum: "0115535800"
}];

var _position = {};

function success(position) {
    console.log(position);
    _position = position.coords;
    sortStoresByDistance();  // this is explained further down
    console.log(_stores);
    alert("Your nearest store is " + _stores[0].storeName + " (" + _stores[0].storeNum + ")");
}
function error(err) {
    alert("Geolocation error : " + err);
}
var options = {
    enableHighAccuracy: true,
    timeout: 5000,
    maximumAge: 10
};

function googleCallback() {
    navigator.geolocation.getCurrentPosition(success, error, options);
}

$.getScript("https://www.google.com/jsapi", function () {
    google.load("maps", "3", {
        other_params: "sensor=false",
        streetViewControl: false,
        callback: function () {
            googleCallback();
        }
    });
});

if (typeof (Number.prototype.toRad) !== "function") {
    Number.prototype.toRad = function () {
        return this * Math.PI / 180;
    }
}

function sortStoresByDistance() {
    for (var i = 0; i < _stores.length; i++) {
        _stores[i].distance = getDistance(_position, _stores[i]);
    }
    _stores.sort(function (a, b) {
        return a.distance - b.distance;
    });
}

function getDistance(position1, position2) {
    var lat1 = position1.latitude;
    var lon1 = position1.longitude;
    var lat2 = position2.latitude;
    var lon2 = position2.longitude;

    console.log(lat1, lon1, lat2, lon2);

    var R = 6371; // km
    var dLat = (lat2 - lat1).toRad();
    var dLon = (lon2 - lon1).toRad();
    var lat1 = lat1.toRad();
    var lat2 = lat2.toRad();
    var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
            Math.sin(dLon / 2) * Math.sin(dLon / 2) * Math.cos(lat1) * Math.cos(lat2);
    var c = 2 * Math.atan2(Math.sqrt(a),...