Skip to content

Instantly share code, notes, and snippets.

@aghull
Created August 21, 2012 17:31
Show Gist options
  • Save aghull/3417584 to your computer and use it in GitHub Desktop.
Save aghull/3417584 to your computer and use it in GitHub Desktop.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<div id="map" style="position:relative">
<img src="http://maps.googleapis.com/maps/api/staticmap?center=40.714728,-73.998672&zoom=2&scale=2&size=640x400&maptype=roadmap&markers=color:blue%7Clabel:S%7C40.714728,-76.211794&markers=color:green%7Clabel:G%7C42.922217,-76.211794&markers=color:red%7Ccolor:red%7Clabel:C%7C42.922217,-73.998672&sensor=false">
</div>
<script>
mapToCoord(42.922217,-73.998672, 40.714728, -73.998672, 6, 2, 640, 400, 'red');
mapToCoord(40.714728,-76.2117944, 40.714728, -73.998672, 6, 2, 640, 400, 'blue');
mapToCoord(42.922217,-76.211794, 40.714728, -73.998672, 6, 2, 640, 400, 'green');
/**
* returns relative x and y of a lat-long pair for a static map
* lat,long (desired point)
* clat, clong (map center)
* zoom, scale, w, h (static map dimensions)
*/
function latLongToCoord(lat, lng, clat, clng, zoom, scale, w, h) {
var center = mercator(clat, clng);
var point = mercator(lat, lng);
var x = center[0] - point[0];
var y = center[1] - point[1];
zoom = 256/360 * Math.pow(2, zoom) * scale;
return [x * zoom, y * zoom]
}
// translate spherical mercator projections
function mercator(lat, lng) {
lat *= Math.PI / 180;
lat = Math.log((Math.sin(lat) + 1.0) / Math.cos(lat));
lat *= 180 / Math.PI;
return [lng, lat];
}
function inverseMercator(lng, lat) {
lat *= Math.PI / 180;
lat = 2 * Math.atan(Math.exp(lat)) - Math.PI / 2;
lat *= 180 / Math.PI;
return [lat, lng];
}
function mapToCoord(lat, lng, clat, clng, zoom, scale, w, h, col) {
xy = latLongToCoord(lat, lng, clat, clng, zoom, scale, w, h);
$('#map').append('<div id="sq" style="z-index:10; position:absolute; border:1px solid '+col+'; border-width: 1px 0 0 1px; width:10px; height:10px; left:'+Math.round(w*scale/2-xy[0])+'px; top:'+Math.round(h*scale/2+xy[1])+'px;">');
}
/**
* takes an array of lat-long pairs and returns the lat-long that
* is the center of the minimum bounding rectangle (MBR) for the entire
* set, given a spherical mercator projection
*/
function centerOfMap(coords) {
var lats = $.map(coords, function(c) { return mercator(c[0], c[1])[1] });
var longs = $.map(coords, function(c) { return c[1] }).sort(function(a,b) { return a-b })
var centerLat = inverseMercator(0, 0.5 * (Math.max.apply(Math, lats) + Math.min.apply(Math, lats)))[0];
var centerLong = 0, minGap = 0;
$.each(longs, function(i, lng) {
var gap = lng - (i>0?longs[i-1]:longs[longs.length-1]-360);
if (gap > minGap) {
minGap = gap;
centerLong = 180 + lng - gap/2;
}
});
return [centerLat, centerLong];
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment