PHPackages                             lukaswhite/uk-postcode-geocoder - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. lukaswhite/uk-postcode-geocoder

ActiveProject[Utility &amp; Helpers](/categories/utility)

lukaswhite/uk-postcode-geocoder
===============================

A PHP library for geocoding UK postcodes

1.0(7y ago)017MITPHPCI failing

Since Oct 21Pushed 4y ago1 watchersCompare

[ Source](https://github.com/lukaswhite/uk-postcode-geocoder)[ Packagist](https://packagist.org/packages/lukaswhite/uk-postcode-geocoder)[ RSS](/packages/lukaswhite-uk-postcode-geocoder/feed)WikiDiscussions master Synced 3d ago

READMEChangelogDependencies (6)Versions (3)Used By (0)

Uk Postcode Geocoder
====================

[](#uk-postcode-geocoder)

A geocoder (PHP) for UK postcodes, based on free open postcode data.

In simple terms, that means you can obtain the latitude and longitude of a postcode.

Data comes from the Office for National Statistics Postcode Directory, and is stored in an SQLite database for blazing fast lookups.

If you want to provide it as a self-hosted web service, you might find [this repository](https://github.com/lukaswhite/uk-postcode-web-service) useful.

A Note about Geocoding UK postcodes
-----------------------------------

[](#a-note-about-geocoding-uk-postcodes)

There are a few different ways of geocoding postcodes, each with their own pros and cons; and indeed there is a key limitation to this library. That's the fact that the data set is not 100% complete. It's very comprehensive; there are currently over 2.6 million postcodes in it. However, PAF — that's the official data set from the Royal Mail — licenses are very expensive.

Because of this, you may need an alternative method such as Google Maps for those rare cases that a postcode is not in this database. However using this library means that the overwhelming majority of your geocoding requests will not incur a cost, and will not be subject to the overhead of using a third-party API.

The other alternative is [postcodes.io](http://postcodes.io/), a free API for doing the same thing; albeit with additional information. This is based on the same ONS data, so if you use this package and keep the data up-to-date, then it's essentially the same as using this package, but with the overhead of an HTTP request. It's open source so you can host it yourself; the primary difference between that and this library is that it's written in Node.js; this is essentially an alternative for those working in a PHP environment.

Getting Started
---------------

[](#getting-started)

Install the package using Composer:

```
composer require lukaswhite/uk-postcode-geocoder
```

**Important**: the data is not included in the package. This is due to the size of the file, and the fact that it's updated periodically.

The package does, however, include a bash script that will create and populate the database for you.

You'll find the data on the [ONS Geo Portal](https://geoportal.statistics.gov.uk/geoportal/catalog/main/home.page), just search for "Postcode Directory".

At time of writing (November 2018), the latest file was published in August 2018.

The file you're looking for is a CSV with a filename similar to `ONSPD_AUG_2018_UK.csv`.

To run the setup process:

```
vendor/lukaswhite/uk-postcode-geocoder/bin/setup.sh [STORAGE DIRECTORY] [PATH TO CSV]
```

For example:

```
vendor/lukaswhite/uk-postcode-geocoder/bin/setup.sh ./storage/database ONSPD_AUG_2018_UK.csv
```

You may also run the provisioning process programmatically; it's all done using the `Provisioner` class; take a look at `setup.sh` to see how to use it.

Usage
-----

[](#usage)

Create an instance, passing it the directory which contains the SQLite database:

```
use Lukaswhite\UkPostCodeGeocoder\Service;

$service = new Service( '/path/to/db' );
```

This assumes that the database filename is `postcodes.sqlite`, but you can override this:

```
$service = new Service( '/path/to/db', 'db.sqlite );
```

Geocoding a Single Postcode
---------------------------

[](#geocoding-a-single-postcode)

To geocode — that's to say, get the latitude and longitude of — a UK postcode, call the `get()` method:

```
$coordinates = $service->get( 'SW1A 2AA' );
```

> The service is quite forgiving about the format; `sw1a2aa` would also work.

This returns an object that contains two key methods; `getLatitude()` and `getLongitude()`. It also includes a `toArray()` method, and implements the `JsonSerializeable` interface.

Geocoding Multiple Postcodes
----------------------------

[](#geocoding-multiple-postcodes)

You can also query multiple postcodes in one go with the `getMultiple()` method, for example:

```
$results = $service->getMultiple( 'AB1 0AG', 'AB1 0AL', 'AB1 0AD' );
```

This returns an associative array of instances of `Coordinate`, keyed by the properly formatted postcode.

Adding Postcodes
----------------

[](#adding-postcodes)

The data is comprehensive — over 2.6 million postcodes — but it's known not to be absolutely complete.

As such, you may need to use another source such as Google Maps if the postcode that you're looking up cannot be found. In such an instance you may wish to add it to this database, which you can do so using the `add()` method; for example:

```
$service->add(
	'sw1A2aa',
	new Coordinate( 51.50354, -0.127695 )
);
```

Note that the library is quite forgiving about how you format the postcode, as you can see above. However passing an invald postcode will throw an `InvalidPostcodeException`. If the postcode is already in the database, it'll throw a `DuplicatePostcodeException`.

###  Health Score

27

—

LowBetter than 49% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity6

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity63

Established project with proven stability

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~938 days

Total

2

Last Release

1824d ago

Major Versions

1.0 → v2.x-dev2021-05-17

### Community

Maintainers

![](https://www.gravatar.com/avatar/f1bd633ffdf0f66a73a288c4edcacfa43d214cd95a53384c6fe5ea4b3554dd9d?d=identicon)[lukaswhite](/maintainers/lukaswhite)

---

Top Contributors

[![lukaswhite](https://avatars.githubusercontent.com/u/999014?v=4)](https://github.com/lukaswhite "lukaswhite (6 commits)")

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/lukaswhite-uk-postcode-geocoder/health.svg)

```
[![Health](https://phpackages.com/badges/lukaswhite-uk-postcode-geocoder/health.svg)](https://phpackages.com/packages/lukaswhite-uk-postcode-geocoder)
```

###  Alternatives

[grumpydictator/firefly-iii

Firefly III: a personal finances manager.

22.8k69.3k](/packages/grumpydictator-firefly-iii)[civicrm/civicrm-core

Open source constituent relationship management for non-profits, NGOs and advocacy organizations.

728272.9k20](/packages/civicrm-civicrm-core)[shlinkio/shlink

A self-hosted and PHP-based URL shortener application with CLI and REST interfaces

4.8k4.3k](/packages/shlinkio-shlink)[craftcms/feed-me

Import content from XML, RSS, CSV or JSON feeds into entries, categories, Craft Commerce products, and more.

292927.5k22](/packages/craftcms-feed-me)[troydavisson/phrets

RETS library in PHP

463355.6k](/packages/troydavisson-phrets)[firefly-iii/data-importer

Firefly III Data Import Tool.

7545.8k](/packages/firefly-iii-data-importer)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
