Question

I have a database of addresses and I want to be able to have a user drop a pinpoint on the map and define a region based on driving distance around that point. I was wondering if there was a way to search my database by that user defined region.

Was it helpful?

Solution

For the International System that uses Kilometers, replace a part of the script with this one:

6371 * acos( cos( radians(LATITUDE1) ) * cos( radians( LATITUDE2 ) ) * cos( radians( LONGITUDE1 ) - radians(LONGITUDE2) ) + sin( radians(LATITUDE1) ) * sin( radians( lat ) ) ) AS DISTANCE

Source: http://www.codecodex.com/wiki/Calculate_Distance_Between_Two_Points_on_a_Globe#MySQL

OTHER TIPS

You should be able to get the longitude and latitude coordinates of the pin drop, then send that data to your server and return a result using the query listed on this page: http://code.google.com/apis/maps/articles/phpsqlsearch.html

SELECT id, ( 3959 * acos( cos( radians(37) ) * cos( radians( lat ) ) * cos( radians( lng ) - radians(-122) ) + sin( radians(37) ) * sin( radians( lat ) ) ) ) AS distance FROM markers HAVING distance < 25 ORDER BY distance LIMIT 0 , 20;

You would need to geocode your addresses into longitude and latitudes as well, and store them with each address though. This is the exact code I used to scrape longitude and latitudes for addresses in my database:

  /* Geocode Address
  /***********************/
  $query = $db->query("SELECT * FROM wholesale_clients WHERE hq_id IN (SELECT owner_id FROM storelocator)");
  while($info = $query->fetch_array()) {
    $address = str_replace(' ', '+', $info['address_1'] . ' ' . $info['address_2'] . ' ' . $info['suburb'] . ' ' . $info['state'] . ' ' . $info['zip'] . ' Australia');
    $file = file_get_contents('https://maps.googleapis.com/maps/api/geocode/xml?address='.$address.'&sensor=false');
    $file = xml2array($file);
    $lat = $file['GeocodeResponse']['result']['geometry']['location']['lat'];
    $lng = $file['GeocodeResponse']['result']['geometry']['location']['lng'];
    //echo $info['hq_id'] . ' ' . $lat . ' ' . $lng . '<br />';
    if(!empty($lat) && !empty($lng)) {
    $db->query("UPDATE `storelocator` SET `lat` = '" . $lat . "', `lng` = '" . $lng . "', `updated` = 1 WHERE `owner_id` = '" . $info['hq_id'] . "'");
    }
  }

  /***********************/

XML2array function: http://www.bin-co.com/php/scripts/xml2array/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top