This is a step by step guide for building a find nearest/store locator ** for free** in PHP just like Postcode Anywhere.

It requires PHP and a mySQL database. That's all.

You don't *need* Google Maps, but it helped me populating the database, so I've included it for completeness. The example I'm using is UK based, but provided Google have a postcode/zipcode to lat/long convertor for your country, it should work nicely.

## Background Maths

Before we start, it's time to go back to school with some background maths.

Don't be tempted into Pythagorean territory here, because the world isn't flat and the distance between lines of longitude gets smaller as we get closer to the poles. Also with the curvature of the earth for distances over say 15 miles, the sides of the triangle go from straight into an arc - not good.

Trying a little harder, we get to the Great Circle Distance method.

The **Great Circle Distance Formula** using radians:

r * acos[sin(lat1) * sin(lat2) + cos(lat1) * cos(lat2) * cos(lon2 - lon1)]

Where r is the radius of the earth *e.g. r = 3963.0 miles*

or

As I'm lazy, I want to add this directly into a SQL query that checks against lat/long values for my stores in my database.

Converted to (my)SQL syntax using lat/long in *degrees* becomes:

[source language="sql"]SELECT 3963.0 * ACOS( SIN( lat1*PI()/180 ) * SIN( lat2*PI()/180 ) + COS( lat1*PI()/180 ) * COS( lat2*PI()/180 ) * COS( (lon2*PI()/180) - (lon1*PI()/180) ) ) AS distance;[/source]

Assuming mySQL uses double precision, we can be assured that the calculation is reasonably accurate. Although the arcos formula can suffer from rounding errors at small distances. But in my experience, it works well when compared to other distance calculators (e.g.GMap Pedometer and Daft Logic Google Maps Distance Calculator).

## Building the scripts

This example is unashamedly simplifed. The PHP is procedural and basic. It is for demonstration only - apply you own favourite MVC framework when working this up.

### Create a simple mySQL database table for stores

In reality, you'd probably want to add columns for phone no, web address, email etc.

### Add some data to the table

I'm using real locations of Apple computer stores in the UK...

The lat/long values can be populated manually (e.g. go get them from Google Maps) or automatically using a function similar to this:

...but you'll need a Google Maps API key

Example for the Apple Store in Regent Street:

### Build the search/results page

By the way, properly cleanse `$_REQUEST['postcode']`

to prevent XSS attacks. The code above is for demo only.

### Reference

### Update

If you find this useful, but are still having trouble, here's an excellent article — Creating a Store Locator with PHP, MySQL & Google Maps from Google.