Google Maps API setBounds to exact coordinates - javascript

In the Google Maps API it allows you to set the bounds of a map given a list of coordinates. That's awesome. My issue is that it gives a little bit of breathing room on the sides. I'm trying to get the bounding box I'm looking at to be barely containing the bounds.
For example, I want to view California so I set the bounds to be the Northeast and Southwest corners. Instead of showing just California though, I get all of Oregon and half of Mexico.
Here's what I'm currently doing:
var geo_region = {
northeast: {
lat: 42.0095169
lng: -114.131211
}
southwest: {
lat: 32.528832
lng: -124.482003
}
}
var map_bounds = new google.maps.LatLngBounds();
map_bounds.extend(new google.maps.LatLng(geo_region.northeast.lat, geo_region.northeast.lng));
map_bounds.extend(new google.maps.LatLng(geo_region.southwest.lat, geo_region.southwest.lng));
var plot_map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
plot_map.fitBounds(map_bounds);
EDIT:
A clearer example might be Wyoming since it's such a nice rectangle. If my map dimensions are the same ratio as Wyoming, I only want it to show me Wyoming.
EDIT:
Somebody suggested that I offset the bounds manually so I grabbed some data on the offsets that Google is using but I can't figure out what their formula is for deciding those offsets so I'm a long ways away from being able to do that. I even used the viewport coordinates from Google's Geocoding API but those didn't help much either.
Here's my data: https://docs.google.com/a/dovidev.com/spreadsheets/d/1HZLdDt5uiGwEtY0NbX0pfkmYVuUDndptm_-kzq0vh_w/edit?usp=sharing

This cannot be done EXACTLY because of the way google's zoom level's work. Google sets the bounds of the area but zooms in as closely as possible without cutting anything out. Because the zoom levels are incremental and their increments are so large, this often means that you'll end up with a lot of extra space.
When I tried to zoom in even once from what I thought was grossly oversized, I found that parts of the bounds had been cut off.
And thus we see that Google is already getting it as tight as it can be.

Related

Set zoom level of google map based on different lat and long

I have different sites drawn on google map(basically polygon/circle). A site can be anywhere in the world on google map. I have center lat and long of sites(polygon/circle) in an array and I want to set the zoom level of the map so that all the sites can be seen in one view.
For e.g. if there is only one site to display in map, zoom level should be more.
Please help me in this. I am looking for javascript code.
try this hint
var latlngBounds = new google.maps.LatLngBounds();
array of latlng object;
for(i=0;i<array.length;i++){
latlngBounds.extend(array[i]);
}
map.fitBounds(latlngBounds);

Exclude overlaid element from Google Maps viewport bounds

