Mapping lat/lon values with JavaScript
Googe Maps loads about 400 kByte for each visit to casastristes.org. Sometimes I prefer to implement a static map instead but still using latitude and longitude values for mapping the places. In the following example I show how to convert lat/lon values to x/y coordinates for the use on a static map.
This example shows the use of lat/lon to x/y mapping I’m going to explain step by step. To separate data from interface I use a JSON file where the lat/lon values are saved as following:
{
"label" : "Barcelona",
"type" : "vivienda",
"addressLatLng" : "41.409775832009565,2.197265625",
"homepage" : "http://bcn.vdevivienda.net"
},
Using plain JavaScript I get lat/lon values out of the file. Reading this article I found the solution for converting this values to x/y coordinates, I adapted the posted ActionScript to the following JavaScript function:
function getYcoord(myLat) {
radBtm = deg2rad(latS);
radPixel = deg2rad(myLat);
sinRadBtm = Math.sin(radBtm);
sinRadPixel = Math.sin(radPixel);
convHtBtm = rfactor * Math.log((1 + sinRadPixel)/(1 - sinRadPixel));
convHtPixel = rfactor * Math.log((1 + sinRadBtm)/(1 - sinRadBtm));
myTotHt = Math.abs(convHtPixel - convHtBtm);
myYcoord = Math.round(mapHeight - myTotHt, 3);
return myYcoord;
}
function getXcoord(myLon){
var longPix = mapWidth / (lonW – lonE);
return Math.round(((lonW – myLon)*longPix), 2);
}
That’s it. In a near future you can see it in action here.
Tags: casastristes, javascript, json, mapping