Learnt By Me - Summing up everything I've learned

 
Javascript Developer

LatLng to Div pixel conversion Converting Latitude and Longitude to the corresponding X,Y coordinate of any element using pure JS.

Due to the easy availability of geo-location information these days, there is a certain need to customize data according to location of the visiting users and in many projects we often encounter problems which needs working with latLng values which point a location in the map.

Ok, so why do we need LatLng to Div conversion ?

Imagine you are developing a site where you need to show all the branches of the client in a custom map . You only have the latLng values of the branches, how will you plot them on to your custom map ?

There are two possible ways:
  1. You can use Google Maps Javascript API to create a custom layer and get the pixel value of the latLng
  2. you can use a simple JavaScript calculation (which I will explain in-detail) to convert LatLng values into your div Pixel.
of these the latter is the most simplest solution, which I will elaborate now . I will explain the later solution (Google Maps JavaScript API) in a different article.

Demo

Google maps has been placed behind with two markers as a proof of the technique.

Note:The Blue dots are placed using JavaScript calculation and the markers are a part of the google maps API. The whole idea is to demonstrate the conversion of latLng into its corresponding pixel values for use in custom maps.

Google maps has nothing to do with the calculation, its included for demo just as a background map.

The Logic behind

function YLatToPixel(lat,elem){

var containerHeight=$(elem).height();
/*
Formula
(givenLat*heightOfContainerElement)/180
where 360 is the total longitude in degrees
Height is calculated from the bottom
*/

lat+=90;
var calculatedHeight=((lat*containerHeight)/180);
return $(elem).offset().top+($(elem).height()-calculatedHeight);

}

function XLngToPixel(lng,elem){

//Formula
/*
(givenLng*widthOfContainerElement)/360
where 360 is the total longitude in degrees
*/
var containerWidth=($(elem).width());
lng=lng+180;
return $(elem).offset().left+((lng*containerWidth)/360);

}
Implementation Assigning top and left values to the "#dot" element using pure JS LatLng to pixel calculation $('#dot').css('top', YLatToPixel(-34 , $('#map_canvas')))
$('#dot').css('left', XLngToPixel(150,$('#map_canvas'))+'px');

repeating the procedure for the second element $('#dot_ch').css('top', YLatToPixel(13, $('#map_canvas')))
$('#dot_ch').css('left', XLngToPixel(80,$('#map_canvas'))+'px');