开发者

Profile Location Information using PHP/MySQL and optionally JavaScript

One of the sites I work on is a social networking site of sorts, and the content would be greatly enhanced by using some sort of location service to recommend "friends" based on proximity. The site focuses on the US, but with potential users worldwide.

I've considered creating an associative array or relational database with countries, states/provinces/territories, counties, and cities to provide a rough way to drill down to their relative proximity, but this can be extremely unwieldy and complicated very quickly.

I've also considered IP geolocation, but the results tend to be unreliable (some services show my company's I开发者_如何学JAVAP as located some 600 miles North-east), and I would at least need some sort of fallback to lookup, for instance, a zip/postal code.

Can you tell me a clear defined way to effectively do this sort of lookup locally, without use of 3rd party APIs, preferably with at least some reference to where to gather the basic information from in the first place? I'm currently running PHP 5.3.2 and MySQL 5.1.44, if it makes any difference.

Thank you!

EDIT: Added a bounty to try to get better ideas, or other ways of handling the problem, perhaps more efficiently. As it is, the load time due to the huge database size is insane. I figure I definitely need to improve my caching, but I'm trying to see if there's anything I should be doing with regard to improving my location system.


This might be a bit obvious... but the only way that you can know the location of a user, with the best degree of accuracy is to actually:

Ask the User where they are!

Once you have asked the user where they are, you can then use third party applications to figure out distances. If you don't want to use any third party application as your question mentioned, then you could download and integrate one of the Geo databases into your own service.

The source which I use is Yahoo Geo Planet.

You can download the entire GeoPlanet Data file which comes in TSV format. When I downloaded it I just imported it to mysql using mysqlimport.

http://developer.yahoo.com/geo/geoplanet/data/

It contains a record for every distinct geographically location in the world. A tonne of post codes, districts, regions, countries, practically everything you would ever need.

In addition to that, it contains neighbours, so you can query based on geographic regions which are close to.


Unfortunately, simply asking where they are isn't quite good enough, and while GeoPlanet is a good option, and I have decided to use it, I didn't feel it was a complete answer. Yes, it works, but -how-. Aliases don't cover misspellings, and while most outsiders call San Francisco things like "San Fran" or "Frisco", locals use "The City", so aliases don't always work. I needed some level of exactitude.

Well, after some work, here's the approach I've used, which is a bit intensive, and may not be an option for everybody, but works for me:

First thing, grab a copy of the GeoPlanet db in TSV format from http://developer.yahoo.com/geo/geoplanet/data/ (105 MB Zipped)

To import this into my MySQL db, I created the tables with columns named according to the Readme file located in the zip. Geoplanet_places was the only one given a primary key associated to the WOE_ID. This and geoplanet_adjacencies are really the only tables I need at this moment. For me, importation was done locally to my DB using:

mysqlimport --socket=/PATH/TO/SOCKET/mysql.sock --user=EXAMPLE --password=EXAMPLE DATABASE_NAME /PATH/TO/DOWNLOADED/GEOPLANET/DATA/geoplanet_places.tsv

I stripped the version number from the .tsv, and used the filename as the table name. Your experience may be significantly different, but I'm adding it for clarity. Import all the files you want.

I decided to have two options for people entering their profile data: You always have to select your country (from an option list, using ISO 3166 Alpha-2 Codes as the value), but we can then use either the postal (ZIP/PIN) code to look up where they are; or, for countries like Ireland lacking a national postal code system, they can enter their city and province name.

To search using country and postal code, I can do something like this:

SELECT Parent_ID FROM geoplanet_places WHERE ISO = "$ctry" AND Name="$zip" AND PlaceType="ZIP";

I count the results. If 0, I have no result, the place is not known, and I assume a problem (An error is logged accordingly to confirm it is not a fluke). If there is more than one, the results are enumerated and a next screen pops up asking to confirm in which location they reside. Ideally, this should never happen with the postal code system, but may occur when asking based on location. If there is only one, I store the Parent_ID to their profile asI continue to query back, passing back in the Parent_ID as a comparator to the WOE_ID, as so:

SELECT Name, WOE_ID, Parent_ID FROM geoplanet_places WHERE WOE_ID="$pid";

Where $pid is the previous Parent_ID - I'll use this later on when rendering the page to determine location, and Town/City is low enough of a level to apply proximity checks on the adjacencies table. Trying to join the results was significantly slower than throwing multiple queries when I ran it with MySQLWorkbench. I continue the queries until Parent_ID="1" meaning that it's parent is the world (it is a country).

I decided that when I'm searching using text entry for city, state/province, and country, I'll have to guarantee accurate entry by confirming using a Metaphone processor to determine their likely selection if it can't be found the first time. Unfortunately some people either can't spell or the primary language of the site is not their primary language.

To display location, I start with the WOE_ID stored in their profile, get the name, then look up it's parent. I comma-separate to get a result like Irvine, Orange, CA, USA. I can look up based on any one of these names to determine other members in proximity using the adjacencies and places tables.

Again, this probably isn't the best way to go about it, and using Geolocation can change if, for instance, you're on a trip using the hotel wifi; however, this method seems "close enough for government work", so I thought I'd share my solution as worthless as it may be.


This solution is generally more accurate & useful than the only matching at the city level, but it will require you to use third-party services for geocoding when a user signs up if you only have their address. Hope it still helps.

1) Get the users's location. Use as much information as you can get:

  • Ask them where they are when they register
  • Use the HTML5/JS navigator.geolocation API http://merged.ca/iphone/html5-geolocation (works well with iPhones and the like)
  • Use IP geolocation database like http://www.maxmind.com/app/geolitecity (it's free, can be downloaded once and used locally, though it should be updated monthly for best results)

2) You need to store the location's latitude and longitude along with the user. If you don't already have it from a sensor lookup or Geo IP database, you will need to do a geocode lookup on the address. You asked not to use a third party service, but there really isn't a way around it (that's why the services exist; rolling your own is very complicated and expensive). See http://en.wikipedia.org/wiki/Geocoding#List_of_some_geocoding_systems for a list of geocoding services you can use.

// Google Maps Example
$address = "$line1, $city, $state $zip, $country";
$ch = curl_init();
$query = http_build_query(array(
    'oe' => 'utf8',
    'sensor' => 'false', // set this to 'true' if you used navigation.geolocation
    'key' => YOUR GMAPS API KEY HERE,
    'address' => $address
));
curl_setopt($ch, CURLOPT_URL, 'http://maps.google.com/maps/api/geocode/json?' . $query);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$latLong = current(end(json_decode(curl_exec($ch), true))); // let's pretend nothing ever goes wrong

3) You can now search users by calculating the distance from your search location to each user's location and putting a limit on it for the proximity. Example:

(reference: http://jehiah.cz/a/spatial-proximity-searching-using-latlongs)

$myLat = 45.5;
$myLong = -73.5833;
$range = 2; // miles
$sql = "SELECT *,
    truncate((degrees(acos(
        sin(radians(latitude))
        * sin( radians({$myLat}))
        + cos(radians(latitude))
        * cos( radians({$myLat}))
        * cos( radians(longitude - {$myLong}) ) 
        ) ) * 69.09),1) as distance
    FROM users
    HAVING distance < {$range}";
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