4

We have 100 users in our system,While registering they have entered their zipcodes,Now what i need is if I enter any zipcode it should give me the result with distance between entered zipcode and other 100 users zipcode ?

Is it possible to do, help me out if anybody know the solutions ?

Nadh
  • 6,987
  • 2
  • 21
  • 21
jsduniya
  • 2,464
  • 7
  • 30
  • 45
  • 3
    Use a zipcode lookup to convert each to a lat/long coordinate pair; then use Haversine or Vincenty to calculate distance - there's thousands of blogs and tutorials out there answering this – Mark Baker Aug 07 '13 at 07:16
  • 1
    http://stackoverflow.com/questions/2296087/using-php-and-google-maps-api-to-work-out-distance-between-2-post-codes-uk – cartina Aug 07 '13 at 07:22

2 Answers2

2

I'd do this in two parts:

  • A geocoding script, run once and results stored in persistent cache (eg. database). This way you will avoid hitting rate limits and speed up the final lookup.
  • Script for calculating distance, run when required or cache this too to build a lookup table storing distances between each postcode and all the others. As you only have 100 zips this lookup table would not be very large.

Geocoding

<?php
// Script to geocode each ZIP code. This should only be run once, and the
// results stored (perhaps in a DB) for subsequent interogation.
// Note that google imposes a rate limit on its services.

// Your list of zipcodes
$zips = array(
    '47250', '43033', '44618'
    // ... etc ...
);

// Geocode each zipcode
// $geocoded will hold our results, indexed by ZIP code
$geocoded = array();
$serviceUrl = "http://maps.googleapis.com/maps/api/geocode/json?components=postal_code:%s&sensor=false";
$curl = curl_init();
foreach ($zips as $zip) {
    curl_setopt($curl, CURLOPT_URL, sprintf($serviceUrl, urlencode($zip)));
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
    $data = json_decode(curl_exec($curl));
    $info = curl_getinfo($curl);
    if ($info['http_code'] != 200) {
        // Request failed
    } else if ($data->status !== 'OK') {
        // Something happened, or there are no results
    } else {
        $geocoded[$zip] =$data->results[0]->geometry->location;
    }
}

Calculating distance

As Mark says, there are a swathe of good examples for this, such as Measuring the distance between two coordinates in PHP

Community
  • 1
  • 1
jgauld
  • 639
  • 5
  • 10
0

There is a Zip Code API that does that - http://zipcodedistanceapi.redline13.com/API.

Bob Bickel
  • 349
  • 2
  • 3