Latitude and Longitude Distance Formula

What I want to do is to expand the bounds of a google maps by a certain distance. This is because I want to include markers that are outside the bounds of the map since they have overlays attached to them which will overlap onto the current map bounds.
For example if I am currently viewing the green area on the map below I want to include all markers in the red area.
Therefore after getting the bounds from google maps I need to extend the bounds by a certain distance to get a new set of bounds.
map
Here is how I have done it.

For longitude:

ll5

ll6

ll7

For Latitude:

ll1

ll2

ll3

ll4

The Javascript


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
    // returns latlng of new coordinate which is dist from the longitude given
    function lngDistance(lat1, lng1, dist) {
        var R = 6371000; // m
        lat1 = deg2rad(lat1);
        lng1 = deg2rad(lng1);
        var lng2 = (R*lng1*Math.cos(lat1)-dist)/(R*Math.cos(lat1));
        return(rad2lng(lng2));
    }

    // returns latlng of new coordinate which is dist from the latitude given
    function latDistance(lat1, dist) {
        var R = 6371000; // m
        var lat1 = deg2rad(lat1);
        var lat2 = (R*lat1-dist)/R;
        return(rad2lat(lat2));
    }

    function extendBounds(bounds,dist) {
        var latNE = bounds.getNorthEast().lat();
        var lngNE = bounds.getNorthEast().lng();
       
        var latSW = bounds.getSouthWest().lat();
        var lngSW = bounds.getSouthWest().lng();
        var latlngNE = new google.maps.LatLng(latDistance(latNE, -dist), lngDistance(latNE,lngNE, -dist));
        var latlngSW = new google.maps.LatLng(latDistance(latSW, dist), lngDistance(latSW, lngSW, dist));
        return (new google.maps.LatLngBounds(latlngSW, latlngNE));
    }

Not that I correct latlngs using the rad2lat and rad2lng functions given in my post converting radians in degrees latitude and longitude

Share


Leave a Reply

Your email address will not be published. Required fields are marked *

Captcha: * Time limit is exhausted. Please reload CAPTCHA.

Subscribe