BaronGrivet
BaronGrivet

Reputation: 4424

How to find the bounds of a list of latitude/longitude co-ordinates in PHP?

I have longitude, latitude route data stored as a plain text list:

172.99521511611377,-41.075469325375181 172.99502480979655,-41.075498182938091 172.99437640866088,-41.075994938345403 172.99216264025972,-41.075945177006659 172.98367077599619,-41.075680790034014 172.98193973070761,-41.075629002582779 172.98184988590305,-41.077284049303138 172.98166597246177,-41.08077655741176 172.98154383897847,-41.082936806274091 172.98133830282006,-41.086519043880244

etc. etc.

I want to get the bounds of the route - which would involve finding the lowest/highest values for longitude and latitude.

What would be the best method to achieve this?

Upvotes: 1

Views: 189

Answers (2)

BaronGrivet
BaronGrivet

Reputation: 4424

This is my crack at it:

/* Set bound limits */
$BoundNELng = 180;
$BoundNELat = -90;
$BoundSWLng = -180;
$BoundSWLat = 90;

/* Split data into pairs by whitespace */
$LongitudeLatitudePairs = preg_split('/[\s]+/', $RawLatLong );

/* Cycle through each pair */
foreach($LongitudeLatitudePairs as $LongitudeLatitudePair){      
  /* Split each pair into longitude/latitude */
  $LongitudeLatitudePairData = explode(',', $LongitudeLatitudePair);

  /* Check we have a pair of values */
  if( isset($LongitudeLatitudePairData[1])){
    $PairLongitude = (float) $LongitudeLatitudePairData[0];
    $PairLatitude = (float) $LongitudeLatitudePairData[1];

    /* If pair is outside of bounds, move bounds outwards */
    $BoundNELng = ($PairLongitude < $BoundNELng) ? $PairLongitude : $BoundNELng;
    $BoundNELat = ($PairLatitude > $BoundNELat) ? $PairLatitude : $BoundNELat;

    $BoundSWLng = ($PairLongitude > $BoundSWLng) ? $PairLongitude : $BoundSWLng;
    $BoundSWLat = ($PairLatitude < $BoundSWLat) ? $PairLatitude : $BoundSWLat;
  }

}

Upvotes: 0

Semicolons and Duct Tape
Semicolons and Duct Tape

Reputation: 3136

to get the routes bounding box do the following:

  1. read the data into 2 seperate lists 1 for longitude and 1 for latitiude (this should be straightforward since you have a well ordered text file)
  2. sort each list individually from smallest to largest values
  3. The 1st and last entries in the sorted longitude list are the west most and east most line of your bounding box respectively. The 1st and last entries in you latitude lists are the South most and north most lines of your bounding box respectively

Upvotes: 2

Related Questions