Skip to content

Instantly share code, notes, and snippets.

@robwilkerson
Created November 29, 2011 15:35

Revisions

  1. robwilkerson created this gist Nov 29, 2011.
    52 changes: 52 additions & 0 deletions location.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,52 @@
    /**
    * Computes the distance in miles between two sets of coordinates.
    *
    * @param object from object containing longitude and latitude members
    * @param object to object containing longitude and latitude members
    * @return number
    */
    exports.distance = function( from, to ) {
    // approx. dist in miles, nothern hemisphere
    // http://www.meridianworlddata.com/Distance-Calculation.asp
    try {
    return Math.sqrt( Math.pow( 69.1 * ( to.latitude - from.latitude ), 2 ) + Math.pow( 53 * ( to.longitude - from.longitude ), 2 ) );
    }
    catch( e ) {
    throw( e );
    }
    };

    /**
    * Calculates the region for a mapView so that all points are dislayed.
    *
    * @param array points An array of objects with long/lat properties.
    * Essentially, stripped down annotation objects.
    * @return object a region object
    */
    exports.region = function( points ) {
    var region = {};
    var delta = 0.02;
    var minLat = points[0].latitude,
    maxLat = points[0].latitude,
    minLon = points[0].longitude,
    maxLon = points[0].longitude;

    for( var i = 0; i < points.length - 1; i++ ) {
    minLat = Math.min( points[i + 1].latitude, minLat );
    maxLat = Math.max( points[i + 1].latitude, maxLat );
    minLon = Math.min( points[i + 1].longitude, minLon );
    maxLon = Math.max( points[i + 1].longitude, maxLon );
    }

    // Define the zoom level
    var deltaLat = maxLat - minLat;
    var deltaLon = maxLon - minLon;
    delta = Math.max( deltaLat, deltaLon ) * 0.25;


    region.latitude = maxLat - parseFloat( ( maxLat - minLat ) / 2 );
    region.longitude = maxLon - parseFloat( ( maxLon - minLon ) / 2 );
    region.latitudeDelta = region.longitudeDelta = delta;

    return region;
    };