Skip to content

Instantly share code, notes, and snippets.

@Oobert
Created October 28, 2014 18:41
Show Gist options
  • Save Oobert/0f3f3f28c02b473ab651 to your computer and use it in GitHub Desktop.
Save Oobert/0f3f3f28c02b473ab651 to your computer and use it in GitHub Desktop.
Lat/Long to x,y and x,y and Lat/Long
function Adjust(X,Y,x,y,z,w)
{
var offset=268435456; //(half of the earth circumference's in pixels at zoom level 21)
var radius=offset/Math.PI;
function LToX(x)
{
return Math.round(offset+radius*x*Math.PI/180);
}
function LToY(y)
{
return Math.round(offset-radius*Math.log((1+Math.sin(y*Math.PI/180))/(1-Math.sin(y*Math.PI/180)))/2);
}
function XToL(x)
{
return ((Math.round(x)-offset)/radius)*180/Math.PI;
}
function YToL(y)
{
return (Math.PI/2-2*Math.atan(Math.exp((Math.round(y)-offset)/radius)))*180/Math.PI;
}
if (w)
{
return {x:(LToX(X)-LToX(x))>>(21-z),y:(LToY(Y)-LToY(y))>>(21-z)};
}
else
{
return {x:XToL(LToX(x)+(X<<(21-z))),y:YToL(LToY(y)+(Y<<(21-z)))};
}
}//function Adjust
function XYToLL(X,Y,x,y,z){return Adjust(X,Y,x,y,z,0)}
// X = X pixel offset of new map center from old map center
// Y = Y pixel offset of new map center from old map center
// x = Longitude of map center
// y = Latitude of map center
// z = Zoom level
// result.x = Longitude of adjusted map center
// result.y = Latitude of adjusted map center
function LLToXY(X,Y,x,y,z){return Adjust(X,Y,x,y,z,1)}
// X = Longitude of marker center
// Y = Latitude of marker center
// x = Longitude of map center
// y = Latitude of map center
// z = Zoom level
// result.x = X pixel offset of marker center from map center
// result.y = Y pixel offset of marker center from map center
function get_coordinates(event, show_coordinates_div_id){
//make the array that the result will be held in
var array_result = new Array();
//determine the x&y coordinates of the mouse cursor
array_result['x'] = event.offsetX?(event.offsetX):event.pageX-document.getElementById('static_map_id').offsetLeft;
array_result['y'] = event.offsetY?(event.offsetY):event.pageY-document.getElementById('static_map_id').offsetTop;
//calulate the center values for the maps' x & y coordinates
var old_map_center_x = 250;
var old_map_center_y = 250;
//calculate the latitude and longitude
var result = XYToLL((array_result['x'] - old_map_center_x),(array_result['y'] - old_map_center_y),-88.1160419,42.9520781,17);
//save the longitude and latitude
array_result['longitude'] = result.x;
array_result['latitude'] = result.y;
//do we have the div id to update?
if(show_coordinates_div_id){
//update the div
document.getElementById(show_coordinates_div_id).innerHTML='x='+ array_result['x']+'|y='+array_result['y']+'|latitude='+array_result['latitude']+'|longitude='+array_result['longitude'];
}//if
return array_result;
}//function get_coordinates()
-->
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment