Get non-wrapping map bounds in Google Maps API V3 - google-maps

If you zoom a google map out the world will start to repeat horizontally. Using .getBounds() seems to return the longitude at the edges of the displayed map image. But I would like to get minimum and maximum longitudes for the current view of the real world.
For example in this image .getBounds() says that the longitude ranges between 116 and 37 degrees (giving a width of -79 degrees!). The range I'm looking for is -244 to +37.
(or even -180 to +37 as this is the extremes of the world that is viewable around the map centre.)
And another example. Here I'm looking for -180 to +180 ...
You can try it for yourself here...
http://jsfiddle.net/spiderplant0/EBNYT/
(Apologies if this has been answered before - I did find some old similar questions but none seemed to have satisfactory answers).

I ran into the same issues today, but I think I finally figured it out.
In the first scenario above, you can use map.getBounds().toSpan() to get the width in longitude.....as long as the map did not wrap around.
For the second scenario where the map wraps around, I extended the google.maps.OverlayView() to get the google.maps.MapCanvasProjection object. From there you can call the function getWorldWidth().
It will give you the world width in pixel, then you can compare it with your map container's width. If your container is bigger, your map has wrapped around.
Don't know if the function is meant for this but it works.

The answer proposed by user1292293 worked for me (Google map api V3)
Extension of google.maps.OverlayView()
function MyMapOverlay() {}
MyMapOverlay.prototype = new google.maps.OverlayView();
MyMapOverlay.prototype.onAdd = function() {};
MyMapOverlay.prototype.draw = function() {};
MyMapOverlay.prototype.onRemove = function() {};
Add overlay to the map
var map = new google.maps.Map(domContainer, {...});
var overlay = new MyMapOverlay();
overlay.setMap(map);
check if map wraps around:
var proj = overlay.getProjection();
var wwidth = 0;
if (proj) wwidth = proj.getWorldWidth();
var mapsWrapsAround=false;
if (__wwidth > 0 && __wwidth < domContainer.width()) mapsWrapsAround = true;

I used the answer from rebpp to prevent the map from wrapping by setting the getWorldWidth. Here's the MapWrappingPrevent I created.
To use this just call
var wrapPreventer = new MapWrappingPrevent(_map);
/* This class prevents wrapping of a map by adjusting the max-width */
function MapWrappingPrevent(map) {
var self = this;
this.setMap(map);
map.addListener('zoom_changed', function () {
self.onZoomChanged();
});
}
MapWrappingPrevent.prototype = new google.maps.OverlayView();
MapWrappingPrevent.prototype.onAdd = function () { this.onZoomChanged(); };
MapWrappingPrevent.prototype.draw = function () { };
MapWrappingPrevent.prototype.onRemove = function () { };
MapWrappingPrevent.prototype.onZoomChanged = function () {
var proj = this.getProjection();
if (proj) {
var wrappingWidth = proj.getWorldWidth();
$(this.getMap().getDiv()).css({'max-width': wrappingWidth + 'px'})
}
};

Related

google map v3 how fitbounds with zoom on user's location

I am using google v3, i want to fitbounds with center on userPinLoc object, i have the following code
var bounds = new google.maps.LatLngBounds();
bounds.extend(userPinLoc)// wants to center on userPinLocation
for (i in nearestEntitiesToZoom) {
entity = nearestEntitiesToZoom[i];
var googleLatLng = new google.maps.LatLng(entity.latitude,entity.longitude);
bounds.extend(googleLatLng);
}
bounds.extend(userPinLoc);
//googleMap.setCenter(userPinLoc) this not working
googleMap.fitBounds(bounds);
any quick fix after update i am pasting new code
function setInitialZoom() {
mapZoom = googleMap.getZoom();
var bounds = new google.maps.LatLngBounds();
bounds.extend(userPinLoc);
for (i in nearestEntitiesToZoom) {
entity = nearestEntitiesToZoom[i];
var googleLatLng = new google.maps.LatLng(entity.latitude,entity.longitude);
bounds.extend(googleLatLng);
}
google.maps.event.addDomListener(googleMap, 'bounds_changed', function() {
googleMap.setCenter(userPinLoc);
});
googleMap.fitBounds(bounds);
setTimeout(function() {
google.maps.event.clearListeners(googleMap, 'bounds_changed');
}, 3000);
}
Remove the setCenter from where it is currently. You need to have an event listener for when the map's bounds change. I think when you call fitBounds, you have to wait for it to redraw before you can adjust the centre. One way would be to use a timeout, but you can simply add this to your initialize function:
google.maps.event.addDomListener(googleMap, 'bounds_changed', updateCenter);
And then create a new function to update the centre, which takes the userPinLoc value (needs to be a global variable):
function updateCenter() {
googleMap.setCenter(userPinLoc);
}

