How to affect the "grace margin" of map.fitBounds() - google-maps

In Google maps API v2, map of our country was nicely fitted to 700x400px map with the following:
map.getBoundsZoomLevel(<bounds of our country>)
But in API v3, the map.fitBounds() method doesn't fit it at that zoom level to 700x400 - it zooms out one level.
This means that map.fitBounds() counts with some "grace margin" or something.
How can I affect the size of this margin?

Here's a solution that will zoom into the map as far as possible without a custom margin. You should be able to adapt it to account for some margin if you want to.
My solution is based on this comment in a Google Groups thread. Unfortunately, the call to helper.getProjection() always returned undefined, so I adapted the above answer a bit and came up with this working code.
Just replace your existing calls to map.fitBounds(bounds) with myFitBounds(map, bounds):
function myFitBounds(myMap, bounds) {
myMap.fitBounds(bounds);
var overlayHelper = new google.maps.OverlayView();
overlayHelper.draw = function () {
if (!this.ready) {
var projection = this.getProjection(),
zoom = getExtraZoom(projection, bounds, myMap.getBounds());
if (zoom > 0) {
myMap.setZoom(myMap.getZoom() + zoom);
}
this.ready = true;
google.maps.event.trigger(this, 'ready');
}
};
overlayHelper.setMap(myMap);
}
// LatLngBounds b1, b2 -> zoom increment
function getExtraZoom(projection, expectedBounds, actualBounds) {
var expectedSize = getSizeInPixels(projection, expectedBounds),
actualSize = getSizeInPixels(projection, actualBounds);
if (Math.floor(expectedSize.x) == 0 || Math.floor(expectedSize.y) == 0) {
return 0;
}
var qx = actualSize.x / expectedSize.x;
var qy = actualSize.y / expectedSize.y;
var min = Math.min(qx, qy);
if (min < 1) {
return 0;
}
return Math.floor(Math.log(min) / Math.log(2) /* = log2(min) */);
}
// LatLngBounds bnds -> height and width as a Point
function getSizeInPixels(projection, bounds) {
var sw = projection.fromLatLngToContainerPixel(bounds.getSouthWest());
var ne = projection.fromLatLngToContainerPixel(bounds.getNorthEast());
return new google.maps.Point(Math.abs(sw.y - ne.y), Math.abs(sw.x - ne.x));
}

Now, the method fitBounds has a second parameter that represents the size of the padding. For those who want to remove it, you just need to pass 0.
Map.map.fitBounds(bounds, 0);
New method signature: fitBounds(bounds:LatLngBounds|LatLngBoundsLiteral, padding?:number)

Related

Error when restricting zoom levels using MarkerClusterer in Google Maps API v3

