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.
Here is how I have done it.
For longitude:
For Latitude:
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
Leave a Reply