Question

I have a website with a form containing a list of locations. I want the default selection to be the location closest to the current location of the user.

I know how to get the current GPS location using Javascript, but the problem is that getting the location take some time, and I want the form to displayed immediately, and just reorder/select the closest item when (or if) the location is retrived.

I've never used Jquery before - can someone give me some starting help?

The locations are stored in a MySQL DB and i use PHP to retrieve the data.

Was it helpful?

Solution

If you want to achieve this you should follow this steps:

  • Store all locations contained in the select into the database along with their coords.
  • Store user location coords into the session
  • Select all locations from the database into an array and reorder it using the function below (user coords from the session and each location coords from the database)
  • Display the new select from the array result

Originaly posted here

var rad = function(x) {
  return x * Math.PI / 180;
};

var getDistance = function(p1, p2) {
  var R = 6378137; // Earth’s mean radius in meter
  var dLat = rad(p2.lat() - p1.lat());
  var dLong = rad(p2.lng() - p1.lng());
  var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
    Math.cos(rad(p1.lat())) * Math.cos(rad(p2.lat())) *
    Math.sin(dLong / 2) * Math.sin(dLong / 2);
  var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
  var d = R * c;
  return d; // returns the distance in meter
};
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top