I'm using code found here: Integrating Spiderfier JS into markerClusterer V3 to explode multi-markers with exact same long / lat to restrict zoom levels when clicking on MarkerClusterer created clusters containing points at the same location.
Live example is here:
http://www.adultlearnersfestival.com/newsite/yourarea/map.html
I'm getting an error in Firebug however:
Error: TypeError: markers is undefined
and can't work out what's causing it. The specific code is:
var minClusterZoom = 14;
mc.setMaxZoom(minClusterZoom);
gm.event.addListener(mc, 'clusterclick', function(cluster) {
map.fitBounds(cluster.getBounds()); // Fit the bounds of the cluster clicked on
if( map.getZoom() > minClusterZoom+1 ) // If zoomed in past 15 (first level without clustering), zoom out to 15
map.setZoom(minClusterZoom+1);
});
Any help much appreciated.
- Tom
I took a different approach suggested here: markerClusterer on click zoom and edited the MarkerClusterer source as follows
from this
/**
* Triggers the clusterclick event and zoom's if the option is set.
*/
ClusterIcon.prototype.triggerClusterClick = function() {
var markerClusterer = this.cluster_.getMarkerClusterer();
// Trigger the clusterclick event.
google.maps.event.trigger(markerClusterer, 'clusterclick', this.cluster_);
if (markerClusterer.isZoomOnClick()) {
// Zoom into the cluster.
this.map_.fitBounds(this.cluster_.getBounds());
}
};
to this
/**
* Triggers the clusterclick event and zoom's if the option is set.
*/
ClusterIcon.prototype.triggerClusterClick = function() {
var markerClusterer = this.cluster_.getMarkerClusterer();
// Trigger the clusterclick event.
google.maps.event.trigger(markerClusterer, 'clusterclick', this.cluster_);
if (markerClusterer.isZoomOnClick()) {
// Zoom into the cluster.
this.map_.fitBounds(this.cluster_.getBounds());
// modified zoom in function
if( this.map_.getZoom() > markerClusterer.getMaxZoom()+1 )
this.map_.setZoom(markerClusterer.getMaxZoom()+1);
}
};
Looks like an error in the MarkerClusterer to me. Inside this function in the for loop, markers is undefined, which means this.getMarkers() is returning undefined, looks to me like it is just wrong:
/**
* Returns the bounds of the cluster.
*
* #return {google.maps.LatLngBounds} the cluster bounds.
*/
Cluster.prototype.getBounds = function() {
var bounds = new google.maps.LatLngBounds(this.center_, this.center_);
var markers = this.getMarkers();
for (var i = 0, marker; marker = markers[i]; i++) {
bounds.extend(marker.getPosition());
}
return bounds;
};
probably should be something like (not tested):
/**
* Returns the bounds of the cluster.
*
* #return {google.maps.LatLngBounds} the cluster bounds.
*/
Cluster.prototype.getBounds = function() {
var bounds = new google.maps.LatLngBounds(this.center_, this.center_);
var markers = this.getMarkers();
if (markers && markers.length)
{
for (var i = 0; i < markers.length; i++) {
bounds.extend(markers[i].getPosition());
}
}
return bounds;
};
Works using MarkerClustererPlus
I solved the issue changing this:
Cluster.prototype.getBounds = function() {
var bounds = new google.maps.LatLngBounds(this.center_, this.center_);
var markers = this.getMarkers();
for (var i = 0, marker; marker = markers[i]; i++) {
bounds.extend(marker.getPosition());
}
return bounds;
};
to this:
Cluster.prototype.getBounds = function() {
var bounds = new google.maps.LatLngBounds(this.center_, this.center_);
var markers = this.getMarkers();
var minZoom =10
mc.setMaxZoom(minZoom);//The maximum zoom level that a marker can be part of a cluster
for (var i = 0; i < markers.length; i++) {
bounds.extend(marker.getPosition());//Extends this bounds to contain the given point.
}
if( map.getZoom() > minZoom+1 ){// If zoomed in past 11, the first level without clustering, zoom out to 11.
map.setZoom(minZoom+1);
}
return bounds;
};

Dynamic google map with custom tiles prevent repeating pan

