Calculating distance between two post codes - php

I would like some help with how to go about calculating the distance between two post codes. Here is the setup that I wish to have, let me give you a scenario.
A user logs into my website (they have provided their details, their postcode being one of them). That data is stored in the users table.
I have another table with details about locations. I would like to display locations (and the distance) that are closest to the user.
I know that there are certain methods that can be used, for example:
Converting a postcode to a long-lat and using built in methods to calculate the distance, I think Google offer a free service. But I have no idea how I would implement such a thing. All the tutorials I have taken a look at seem too complicated and for the time being I want a very crude and simple solution upon which I can build and more importantly learn!
I am fairly familiar with PHP and MySQL when it comes to basic input/output of data. But I am not sure of the best way to handle the information with regards to user data, and the locations of the 'businesses'.
Any suggestions, comments will be more than appreciated.

If you're US based, this API should meet your needs: https://www.zipcodeapi.com
It's made specifically to find distance between two zip codes, tells you the long-lat for zip codes, find all zips relative to a location, etc.

Get postcode northings eastings data free from ordinance survey (credit them on your webpage to get free)
2 calculate distance from the appropriate csv flat file (M.csv contains all manchester postcodes and north and eastness).
Distance is sqrt((n1-n2)**2 +(e1-e2)**2) - excuse my fortran
If its slow,and you want an approximate distance create a small database of first half postcodes averages so you are looking up M20 not M20 3nb.
5 NB google don't like you using their postcode apis outside google Maps.
I am wondering about an algorithm so that for short distances, if you are looking at places close to a postcode, you just search M postcodes for a M postcode (and maybe nearby post areas like SK, OL, if you have a table of adjacent postcode areas).
7 Any body taken this further?

Related

Generate countries map based on geoip data

I have searched a lot on this topic, and have found no answers.
I have my own statistics package where I'm saving the geoip data of my users (along with a bunch of other data). I'm using the maxmind geoip library to get this information.
So, in my backend I'm visualizing this data as text that have basically two columns, one for the country name and another for the number of visits from the country.
I'd like to generate a map with this data.
something like a world map with the countries I have visits from highlighted.
Heat mapping would be nice, but not required.
I dont really care if it's generated with php (GD image library) or jquery, since I'm already using both those technologies for the statistics backend. But I'd REALLY like to do this without google analytics or their graphing APIs.
I will try to suppose. The way I would try do it ...
Get FullHD (or HighRes world map)
Coordinates I'd keep in WGS84 standard (float values, otherwise it is easy to convert)
I would try to approach real coordinates to the scale of image, but before this ...
The major part in this work is Math. I'm actually not a mathematician, but I know that it should be applied here and why.
Main goal here is to project coordinates on a flat surface, bec. WGS84 uses oblate spheroid as a reference surface (with radius = 6378137 m; flattering = 1/298.257223563), so it is not ideal circumference and it should be taken into account. + image should be GEO binded somehow (you should know coordinates of corner angles of this image #least. it is the easiest case if so).
Calculations for this case are not very massive, everything leads to the elementary plane geometry.
Here is the library that could help you working with geospatial data http://www.gdal.org/.
My advice to you, to consult some specialists in this field if you know nothing about it (maybe SatCom spec. or MobCom spec. in some university/academy) (or try Google if you are familiar enough with math and GEO) and to ask for a math model for projection of GPS coordinates to the flat surface and you will definitely get the answer.
If you don't need very high accuracy, try it yourself maybe you'll have luck.
You can try yourself in MatLab (more applicable in this case) or Mathcad if you know math enough and try yourself to position few points on the raster.
If you will find the answer in the nearest future, I would be glad if you post it here or share with me your solution for the particular case.
i need to finally answer my own question here. for anyone else who stumbles across this:
i have been using the d3js library with the topojson extension.
https://github.com/mbostock/topojson

Postcode Radius Validation

I need to offer user's who Live in x location in the UK.
I'm currently having users enter their postcode via a form I've built, the postcodes get submitted to the database and I use Google search to check their in a close proximity to which I can offer services.
This sometimes can take me hours to manually hack through hundreds of postcodes this way so I'm looking to automate the process; if I could have the postcodes run through a script that'll determine if postcode x is within y miles of postcode z I'll be able to die happy.
Speed is also an issue for me, so I'm looking for a solution that doesn't rely on an external web service. Does anyone know of a script that'll do the trick?
What I would do is map postcodes to latitude and longitude and then use the distance formula between lat/lon coordinates to find out how far away they are.
Link for formula: http://www.mathforum.com/library/drmath/view/51711.html
Link for postcode -> lat/long values: http://www.freemaptools.com/download-uk-postcode-lat-lng.htm (this should be okay but haven't checked)

PHP - Postcode check if it's covered

I am currently developing a website for an electrical company. They would like some sort of postcode check on there. It would somehow work like this:
User enters postcode
See if we cover it
display results.
But I have never worked with postcodes before. How would I be able to check whether they cover it. I obviously need some sort of database listing the postcode or area they cover. But how would I also check if the postcode is valid.
The postcode lookup is obviously to see if the electrical company covers the user's area.
Thanks in advance.
I think instead of using a database to search your results, you would be better of looking at geo location, and using a 3rd party to calculate everything for you.
Google and Sony both provide Geo Location platforms
Sony has: http://www.placeengine.com/en
Google has: http://code.google.com/apis/maps/documentation/distancematrix/
I obviously need some sort of database listing the postcode or area they cover.
Yes. Then do a simple look up.
But how would I also check if the postcode is valid.
You would have to have a database listing all possible post codes and do a similar check.
I don't know which country you are in, but in most countries there is no programmatical way of determining wether a postcode is covered by a service or not.
Also no way of knowing wether it is valid or not without consulting a database that contains coverage.
There are databases available with postal codes, here is a dutch one: http://www.postcode.nl/index/269/1/0/overzicht-producten-en-diensten.html
You can validate the postal code using a regular expression.
The electrical company could surely give you a list of postcodes they do cover? Then it is a simple string matching from there....
I assume you are interested in the UK. To see if a postcode is valid grab the free CodePoint open data set from OS: http://www.ordnancesurvey.co.uk/oswebsite/products/code-point-open/
You could pull that into a DG and cross check user input. Just remember that this data is based on the Royal Mail PAF, so do not assume it is 100% accurate. Build a bit of flexibility/fault tolerance into your code.
If the client wants a specific radius covered, you coudl also use the OS data for distance calculations... and it is all FREE, as in both freedom and free beer :-)
As a first step you could check if the postcode is in a valid format: http://en.wikipedia.org/wiki/Postcodes_in_the_United_Kingdom#Validation - this check will pre-filter input for you.

