Draw a Box Around a Coordinate In Google Maps Based on Miles or Kilometers

Attached File(s): 

This post explains how, given latitude and longitude coordinates in Google Maps (specifically, in the Static API), how one can draw a bounding box around them, based on a distance in either miles or kilometers.

gmap_bounding.pngLet's say you already know the lat/long of a particular point on the map, and now you want to draw a box around it, or maybe you just need to know the lat/long coordinates of another point, so many km or miles away?  Well, this is the script for you!

Based on a script retrieved from here:
http://www.sitepoint.com/forums/showthread.php?656315-adding-distance-gps-coordinates-get-bounding-box

The trick is that Google Maps wants you to provide it with the lat/long coordinates for each corner of the box.  After several hours of searching, I finally found a script which I was able to modify to give me what I needed.

Simply download the script linked at the top of the page, and then use the following code to create the image you see here. 

Enjoy!


    $lat = -33.872986011907216;
    $lng = 150.90904516601563;

    // Create the static map api image.
    $static_maps_url = "http://maps.googleapis.com/maps/api/staticmap";
    $static_maps_url .= "?center=$lat,$lng";
    $static_maps_url .= "&zoom=15";
    $static_maps_url .= "&size=300x300";
    $static_maps_url .= "&maptype=roadmap";
    $static_maps_url .= "&sensor=false";
    $static_maps_url .= "&markers=color:blue|$lat,$lng";

    // Figure out the corners of a box surrounding our lat/lng.
    $d = 0.3;  // distance
    $path_top_right = bpot_getDueCoords($lat, $lng, 45, $d);
    $path_bottom_right = bpot_getDueCoords($lat, $lng, 135, $d);
    $path_bottom_left = bpot_getDueCoords($lat, $lng, 225, $d);
    $path_top_left = bpot_getDueCoords($lat, $lng, 315, $d);
   
    $static_maps_url .= "&path=color:334433|weight:5|fillcolor:0xFFFF0033|";
    $static_maps_url .= "$path_top_left|$path_top_right|$path_bottom_right|";
    $static_maps_url .= "$path_bottom_left|$path_top_left";
     
    // Now, draw the image from Google Maps API!
    print "<img src='$static_maps_url'>";


 

 


Software License Fine Print

Creative Commons LicenseThis code is licensed as-is, with no warranty or guarantee, under a Creative Commons Attribution 3.0 Unported License.

You may use this code however you want, even in commercial products, but only if you include attribution to me, Richard Peacock, as the original author of this small portion of code, but not in a way that implies I endorse your project.

For example, on a Help/Credits screen:  Portions of this project were based on work freely obtained from these developers: Richard Peacock (http://richardpeacock.com), NAME HERE, etc.  These outside developers neither endorse nor support this software.

If you use this code, feel free to email me to let me know!  I'll include a link to your project here.