I have a dynamic tile set where I do NOT want to allow panning outside of its bounds.
The below code gets me close, but the user can still scroll horizontally outside of strict bounds because it uses the map center for comparison
var strictBounds = new google.maps.LatLngBounds(
new google.maps.LatLng(sw_lat, sw_lon),
new google.maps.LatLng(ne_lat, ne_lon)
);
google.maps.event.addListener(map, 'drag', function()
{
if (strictBounds.contains(map.getCenter())) return;
// We're out of bounds - Move the map back within the bounds
var c = map.getCenter(),
x = c.lng(),
y = c.lat(),
maxX = strictBounds.getNorthEast().lng(),
maxY = strictBounds.getNorthEast().lat(),
minX = strictBounds.getSouthWest().lng(),
minY = strictBounds.getSouthWest().lat();
if (x < minX) x = minX;
if (x > maxX) x = maxX;
if (y < minY) y = minY;
if (y > maxY) y = maxY;
map.setCenter(new google.maps.LatLng(y, x));
});
For quick access, here is the jsfiddle for this solution: http://jsfiddle.net/nYz6k/
Supposed you're happy with the current solution of detecting bounds against the center, all you have to do is to restrict the bounds based on the current map canvas size.
The result that you're getting now is that every corner of the restricting bounds appears on the center of the map when it's full restricting (i.e. both latitude and longitude exceed the bounds corners).
The solution is to actually remove the x and y offset from the bounds, and still be able to check against the center (which is the most efficient solution, compared to other bounds-based checking solutions).
Also, you have to restrict the bounds only when you initialize the map and when the window is resizing, which means that when you pan there is no extra processing overhead besides the check method that you have already provided.
Don't forget to set the maxZoom property for the map (tweak it as needed) because above a determined zoom level the restricting bounds will by themselves fit in the viewport and there's no solution for that.
Important! Use 'center_changed' instead of 'drag' because 'drag' has that sliding behavior that when you finished dragging and set the center, the maps still slides in the direction of the panning.
Before you implement the solution I recommend you to check out how the Maps API coordinate system and projection works, because this solution is heavily based on it, and if you want to tweak it out, it's useful to know this information.
https://developers.google.com/maps/documentation/javascript/maptypes and check out the Custom Map Types -> Map Coordinates section.
Here's what you need to do. First, you need to implement 2 short methods of converting between geographic coordinates (LatLng) and pixel coordinates.
var fromLatLngToPixel = function (latLng) {
var point = map.getProjection().fromLatLngToPoint(latLng);
var zoom = map.getZoom();
return new google.maps.Point(
Math.floor(point.x * Math.pow(2, zoom)),
Math.floor(point.y * Math.pow(2, zoom))
);
}
var fromPixelToLatLng = function (pixel) {
var zoom = map.getZoom();
var point = new google.maps.Point(
pixel.x / Math.pow(2, zoom),
pixel.y / Math.pow(2, zoom)
);
return map.getProjection().fromPointToLatLng(point);
}
Next, implement the method that effectively restricts the bounds. Note that you always have to keep a variable that stores the original bounds, because each time the map canvas is resized, the resulting bounds will change.
For this, let's say originalBounds keeps the bounds you provided with sw_lat, sw_long etc, and shrinkedBounds is modified by this method. You can rename it to strictBounds to still work in your method, but it's up to you. This uses jQuery for getting the width and height of the canvas object.
var shrinkBounds = function () {
zoom = map.getZoom();
// The x and y offset will always be half the current map canvas
// width and height respectively
xoffset = $('#map_canvas').width() / 2;
yoffset = $('#map_canvas').height() / 2;
// Convert the bounds extremities to global pixel coordinates
var pixswOriginal = fromLatLngToPixel(originalBounds.getSouthWest());
var pixneOriginal = fromLatLngToPixel(originalBounds.getNorthEast());
// Shrink the original bounds with the x and y offset
var pixswShrinked = new google.maps.Point(pixswOriginal.x + xoffset, pixswOriginal.y - yoffset);
var pixneShrinked = new google.maps.Point(pixneOriginal.x - xoffset, pixneOriginal.y + yoffset);
// Rebuild the shrinkedBounds object with the modified
shrinkedBounds = new google.maps.LatLngBounds(
fromPixelToLatLng(pixswShrinked),
fromPixelToLatLng(pixneShrinked));
}
Next, all you have to do is to call this method:
once when the map is initialized. Be aware that depending on when you call the method, you may be getting some weird errors because the map might not have yet initialized all it's properties. Best way is to use the projection_changed event.
google.maps.event.addListener(map, 'projection_changed', function (e) {
shrinkBounds();
});
every time the map canvas is resized
google.maps.event.addListener(map, 'resize', function (e) {
shrinkBounds();
});
But the most important part of this is that the 'resize' event is never triggered for programmatic resizes of the map container, so you have to trigger it manually every time you resize the canvas programmatically (if you do, but I doubt you do).
The most common way is to trigger it when the window is resized:
$(window).resize(function () {
google.maps.event.trigger(map, 'resize');
});
After all of this, you can now safely use your method, but as a handler for 'center_changed' and not for 'drag' as I've mentioned earlier.
I set up a jsfiddle with the full working code.
http://jsfiddle.net/nYz6k/
You can see the restricting at the bottom left corner with that little half-marker that shows up, which is positioned in the SW corner of the bounds. There is also one at the NW corner but naturally you can't see it because it's displayed above the position.
Instead of using map.getCenter() as a check, use map.getBounds()
Untested, but a simple way to accomplish this would be to check if the union of both bounds were identical (if not, your map bounds is outside your strict bounds):
var union = strictBounds.union(map.getBounds());
if (strictBounds.equals(union)) { //new map bounds is within strict bounds
Tiborg version above is the best version so far in keeping the bounds...
I noticed a bug that occurs when zoom level and width/height are larger than original bounds
I have modified his code and added a rectangle to see it in action.
var buildBounds = function(sw, ne) {
var swY = sw.lat();
var swX = sw.lng();
var neY = ne.lat();
var neX = ne.lng();
if (swY > neY) {
var cY = (swY + neY) / 2;
swY = cY;
neY = cY;
}
if (swX > neX) {
var cX = (swX + neX) / 2;
swX = cX;
neX = cX;
}
return new google.maps.LatLngBounds(
new google.maps.LatLng(swY, swX),
new google.maps.LatLng(neY, neX));
}
http://jsfiddle.net/p4wgjs6s/

Box/Rectangle Draw Selection in Google Maps

I am working on Google Maps and want to implement a feature where a user can draw a box/rectangle using his/her mouse to select a region on map (like selecting multiple files in windows). Upon selection, I want to get all the markers that fall in the region. I have been looking around both Google Maps api and search but I am unable to find a solution. I tried using jQuery Selectable for selection but all it returns is a bunch of divs from which I am unable to determine if any marker is selected or not.
I found a Library keydragzoom (http://google-maps-utility-library-v3.googlecode.com/svn/tags/keydragzoom/1.0/docs/reference.html) and used it to draw a rectangle on the page.
Later, I edit the library and stopped it from zooming the selected area and instead made it return the correct co-ordinates in 'dragend' event. Then I manually looped through all the marker on the map to find the markers that are within that particular region. The library was not giving me the proper co-ordinates to I made the following changes.
Changed the DragZoom function to
var prj = null;
function DragZoom(map, opt_zoomOpts) {
var ov = new google.maps.OverlayView();
var me = this;
ov.onAdd = function () {
me.init_(map, opt_zoomOpts);
};
ov.draw = function () {
};
ov.onRemove = function () {
};
ov.setMap(map);
this.prjov_ = ov;
google.maps.event.addListener(map, 'idle', function () {
prj = ov.getProjection();
});
}
and DragZoom.prototype.onMouseUp_ function to
DragZoom.prototype.onMouseUp_ = function (e) {
this.mouseDown_ = false;
if (this.dragging_) {
var left = Math.min(this.startPt_.x, this.endPt_.x);
var top = Math.min(this.startPt_.y, this.endPt_.y);
var width = Math.abs(this.startPt_.x - this.endPt_.x);
var height = Math.abs(this.startPt_.y - this.endPt_.y);
var points={
top: top,
left: left,
bottom: top + height,
right: left + width
};
var prj = this.prjov_.getProjection();
// 2009-05-29: since V3 does not have fromContainerPixel,
//needs find offset here
var containerPos = getElementPosition(this.map_.getDiv());
var mapPanePos = getElementPosition(this.prjov_.getPanes().mapPane);
left = left + (containerPos.left - mapPanePos.left);
top = top + (containerPos.top - mapPanePos.top);
var sw = prj.fromDivPixelToLatLng(new google.maps.Point(left, top + height));
var ne = prj.fromDivPixelToLatLng(new google.maps.Point(left + width, top));
var bnds = new google.maps.LatLngBounds(sw, ne);
//this.map_.fitBounds(bnds);
this.dragging_ = false;
this.boxDiv_.style.display = 'none';
/**
* This event is fired when the drag operation ends.
* Note that the event is not fired if the hot key is released before the drag operation ends.
* #name DragZoom#dragend
* #param {GLatLngBounds} newBounds
* #event
*/
google.maps.event.trigger(this, 'dragend', points);
}
};

Google Maps v3 fitBounds() Zoom too close for single marker

Is there a way to set a max zoom level for fitBounds()?
My problem is that when the map is only fed one location, it zooms in as far as it can go, which really takes the map out of context and renders it useless. Perhaps I am taking the wrong approach?
I like mrt's solution (especially when you don't know how many points you will be mapping or adjusting for), except it throws the marker off so that it isn't in the center of the map anymore. I simply extended it by an additional point subtracting .01 from the lat and lng as well, so it keeps the marker in the center. Works great, thanks mrt!
// Pan & Zoom map to show all markers
function fitToMarkers(markers) {
var bounds = new google.maps.LatLngBounds();
// Create bounds from markers
for( var index in markers ) {
var latlng = markers[index].getPosition();
bounds.extend(latlng);
}
// Don't zoom in too far on only one marker
if (bounds.getNorthEast().equals(bounds.getSouthWest())) {
var extendPoint1 = new google.maps.LatLng(bounds.getNorthEast().lat() + 0.01, bounds.getNorthEast().lng() + 0.01);
var extendPoint2 = new google.maps.LatLng(bounds.getNorthEast().lat() - 0.01, bounds.getNorthEast().lng() - 0.01);
bounds.extend(extendPoint1);
bounds.extend(extendPoint2);
}
map.fitBounds(bounds);
// Adjusting zoom here doesn't work :/
}
You can setup your map with maxZoom in the MapOptions (api-reference) like this:
var map = new google.maps.Map(document.getElementById("map"), { maxZoom: 10 });
This would keep the map from zooming any deeper when using fitBounds() and even removes the zoom levels from the zoom control.
Another solution is to expand bounds if you detect they are too small before you execute fitBounds():
var bounds = new google.maps.LatLngBounds();
// here you extend your bound as you like
// ...
if (bounds.getNorthEast().equals(bounds.getSouthWest())) {
var extendPoint = new google.maps.LatLng(bounds.getNorthEast().lat() + 0.01, bounds.getNorthEast().lng() + 0.01);
bounds.extend(extendPoint);
}
map.fitBounds(bounds);
Once you've added all of the real bounds add these lines
var offset = 0.002;
var center = bounds.getCenter();
bounds.extend(new google.maps.LatLng(center.lat() + offset, center.lng() + offset));
bounds.extend(new google.maps.LatLng(center.lat() - offset, center.lng() - offset));
it get the center of the real bounds then adds two additional points one to the northeast and one to the southwest of you center
This effectively sets the minimum zoom, change the value of offset to increase or decrease the zoom
var map = new google.maps.Map(document.getElementById("map"), { maxZoom: 10 });
Using the MaxZoom option works best for not zooming to close on to the marks you have.
If it is for a single location, you can use setCenter() and setZoom() instead.
u can use
map.setOptions({
maxZoom: [what u want],
minZoom: [what u want]
});
this way u set the properties of the map after the map has been initialized .... u can set them as many times as u want ... but in ur case ... u can set them before fitBounds()
good luck,
rarutu
The way I prevent the map from zooming in to far is by adding this line of code:
var zoomOverride = map.getZoom();
if(zoomOverride > 15) {
zoomOverride = 15;
}
map.setZoom(zoomOverride);
Directly after this line:
map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
Feel free to change the zoom level to whatever level you don’t want the map to zoom past.
If you have any problems or questions, just leave me a comment on the blog post I wrote about this at http://icode4you.net/creating-your-own-store-locator-map-how-to-prevent-the-map-from-zooming-in-too-close-on-a-single-marker
I really like mrt's solution and it works perfectly if you've always only have one point to work with. I did however find that if the bounding box was not based on one point, but the points were very close together, this could still cause the map to be zoomed in too far.
Here's a way to first check if the points are within a defined distance of each other, then if they are smaller than that minimum distance, extend the bounds by that minimum distance:
var bounds = new google.maps.LatLngBounds();
// here you extend your bound as you like
// ...
var minDistance = 0.002;
var sumA = bounds.getNorthEast().lng() - bounds.getSouthWest().lng();
var sumB = bounds.getNorthEast().lat() - bounds.getSouthWest().lat();
if((sumA < minDistance && sumA > -minDistance)
&& (sumB < minDistance && sumB > -minDistance)){
var extendPoint1 = new google.maps.LatLng(bounds.getNorthEast().lat() + minDistance, bounds.getNorthEast().lng() + minDistance);
var extendPoint2 = new google.maps.LatLng(bounds.getNorthEast().lat() - minDistance, bounds.getNorthEast().lng() - minDistance);
bounds.extend(extendPoint1);
bounds.extend(extendPoint2);
}
Hope this helps someone!
As for me guys i solve it by creating an idle event after fitBounds. Working perfectly. Guess that's one of the most clean solutions here
var locations = [['loc', lat, lng], ['loc', lat, lng]];
.....
for (i = 0; i < locations.length; i++) {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 10
});
.... create markers, etc.
}
....
map.fitBounds(bounds);
google.maps.event.addListenerOnce(map, 'idle', function() {
if (locations.length == 1) {
map.setZoom(11);
}
});
This gives you a direct control upon max allowed zoom on bounds fitting.
var fitToMarkers = function(map, markers, maxZoom) {
if (typeof maxZoom == 'undefined') maxZoom = 15;
google.maps.event.addListenerOnce(map, 'bounds_changed', function(event) {
if (this.getZoom() > maxZoom) {
this.setZoom(maxZoom);
}
});
var bounds = new google.maps.LatLngBounds();
for (var m = 0; m < markers.length; m++) {
var marker = markers[m];
var latlng = marker.getPosition();
bounds.extend(latlng);
}
map.fitBounds(bounds);
};
I solved with this chunk, since Google Maps V3 is event driven:
you can tell the API to set back the zoom to a proper amount when the zoom_changed event triggers:
var initial = true
google.maps.event.addListener(map, "zoom_changed", function() {
if (intial == true){
if (map.getZoom() > 11) {
map.setZoom(11);
intial = false;
}
}
});
I used intial make the map not zooming too much loading when the eventual fitBounds permorfed, without it any zoom event over 11 would be impossible for the user.
After calling fitBounds() method, try to setup zoom level again. It will force the map to be at that zoom level whilst being centered at the right place.
I have soulution based on limiting max zoom when fitting bounds. Works for me (tested on Win 7 - IE 9, FF 13, Chrome 19):
// When fitting bounds:
var bounds = new google.maps.LatLngBounds();
// ...
// extend bounds as you like
// ..
// now set global variable when fitting bounds
window.fittingBounds = true;
map.fitBounds(bounds);
window.fittingBounds = false;
// attach this event listener after map init
google.maps.event.addListener(map, 'zoom_changed', function() {
// set max zoom only when fitting bounds
if (window.fittingBounds && map.getZoom() > 16) {
this.setZoom(16);
}
});
And .. here is another one.
Same idea as mrt and Ryan, but
also works if bounds size is not exactly zero (*)
prevents distortion near the poles
uses getCenter() instead of getNorthEast()
(*) Note: If the box is already big enough, then adding those two extra points should have no effect. So we don't need any further checking.
function calcBounds(markers) {
// bounds that contain all markers
var bounds = new google.maps.LatLngBounds();
// Using an underscore _.each(). Feel free to replace with standard for()
_.each(markers, function(marker) {
bounds.extend(marker.getPosition());
});
// prevent lat/lng distortion at the poles
var lng0 = bounds.getNorthEast().lng();
var lng1 = bounds.getSouthWest().lng();
if (lng0 * lng1 < 0) {
// Take the cos at the equator.
var cos = 1;
}
else {
var cos0 = Math.cos(lng0);
var cos1 = Math.cos(lng1);
// Prevent division by zero if the marker is exactly at the pole.
var cos_safe = Math.max(cos0, cos1, 0.0001);
}
var cos0 = Math.cos(bounds.getNorthEast.lng() * Math.PI / 180);
var cos1 = Math.cos(bounds.getSouthWest.lng() * Math.PI / 180);
// "radius" in either direction.
// 0.0006 seems to be an ok value for a typical city.
// Feel free to make this value a function argument.
var rLat = 0.0006;
var rLng = rLat / cos_safe;
// expand the bounds to a minimum width and height
var center = bounds.getCenter();
var p0 = new google.maps.LatLng(center.lat() - rLat, center.lng() - rLng);
var p1 = new google.maps.LatLng(lat.center() + rLat, center.lng() + rLng);
bounds.extend(p0);
bounds.extend(p1);
return bounds;
}
EDIT: I am not exactly sure if my ratio calculation correctly, considering we have a Mercator projection. I might re-edit this..
Its already answered here Google Maps v3: Enforcing min. zoom level when using fitBounds it works as expected :) so now if after fit bounds zoom is less then lets say 13 then you can set new zoom which you preffer
Here is my go at a solution, which also works when two markers are very close. The effective maximum zoom level is the same in both situations. So we do not end up zooming unneccesarily out, when there are more than one marker
The effect, again is ensuring a maximum zoom, without using the maxZoom option, which has the probably unwanted effect of making it impossible for the user to zoom further than the maxZoom level with the zoom control
I have calculated maxLat, minLat, maxLng and minLng beforehand...
var minLatSpan = 0.002;
if (maxLat - minLat < minLatSpan) {
// ensures that we do not zoom in too much
var delta = (minLatSpan - (maxLat - minLat)) / 2;
maxLat += delta;
minLat -= delta;
}
map.fitBounds({
east: maxLng,
west: minLng,
north: maxLat,
south: minLat,
});