limiting google maps autocomplete to UK address only

I've been looking at the example on:
http://code.google.com/apis/maps/documentation/javascript/examples/places-autocomplete.html
and have decided to incorporate it into my site.
Is it possible to limit the addresses to UK addresses only?
Try this:
var input = document.getElementById('searchTextField');
var options = {
types: ['(cities)'],
componentRestrictions: {country: 'tr'}//Turkey only
};
var autocomplete = new google.maps.places.Autocomplete(input,options);
You can't strictly/hard limit the locations that it finds, although there is a feature request in the system to do so, but you can set a 'bias' on the results. It's passed in as an argument to the autocomplete method as a google maps bounds object. Autocomplete will then favor locations within those boundaries. Note, however, that since this isn't a hard boundary, if there are matches for the search outside the boundaries it will return those.
From my usage it seems a bit buggy and can use some improvement - especially considering that anything outside your boundary is not tagged by proximity at all, so something one block outside the boundary is just as likely to show as something 1000 miles outside, so make sure you play around with getting the boundaries working right.
You can intercept the JSONP results that are returned by the google.maps.places.Autocomplete functionality and use them as you see fit, such as to limit by country and display the results.
Basically you redefine the appendChild method on the head element, and then monitor the javascript elements that the Google autocomplete code inserts into the DOM for JSONP. As javascript elements are added, you override the JSONP callbacks that Google defines in order to get access to the raw autocomplete data.
It's a bit of a hack, here goes (I'm using jQuery but it's not necessary for this hack to work):
//The head element, where the Google Autocomplete code will insert a tag
//for a javascript file.
var head = $('head')[0];
//The name of the method the Autocomplete code uses to insert the tag.
var method = 'appendChild';
//The method we will be overriding.
var originalMethod = head[method];
head[method] = function () {
if (arguments[0] && arguments[0].src && arguments[0].src.match(/GetPredictions/)) { //Check that the element is a javascript tag being inserted by Google.
var callbackMatchObject = (/callback=([^&]+)&|$/).exec(arguments[0].src); //Regex to extract the name of the callback method that the JSONP will call.
var searchTermMatchObject = (/\?1s([^&]+)&/).exec(arguments[0].src); //Regex to extract the search term that was entered by the user.
var searchTerm = unescape(searchTermMatchObject[1]);
if (callbackMatchObject && searchTermMatchObject) {
var names = callbackMatchObject[1].split('.'); //The JSONP callback method is in the form "abc.def" and each time has a different random name.
var originalCallback = names[0] && names[1] && window[names[0]] && window[names[0]][names[1]]; //Store the original callback method.
if (originalCallback) {
var newCallback = function () { //Define your own JSONP callback
if (arguments[0] && arguments[0][3]) {
var data = arguments[0][4]; //Your autocomplete results
//SUCCESS! - Limit results here and do something with them, such as displaying them in an autocomplete dropdown.
}
}
//Add copy all the attributes of the old callback function to the new callback function. This prevents the autocomplete functionality from throwing an error.
for (name in originalCallback) {
newCallback[name] = originalCallback[name];
}
window[names[0]][names[1]] = newCallback; //Override the JSONP callback
}
}
//Insert the element into the dom, regardless of whether it was being inserted by Google.
return originalMethod.apply(this, arguments);
};
James Alday is correct:
http://code.google.com/apis/maps/documentation/javascript/places.html#places_autocomplete
var defaultBounds = new google.maps.LatLngBounds(
new google.maps.LatLng(49.00, -13.00),
new google.maps.LatLng(60.00, 3.00));
var acOptions = {
bounds: defaultBounds,
types: ['geocode']
};
it is somewhat annoying as searching for Durham gives Durham, North Carolina as the second result, regardless of how you try to persuade it to region bias - you can set it to viewport map bounds and it'll still try to suggest NC state... The jQuery solution can be found here, but doesn't seem to give as many results as the v3 API.
http://code.google.com/p/geo-autocomplete/
The best way you would go about doing this, is to query the places api yourself and appending the queried string with your country. Or, of course, use the geo-autocomplete jQuery plugin.
Just change the google domain for the maps to your country domain and it will automatically search within your country only:
So:
http://maps.google.com/maps/api/geocode/xml?address={0}&sensor=false&language=en
To:
http://maps.google.nl/maps/api/geocode/xml?address={0}&sensor=false&language=nl
Try something like this.
// Change Bangalore, India to your cities boundary.
var bangaloreBounds = new google.maps.LatLngBounds(
new google.maps.LatLng(12.864162, 77.438610),
new google.maps.LatLng(13.139807, 77.711895));
var autocomplete = new google.maps.places.Autocomplete(this, {
bounds: bangaloreBounds,
strictBounds: true,
});
autocomplete.addListener('place_changed', function () {
});
I find that if you set the map to roughly where you want then set bounds to it, the search finds places in that area first. You do not to physically show the map.
It works better than giving random overseas addresses first, setting to country does not work.
The code for autocomplete to get latln is:
<div id="map_canvas"></div>
<input type="text" name="location" id="location" placeholder="Type location...">
<input type="text" name="loc_latitude" id="latitude">
<input type="text" name="loc_longitude" id="longitude">
and the JS is:
$(document).ready(function () {
var mapOptions = {
center: new google.maps.LatLng(52.41041560, -1.5752999),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map_canvas'),
mapOptions);
var autocomplete;
autocomplete = new google.maps.places.Autocomplete((document.getElementById(searchInput)), {
types: ['geocode'],
});
autocomplete.bindTo('bounds', map);
google.maps.event.addListener(autocomplete, 'place_changed', function () {
var near_place = autocomplete.getPlace();
document.getElementById('latitude').value = near_place.geometry.location.lat();
document.getElementById('longitude').value = near_place.geometry.location.lng();
});
});
$(document).on('change', '#'+searchInput, function () {
document.getElementById('latitude').value = '';
document.getElementById('longitude').value = '';
});
Not exactly what you asked for but it works for me.

How to create a text overlay in Google Maps API v3 that does not pan?

I'm using Google Maps API v3. I would like to create a text overlay on a map that does not move when the map is panned. Is the best approach to manipulate the DOM elements accessible from the MapPanes object or is it best to create a custom control even though it would not do much other than display text?
The simplest way that I found worked for me was a few lines of JavaScript added after I created a new map. So, after this:
map = new google.maps.Map('myMapDivId', mapOptions);
add this:
var myTitle = document.createElement('h1');
myTitle.style.color = 'white';
myTitle.innerHTML = 'Hello World';
var myTextDiv = document.createElement('div');
myTextDiv.appendChild(myTitle);
map.controls[google.maps.ControlPosition.BOTTOM_CENTER].push(myTextDiv);
You will probably want to style the text to look nicer.
An alternative is to put the div in your HTML:
<div id="myTextDiv" style="color: white; position: absolute;">
<h1>Hello World</h1>
</div>
and then do this in your JavaScript:
var myControl = document.getElementById('myTextDiv');
map.controls[google.maps.ControlPosition.TOP_CENTER].push(myControl);
NOTE an important difference: If you use the HTML route to define your div, you must set the position style to absolute in the HTML to avoid rendering problems.
From you're describing, the best approach would be a custom control. Docs for that are here. Custom controls can be as simple or a complicated as you want.
One reason why you would want to muck around with the map panes is if you wanted such a 'control' to lie underneath the markers / shadows / polylines etc. I'm doing this right now to show a crosshairs in the center of the map at all times. But because I keep it as an overlay, I choose the panes in such a way that the markers are above it, so they can continue to be clicked and interacted with - using the mapPane. Here's how I'm doing it:
var CrosshairOverlay = function(map){
this._holder = null;
this.setMap(map);
};
CrosshairOverlay.prototype = new google.maps.OverlayView();
CrosshairOverlay.prototype.onAdd = function(){
var map = this.getMap();
var holder = this._holder = $('<div>').attr('id', 'crosshair')[0];
var crosshairPaper = this._paper = R(holder, 150, 150);
// ... all your drawing and rendering code here.
var projection = this.getProjection();
var wrappedHolder = $(holder);
var updateCrosshairPosition = function(){
var center = projection.fromLatLngToDivPixel(map.getCenter());
wrappedHolder.css({left:center.x-75, top:center.y-75});
}
_.each(['drag','dragend','bounds_changed','center_changed','zoom_changed','idle','resize'], function(event){
google.maps.event.addListener(map, event, updateCrosshairPosition);
});
google.maps.event.addListener(map, 'maptypeid_changed', function(){
_.defer(updateCrosshairPosition);
});
this.getPanes().mapPane.appendChild(holder);
};
CrosshairOverlay.prototype.draw = function(){
};
CrosshairOverlay.prototype.onRemove = function(){
this._holder.parentNode.removeChild(this._holder);
this._holder = null;
};
The reason the maptypeid_changed has its own handler with a defer is because that event is fired before the map properly sets itself up when changing the type. Just run your function after the current event loop.

Google Maps v3 OverlayView.getProjection()

I cannot seem to figure out why the object returned by getProjection() is undefined. Here is my code:
// Handles the completion of the rectangle
var ne = recBounds.getNorthEast();
var sw = recBounds.getSouthWest();
$("#map_tools_selat").attr( 'value', sw.lat() );
$("#map_tools_nwlat").attr( 'value', ne.lat() );
$("#map_tools_selng").attr( 'value', ne.lng() );
$("#map_tools_nwlng").attr( 'value', sw.lng() );
// Set Zoom Level
$("#map_tools_zoomlevel").attr( 'value', HAR.map.getZoom()+1 );
document.getElementById("map_tools_centerLat").value = HAR.map.getCenter().lat();
document.getElementById("map_tools_centerLong").value = HAR.map.getCenter().lng();
// All this junk below is for getting pixel coordinates for a lat/lng =/
MyOverlay.prototype = new google.maps.OverlayView();
MyOverlay.prototype.onAdd = function() { }
MyOverlay.prototype.onRemove = function() { }
MyOverlay.prototype.draw = function() { }
function MyOverlay(map) { this.setMap(map); }
var overlay = new MyOverlay(HAR.map);
var projection = overlay.getProjection();
// END - all the junk
var p = projection.fromLatLngToContainerPixel(recBounds.getCenter());
alert(p.x+", "+p.y);
My error is: Cannot call method 'fromLatLngToContainerPixel' of undefined
Actually, i the reason why this happens is because the projection object is created after the map is idle after panning / zooming. So, a better solution is to listen on the idle event of the google.maps.Map object, and get a reference to the projection there:
// Create your map and overlay
var map;
MyOverlay.prototype = new google.maps.OverlayView();
MyOverlay.prototype.onAdd = function() { }
MyOverlay.prototype.onRemove = function() { }
MyOverlay.prototype.draw = function() { }
function MyOverlay(map) { this.setMap(map); }
var overlay = new MyOverlay(map);
var projection;
// Wait for idle map
google.maps.event.addListener(map, 'idle', function() {
// Get projection
projection = overlay.getProjection();
})
I kind of figured out what was going on. Even though it is still not crystal clear why this happens, I know that I had to instantiate the variable "overlay" right after instantiating my google map (HAR.map). So I practically moved that code snippet into my HAR class and now i use:
HAR.canvassOverlay.getProjection().fromLatLngToContainerPixel( recBounds.getCenter() );
So now, every time I create a map via my class "HAR" I also have a parallel OverlayView object within my class.
The Error could have been with losing scope of my class object, but I think it was more of the map event "projection_changed" not being fired. I got a hint from the map API docs for map class, under method getProjection():
"Returns the current Projection. If the map is not yet initialized (i.e. the mapType is still null) then the result is null. Listen to projection_changed and check its value to ensure it is not null."
If you are getting the similar issue, make sure that you assign your overlayView.setMAP( YOUR_MAP_OBJECT ) closely after instantiating the map object.

Google maps: Set different zoom levels for two different maps

I have two maps on a page, one is a map of the world, and the other is a closeup of the current place they picked on the map of the world. I would like to set different zoom min/max levels for each map but:
G_NORMAL_MAP.getMinimumResolution = function(){return 11};
Seems to set the same min/max for both maps, I can't set them to different levels.
I think the problem is probably elsewhere in your code - I'm not sure exactly how you're using that function.
Here is a method that will work. You can re-write it to have less duplication.
map1 = new GMap2(document.getElementById("map1"));
map1.addControl(new GLargeMapControl3D());
map1.addControl(new GMenuMapTypeControl());
var mt = map1.getMapTypes();
// Overwrite the getMinimumResolution() and getMaximumResolution() methods
for (var i=0; i<mt.length; i++) {
mt[i].getMinimumResolution = function() {return 7;}
mt[i].getMaximumResolution = function() {return 11;}
}
map1.setCenter(new GLatLng(40,-100), 8);
map2 = new GMap2(document.getElementById("map2"));
map2.addControl(new GLargeMapControl3D());
map2.addControl(new GMenuMapTypeControl());
var mt = map2.getMapTypes();
// Overwrite the getMinimumResolution() and getMaximumResolution() methods
for (var i=0; i<mt.length; i++) {
mt[i].getMinimumResolution = function() {return 2;}
mt[i].getMaximumResolution = function() {return 6;}
}
map2.setCenter(new GLatLng(40,-100), 4);
Do you need 2 different maps? You can use the Map2.showMapBlowup() function to show a subarea which will be a zoomed in section on the current map.
I'm sorry I don't know if you can actually do it with 2 different maps.
http://code.google.com/apis/maps/documentation/reference.html#GMap2.showMapBlowup
You could use a custom map type and copy the G_NORMAL_MAP members of using a library like Prototype.
var G_MY_MAP = Class.create(G_NORMAL_MAP, {
getMinimumResolution: function()
{
return 11;
}
});
Then on your second map:
secondMap.addMapType(G_MY_MAP);
secondMap.setMapType(G_MY_MAP);
No idea if this will work, just a brain storm.....