NYCPHP Meetup

NYPHP.org

[nycphp-talk] Getting Closure - on PHP Closures and 5.3

Edward Potter edwardpotter at gmail.com
Fri Jul 16 20:29:34 EDT 2010


>>> Given an array of businesses with latitude/longitude coordinates, and the user's location, sort the array of businesses by closest to the user.

A slight language digression:

Oh my, if you saw how easy that was to do on an iPhone in ObjC
(hundreds of locations). And then visualize it all on a google map
with a detail view of everyone of those locations. With data updated
in real-time. With a 5,000 mile server round trip. And do it all in a
blink of the eye.
(plus you get to talk to 4 orbiting satellites at the same time).  Yummy! :-)

Code in action here: (dropping, sorted pins by user location 1/2 way through).
http://www.youtube.com/watch?v=krF9IUyF3Rw


On Fri, Jul 16, 2010 at 4:36 PM, John Campbell <jcampbell1 at gmail.com> wrote:
> On Fri, Jul 16, 2010 at 2:48 PM, Hans Zaunere <lists at zaunere.com> wrote:
>> Closures - great for Javascript, but for PHP?  In a non-callback-centric
>> synchronous language such as PHP, what else can we use this "syntactic
>> sugar" for?  How are people using them and what can we gain from them?  And,
>> the hell with code reuse?
>
> I have a favorite problem, that is hard/ugly to solve without closures:
>
> Given an array of businesses with latitude/longitude coordinates, and
> the user's location, sort the array of businesses by closest to the
> user.
>
> so you have:
>
> $stores = array(
>  array('name' => 'Pet Smart', 'lat'=>24.12, 'lon' => 54.23),
>  array('name' => 'Cats and Critter', 'lat'=>24.19, 'lon' => 54.32),
>  array('name' => 'Snakes and such', 'lat'=>24.45, 'lon' => 53.35),
>  array('name' => 'Lots of llams', 'lat'=>24.46, 'lon' => 54.97));
>
> $user_location = array('lat'=> 24.45, 'lon' => 54.96);
>
> // Solution using closures
>
> // geo sort.
> function sort_by_closest(&$points,$location) {
>  usort($points, function($a,$b) use($location) {
>    return distance($a,$location) > distance($b,$location);
>  });
> }
>
> // geo distance using sperical law of cosines.
> function distance($a,$b) {
>        $R = 6371; // km
>        $d2r = pi() / 180;
>        return acos(sin($a['lat']*$d2r)*sin($b['lat']*$d2r) +
>                          cos($a['lat']*$d2r)*cos($b['lat']*$d2r) *
>                          cos($b['lon']*$d2r-$a['lon']*$d2r)) * $R;
> }
>
> print_r($stores);
> sort_by_closest($stores,$user_location);
> print_r($stores);
>
>
> -John
> _______________________________________________
> New York PHP Users Group Community Talk Mailing List
> http://lists.nyphp.org/mailman/listinfo/talk
>
> http://www.nyphp.org/Show-Participation
>



-- 
IM/iChat: ejpusa
Links: http://del.icio.us/ejpusa
Follow me: http://www.twitter.com/ejpusa
Karma: http://www.coderswithconscience.com



More information about the talk mailing list