0

I have longitude and latitude stored in database like

table name: km_stores fields: store_id, store_long, store_lat, store_name

How can I pull the nearest stores using their longitude and latitude?

I am using

<script>
var x = document.getElementById("demo");

function getLocation() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(showPosition);
    } else { 
        x.innerHTML = "Geolocation is not supported by this browser.";
    }
}

function showPosition(position) {
    document.getElementById("km_long").value = position.coords.latitude;
    document.getElementById("km_lat").value = position.coords.longitude;    
}
</script>
<strong>Long:</strong> <input type="text" id="km_long" /> <strong>Latitude:</strong> <input type="text" id="km_lat" />
[php]

global $wpdb;
$results = $wpdb->get_results('select * from km_stores', OBJECT );
foreach ($results as $store) {
            echo $store->store_name;
}
[/php]

[php][/php] tags because I am using PHP in WordPress Pages Plugin.

hindmost
  • 7,125
  • 3
  • 27
  • 39
Karthik Malla
  • 5,570
  • 12
  • 46
  • 89
  • Possible duplicate: http://stackoverflow.com/questions/5031268/algorithm-to-find-all-latitude-longitude-locations-within-a-certain-distance-fro – hindmost Jun 16 '14 at 12:15

2 Answers2

0

Use pythagoras to get their distance away from your coordinates.

If you coordinates are 5, 15 (for arguments sake) and the first store in your like is 10, 20. You can use;

$distance = sqrt((5 - 10) * (5 - 10) + (15 - 20) * (15 - 20))

This formula may give you a negative number, but if you ignore the the -, you'll get the distance.

Apologies, this answer is a bit rough.

Prinsig
  • 245
  • 3
  • 9
0

Right now your select statement is pulling in ALL of the points, so you'll want to limit it to only pull the nearby points. The simplest way to do this is by adding search criteria for the lat and lng values in your database table.

$query = 'SELECT * FROM km_stores WHERE lat BETWEEN ' . $lat - x . ' AND ' . $lat + x;
$query = $query . ' AND lng BETWEEN ' . $lng - x . ' AND ' . $lng + x;
$results = $wpdb->get_results($query, OBJECT );

This assumes that you have $lat and $lng values defined representing the point you want to search around (it looks like you refer to them as km_lat and km_lng). Then you will replace x with a lat/lng distance you want the points to be within. Play with the values to decide what number works for your application.