Jump to content

zip code distance calculator


Q695

Recommended Posts

I'll be doing it for users within any given zip code, and calculating the distance to other users, so I don't think the tool is powerful enough.

Why would you think that? Just pass the users entered zipcode to the API and read the results. It'll do exactly what you want.

Link to comment
Share on other sites

I have a sqlite database of zip codes and their geo coordinates. When I want to find the distance between two zip codes I query the db and then use the following function:

<?php

/**
 * This function calculates the distance between two 
 * points (given the latitude/longitude of those points).
 *
 * @param  decimal degrees  latitude of point 1
 * @param  decimal degrees  longitude of point 1
 * @param  decimal degrees  latitude of point 2
 * @param  decimal degrees  longitude of point 2
 * @param  string  the unit for results
 *                   'M' is statute miles
 *                   'K' is kilometers
 *                   'N' is nautical miles
 */
if( ! function_exists( 'distance_between_geo_coords' ) )
{
	function distance_between_geo_coords( $lat1, $lng1, $lat2, $lng2, $unit )
	{
		$theta = $lng1 - $lng2;
		$dist = sin( deg2rad( $lat1 ) ) * 
				sin( deg2rad( $lat2 ) ) +  
				cos( deg2rad( $lat1 ) ) * 
				cos( deg2rad( $lat2 ) ) * 
				cos( deg2rad( $theta ) );
		$dist = acos( $dist );
		$dist = rad2deg( $dist );
		$miles = $dist * 60 * 1.1515;
		$unit = strtoupper( $unit );

		if( strtolower( $unit ) == 'k' )
		{
			return $miles * 1.609344;
		}
		else if( strtolower( $unit ) == 'n' )
		{
			return $miles * 0.8684;
		}
		else
		{
			return $miles;
		}
	}
}

// --------------------------------------------------------------
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.