I am using Google Maps API v3 to create an inline map on a website. In its container element, I also have an absolute positioned overlay which shows some detail information, visually hovering over the map. Determining on context this element may grow up to the size of the entire map element.
All this is working fine, however the Maps instance of course still considers the overlaid part of the map a valid usable part of the map. This means that, especially if the overlay is at maximum height, setCenter doesn't focus on the visible center, and routes drawn with DirectionsRenderer are partially underneath the overlay.
See this image:
Is there a way to limit the actual viewport to the blueish area, so that setCenter centers on the arrow tip and setBounds fits to the blue part?
I have managed to implement an acceptably functional workaround for the time being.
Some general notes which are good to know:
Every Map object has a Projection, which can convert between LatLng points to map points.
The map points a Projection uses for calculation are in 'world' coordinates, meaning they are pixels on the world map at zoom level 0.
Every zoom level exactly doubles the number of pixels shown. This means that the number of pixels in a given map point equals 2 ^ zoom.
The samples below assume a 300px wide sidebar on the right - adapting to other borders should be easy.
Centering
Using this knowledge, it becomes trivial to write a custom function for off-center centering:
function setCenter(latlng)
{
var z = Math.pow(2, map.getZoom());
var pnt = map.getProjection().fromLatLngToPoint(latlng);
map.setCenter(map.getProjection().fromPointToLatLng(
new google.maps.Point(pnt.x + 150/z, pnt.y)));
}
The crucial bits here are the z variable, and the pnt.x + 150/z calculation in the final line. Because of the above assumptions, this moves the point to center on 150 pixels to the left for the current zoom level, and as such compensates for the missing 300 pixels on the right sidebar.
Bounding
The bounds issue is far less trivial. The reason for this is that to offset the points correctly, you need to know the zoom level. For recentering this doesn't change, but for fitting to previously unknown bounds it nearly always will. Since Google Maps uses unknown margins itself internally when fitting to bounds, there is no reliable way to predict the required zoom level.
Thus a possible solution is to invoke a two-step rocket. First off, call fitBounds with the entire map. This should make the bounds and zoom level at least nearly correct. Then right after that, do a second call to fitBounds corrected for the sidebar.
The following sample implementation should be called with a LatLngBounds object as parameter, or no parameters to default to the current bounds.
function setBounds(bnd, cb)
{
var prj = map.getProjection();
if(!bnd) bnd = map.getBounds();
var ne = prj.fromLatLngToPoint(bnd.getNorthEast()),
sw = prj.fromLatLngToPoint(bnd.getSouthWest());
if(cb) ne.x += (300 / Math.pow(2, map.getZoom()));
else google.maps.event.addListenerOnce(map,'bounds_changed',
function(){setBounds(bnd,1)});
map.fitBounds(new google.maps.LatLngBounds(
prj.fromPointToLatLng(sw), prj.fromPointToLatLng(ne)));
}
What we do here at first is get the actual points of the bounds, and since cb isn't set we install a once-only event on bounds_changed, which is then fired after the fitBounds is completed. This means that the function is automatically called a second time, after the zoom has been corrected. The second invocation, with cb=1, then offsets the box to correct for the 300 pixel wide sidebar.
In certain cases, this can lead to a slight off-animation, but in practice I've only seen this occur when really spamclicking on buttons causing a fit operation. It's running perfectly well otherwise.
Hope this helps someone :)
You can use the map panBy() method which allows you to change the center of the map by a given distance in pixels.
Hope this helps!
I had a similar need and ended up just forcing some "padding" to the east of a LatLngBounds object.
On the upside, it's simple and it works. On the downside it's not really versatile. Just a quick little hack.
// start with a standard LatLngBounds object, extending as you usually would...
bounds = new google.maps.LatLngBounds();
// ...
ne = bounds.getNorthEast();
sw = bounds.getSouthWest();
// the multiplier used to add space; positive for east, negative for west
lngPadding = 1.5
extendedLng = ne.lng() + (ne.lng() - sw.lng()) * lngPadding;
// copy original and extend with the new Lng
extendedBounds = bounds;
extendedBounds.extend(new google.maps.LatLng(ne.lat(), extendedLng));
map.fitBounds(extendedBounds);

Getting proper map boundaries

I use the simple:
var ne = gMap.getBounds().getNorthEast(),sw = gMap.getBounds().getSouthWest();
to get the lat long of the boundaries of a map
It works fine when the map is like this:
But when the map is like this:
The North-East lat long comes as something like 63.821287740550275, -179.73632762500006. Which creates a problem because this lat long is almost same as the South-West resulting in no-area between them.
Is there a way to get the desired values, something like a maximum value if it crosses the line.
If you refer to this question: Get non-wrapping map bounds in Google Maps API V3
You'll see that as you have stated the map obviously wraps on the date line, so that as you zoom out you don't end up with blank areas at the edges and so that you scroll off the edge of china and hit America etc.
If you examine the answers you will see that you need to check for this wrap and go from there. And interesting question that I had never really considered!

Algorithm Mid Point between different GPoint

I have to show several brands on my google maps, one can be a very distant from the other, How i can calculate the point where i center my map, anyone can give me tips to do this, thanks
You can use the fitBounds method to help you show all items on the map at the correct zoom level:
var bounds = new google.maps.LatLngBounds();
//you can run this in a loop for all points/markers
bounds.extend(markerLatLng);
//finally
map.fitBounds(bounds);

Openlayer Projection

I want to zoom to a particular house in the google mapS, but when I provide its bounds and lattitude and longitude, it does not show images as well as the particular house. Can anyone provide the solution for this?
Solution would be probably to transporm coordinates first. Unfortunately when You pass coordinates to OpanLayers.LonLat(lon,lat) it is supposed to be WGS:84, while OpenLayer.Bounds() needs coordinates given in EPSG:900913.
You should then use Proj4js.transform and pass transformed coordintes in EPSG:900913
You can transform it like this one:
var map = new OpenLayers.Map('map');
var location.transform(map.getProjectionObject(), new OpenLayers.Projection("EPSG:900913"));

Categories

Resources