Post Code Lookup

A client wants a page on their website where the user can search for a stockist of their product range. What they want is the ability to enter a UK PostCode and for a list of their stockists to appear in closest order.
Is there a way to utilise Google Maps to determine the closest supplier?
I have a PHP MySQL database with ALL the suppliers Postcodes and details and I'll have the postcode of the user to use as well.
I think you'll need the Ordnance Survey CodePoint data to map your postcodes to a longitude and latitude. Codepoint is available as a commercial product, or there's also Codepoint Open
Once you have the latitude and longitude, then you can use standard algorithms such as Haversine or Vincenty to calculate distances between the points
EDIT
Structure of the CodePoint Open CSV files can be found here. Note that location is held as Northings and Esatings rather than Longitude and Latitude, so it will need converting. There's a number of articles about this on the web, e.g.
http://www.deepbluesky.com/blog/-/converting-os-coodinates-into-longitude-latitude_7/
http://mediakey.dk/~cc/convert-northing-and-easting-utm-to-longitude-and-latitude/
but you need to be aware that OS Northings/Eastings are based on the Airy 1830 ellipsoid rather than the WGS84 model used by Google maps (and most GSM systems). Failing to allow for this difference can put you out by anything between 70-120m between Cornwall and East Anglia.
You can also find PHP functions to do this conversion at the Movable Type site (essential reading for any PHP developer, working with GeoData. I'd recommend adding a couple off columns to your stockist database for longitude and latitude, and a one-off script to update all existing data using the Codepoint data, then modify your insert/update routines for stockists to keep this information up-to-date.
Using PHP, another solution for this conversion is PHPCoord by Jonathan Stott
For higher performance in your database query, do a lookup of lat/long against a "bounding box" before calculating distances. I've explained how to do this in response to a similar query.
I think you'll need a little more data than that. I'd suggest that you need to store the latitude and longitude of every UK postcode alongside the postcode itself. I think this data is available from the Royal Mail for a cost and I remember reading somewhere that it was going to be available in the public domain too. Have a user enter their postcode, look up their latitude and longitude in the db and then use that to perform another query that calculates the closest supplier to them, perhaps within a certain number of miles. You could perhaps create a stores procedure to do all of this on the db. This post seems to have some details on how to do this.
If you want it to be fast then pre-compute the distances between postcodes within a certain radius of each other - see the following:
Calculate distance between zip codes and users
This should work fine in your case unless you think a user would be willing to travel more than 100 miles to purchase a product ??
Instead of Google Maps, this open postcode geocoding API may be of use to you. As others have mentioned, once you have lat long for both points you can use standard algos to find distances. A previous question contains some info on how to do this directly in SQL.
You may find this website helpful: SQL/CSV Postcode Database
I've previously used this to lookup long/lat from a postcode "outcode".
There's also a php script (which I've not tested) which calculates distance between two postcodes.

google Maps getDistance without loading the page

Google maps has a function that lets you retreive the distance between two points: getDistance(), of the GDirections class.
Now, this is Javascript, so it'll only be able to calculate once the page has loaded.
My search form however, has the ability to indicate what's the maximum distance you want between yourself and another person and based on that, a list of search results has to be provided.
Since I can't use this function in PHP, is there another way for me to calculate the distance between 2 points on the earth? By giving up the street, postal code and city name, just like what Google maps needs.
This page has a list of google maps parameters for use in http connection. By specifying the output paramter you can choose to give back kml files or similar and can be used in any lanuage that can make http connections.
Looks like you want to calculate a Great Circle Distance
Formulas have been discussed here on stackoverflow before.
A point on earth is defined by it's latitude and longitude. If you want to calculate the distance between 2 points on earth by giving up the street, postal code and city name, you will need geo-referene data.
This data is available for free on the internet, but the accuracy and availability differ greatly from region to region. (USA data is of good quality, data for Kenia for example will be harder to come by)
So to answer your question:
Yes, there are other ways to calculate what you want. But they require more work/are more complex than just querying the google API.
You might want tot read: Creating a Store Locator with PHP, MySQL & Google Maps
Hope this points you into the right direction.
You can use kml file. It's xml-formatted file that you can recieve by link like http://maps.google.com/maps?f=d&hl=en&saddr=<src latitude>,<src longitude>&daddr=<dist latitude>,<dist longitude>&ie=UTF8&0&om=0&output=kml
in recieved file you can parse and summate distances from

Categories