Google Maps add 2 GEvent Listeners. 1 for each marker

I have the following code which lets the user plot two points on a Google MAP. I then want to be able to catch the event for each point(marker) being dragged to a new location. I am bad at Javascript and have spent hours trying to do this so I think it's time I get some help..
What I am trying to do is get the user to plot two points(markers) draggable on the map. I then want to be able to have my script write the positions(lat,long) to the document. I will then calculate the distance between these as part of a shipping app I am making.
I would like to have the contents of the document (lat,long) updated when a marker(point) is dragged to a new location.
Also, I fixed a schoolboy error where the point vars were being decalred inside the switch statement. My problem is fixed by moving the Add event listener statements inside the switch statement. Thanks Cannonade :)
The next thing now is to try and calculate the distance (crow flies) between the two points
Again, thanks for you help.. appreciated as always!!
Updated Code that works:
var map = null;
var geocoder = null;
var zoom = 15;
var first_point = false;
var boundary = new Array();
var cCount = 0;
var point1;
var point2;
function initialize() {
if (GBrowserIsCompatible()) {
first_point = false;
map = new GMap2(document.getElementById("map_canvas"));
var center = new GLatLng(37.4419, -122.1419);
map.setCenter(center, zoom);
GEvent.addListener(map, "click", function(overlay,point)
{
if (overlay != null)
{}
else
{
var n = boundary.length;
switch (cCount)
{
case 0:
point1 = new GMarker(point,{draggable: true});
map.addOverlay(point1);
cCount++;
GEvent.addListener(point1, "dragend", function()
{
alert('P1 Dragged');
});
break;
case 1:
point2 = new GMarker(point,{draggable: true});
map.addOverlay(point2);
cCount++;
GEvent.addListener(point2, "dragend", function()
{
alert('P2 Dragged');
});
break;
case 2:
map.clearOverlays();
cCount=0;
break;
}
}
});
map.addControl(new GSmallMapControl());
geocoder = new GClientGeocoder();
}
}
I have taken your code and made the following fixes:
Fixed the unbalanced brackets I mentioned in the comment.
Moved the two addListener calls into the switch statement so that the point1 and point2 variables are still in scope when you attach the events.
You can check out the example here (source).
Edit:
Here is some Javascript code to get the linear distance between two points (in meters):
/* Convert degress to radians */
function deg2rad(deg) {
return deg / (180 / Math.PI);
}
/* Calculate distance between two points */
function point_distance(a, b) {
var r = 6378700;
var lat1 = a.y;
var lat2 = b.y;
var lon1 = a.x;
var lon2 = b.x;
var dist = r * Math.acos(Math.sin(deg2rad(lat1)) * Math.sin(deg2rad(lat2)) +
Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) *
Math.cos(deg2rad(lon1 - lon2)));
return dist;
}
This is based on the approximate radius of the earth being 6378700m.