1

I managed to find a function which gave me NE corner et SW corner coordinates given a latLng and a radius.

/**
 * Get NE & SW coordinates around a point
 * 
 * @param $lat float latitude of origin pt
 * @param $lng float longitude of origin pt
 * @param $distance int radius in km
 * 
 */
function getBoundsCoords($latitude, $longitude, $distance) {
    $radius = 6378.1;

    $neLat = rad2deg(asin(sin(deg2rad($latitude)) * cos($distance / $radius) + cos(deg2rad($latitude)) * sin($distance / $radius) * cos(deg2rad(0))));
    $swLat = rad2deg(asin(sin(deg2rad($latitude)) * cos($distance / $radius) + cos(deg2rad($latitude)) * sin($distance / $radius) * cos(deg2rad(180))));
    $neLng = rad2deg(deg2rad($longitude) + atan2(sin(deg2rad(90)) * sin($distance / $radius) * cos(deg2rad($latitude)), cos($distance / $radius) - sin(deg2rad($latitude)) * sin(deg2rad($neLat))));
    $swLng = rad2deg(deg2rad($longitude) + atan2(sin(deg2rad(270)) * sin($distance / $radius) * cos(deg2rad($latitude)), cos($distance / $radius) - sin(deg2rad($latitude)) * sin(deg2rad($neLat))));

    return array(
        'ne' => array(
            'lat' => $neLat,
            'lng' => $neLng
        ),
        'sw' => array(
            'lat' => $swLat,
            'lng' => $swLng
        )
    );
}

I also managed to find part of the opposite function wich gives me back the center point coordinates (quite easily) but I'm not able to find the radius back:

function getCoordsFromBounds($coordsNeSw) {
    return array(
        'lat' => ($coordsNeSw['ne']['lat'] + $coordsNeSw['sw']['lat']) / 2,    
        'lng' => ($coordsNeSw['ne']['lng'] + $coordsNeSw['sw']['lng']) / 2,
        'radius' => "??????"
    );
}

I suspect I should just do the opposite of getBoundsCoords() function but I'm not so comfortable with sin/cos/deg/rad...

Axi
  • 1,534
  • 15
  • 20
  • When you say "from NE SW area" do you mean you are given sq miles, or that you are given the NE and SW coordinates and you need the radius based on that? – Rabbit Guy Oct 13 '15 at 15:57
  • NE and SW coordinates are given and I'm looking for radius based on that – Axi Oct 13 '15 at 16:06

1 Answers1

1

Assuming your getCoordsFromBounds only applies to squares, not rectangles, the radius would be half the distance between the two latitudes or longitude. Latitude difference is easier to calculate than longitude. Distance based on latitude is nearly constant at 111 km/degree (varies slightly from pole to equator)

so the distance between the top and bottom of your square is (in km)

$distance = abs(($coordsNeSw['ne']['lat'] - $coordsNeSw['sw']['lat'])) * 111

thus the radius is half that

$radius = $distance / 2

I think your solution for calculating the bounding box seems more complicated than it need be, see Calculating bounding box a certain distance away from a lat/long coordinate in Java

Community
  • 1
  • 1
John Price
  • 166
  • 1
  • 5