Google Maps KMZ file not rendering in IE8 and IE7 - google-maps

I have a web app with a map in it. I've added a nice little custom map control to turn on and off different layers on the map. Currently there are only two layers, and it all works nice and fine in most browsers.
Except for IE8+7. None of the layers are showing on the map when turned on. As far as I can tell the map is loading the kmz/kml files (when preserveViewport is set to false, the map moves to the right location) but they're just not appearing. One layer contains polylines, and the other contains markers. The code I use is below:
function someFunction() {
//code to initialise map etc goes here...
var layers = [];
//Create 1st layer
var exchangeslayer = new google.maps.KmlLayer('http://link.to.file/exchanges.kmz'
suppressInfoWindows: true,
preserveViewport: true
});
layers.push({name: "Exchanges", layer: exchangeslayer});
//Code to create second layer
var nyclayer = new google.maps.KmlLayer('http://www.nyc.gov/html/dot/downloads/misc/cityracks.kml'
suppressInfoWindows: true,
preserveViewport: false
});
layers.push({name: "NY City Tracks", layer: nyclayer});
addCustomLayerControls(layers);
}
function addCustomLayerControls(layers) {
//there is code here that would generate the divs for the custom map control
var container; //container is a div element created via javascript
for (var i = 0; i < layers.length; i++) {
this.addLayerLabelToContainer(layers[i], container);
}
//some more code
}
function addLayerLabelToContainer(layer, container) {
var map; //Assume I get a reference to the map
//some code here to make pretty labels for the map controls...
var layerLabel; // layerLabel is a div element created via javascript
google.maps.event.addDomListener(layerLabel, 'click', function() {
if(layer.layer.map == null) {
layer.layer.setMap(map);
} else {
layer.layer.setMap(null);
}
});
}

So as it turns out my problem related to CSS. One of my stylesheets was applying max-width: 100% to all img tags. This was playing havok with the map markers/polylines.
Its obvious now that I see it, but when you think the problem is to do with the javascript its not so obvious. As such, I'll leave this answer here for anyone else who makes the same mistake as me.

If you modify addLayerLabelToContainer() like this then it works in IE as expected. Verified it loads KMZ correctly in IE 8 and 9.
function addLayerLabelToContainer(layer, container) {
// var map; //Assume I get a reference to the map
//some code here to make pretty labels for the map controls...
var layerLabel; // layerLabel is a div element created via javascript
if(layer.layer.map == null) {
layer.layer.setMap(map);
} else {
layer.layer.setMap(null);
}
}
Don't need to invoke addDomListener(). Also note the API syntax:
addDomListener(instance:Object, eventName:string, handler:Function)
Also minor fix of syntax errors in someFunction as follows:
function someFunction() {
// var map; //assume map is initialised, I've just removed that code
var layers = [];
// see https://developers.google.com/maps/documentation/javascript/layers
//Create 1st layer
var exchangeslayer = new google.maps.KmlLayer(
'http://kml-samples.googlecode.com/svn/trunk/kml/kmz/simple/big.kmz',
{ suppressInfoWindows: true, preserveViewport: true
});
layers.push( {name: "Exchanges", layer: exchangeslayer} );
// ...
addCustomLayerControls(layers);
}

Related

Can the default behavior of a Google Maps Event be overridden

I am trying create a restriction on the movement of an editable polygon. I want to prevent the inside path from being pulled outside of outer path. I am using Google Maps google.maps.geometry.poly.containsLocation function to check if the new point is within the outer bounds but I can't find a way to stop the action from happening if it is outside.
I have tried returning false but the polygon still goes to the new location
google.maps.event.addListener(poly.getPaths().getArray()[1], 'set_at', function() {
return keepInside(this, arguments[0], arguments[1]);
});
function keepInside(polygon, index, new_point)
{
outer_edge = new google.maps.Polygon({
paths: polygon.getArray(),
});
is_in = google.maps.geometry.poly.containsLocation(new_point,outer_edge);
if(!is_in)
{
return false;
}
return true;
}
You got pretty close with your original code. Instead of returning false, you could set the point back to it's original position. Also, the second argument passed to the set_at listener is not the new point but the old point. Try this:
google.maps.event.addListener(poly.getPaths().getArray()[1], 'set_at', function(index, oldPoint) {
return keepInside(this, index, this.getAt(index), oldPoint);
});
function keepInside(polygon, index, newPoint, oldPoint)
{
outer_edge = new google.maps.Polygon({
paths: polygon.getArray(),
});
if(!google.maps.geometry.poly.containsLocation(newPoint, outer_edge))
{
polygon.setAt(index, oldPoint);
}
}

Bring GoogleMaps InfoWindow to front

I have a GoogleMaps APIv3 application in which multiple InfoWindows can be open at any one time. I would like to be able to bring an obscured InfoWindow to the front of all other InfoWindows if any part of it is clicked - similar to the behaviour of windows in MS Windows OS.
I had thought to add an onclick event handler which increases the z-index of the InfoWindow, but the event handler does not appear to be firing.
ZIndex is a global variable that keeps increasing as InfoWindows are clicked - or thats the theory anyway.
Can anyone help ?
Here is my code:-
var ZIndex=1;
var iw = new google.maps.InfoWindow({ content:contentString });
google.maps.event.addListener(iw, 'click', handleInfoWindowClick(iw) );
function handleInfoWindowClick(infoWindow) {
return function() {
infoWindow.setZIndex(ZIndex++);
}
}
there is no click-event for an infoWindow, it's a little bit more difficult.
you'll need to use an element(not a string) as content for the infowindow, because you need a DOMListener instead a listener for the infowindow-object
when domready-fires, you must apply the click-DOMListener to the anchestor of this content-node that defines the infowindow
The following code will do this for you, add this to your page:
google.maps.InfoWindowZ=function(opts){
var GM = google.maps,
GE = GM.event,
iw = new GM.InfoWindow(),
ce;
if(!GM.InfoWindowZZ){
GM.InfoWindowZZ=Number(GM.Marker.MAX_ZINDEX);
}
GE.addListener(iw,'content_changed',function(){
if(typeof this.getContent()=='string'){
var n=document.createElement('div');
n.innerHTML=this.getContent();
this.setContent(n);
return;
}
GE.addListener(this,'domready',
function(){
var _this=this;
_this.setZIndex(++GM.InfoWindowZZ);
if(ce){
GM.event.removeListener(ce);
}
ce=GE.addDomListener(this.getContent().parentNode
.parentNode.parentNode,'click',
function(){
_this.setZIndex(++GM.InfoWindowZZ);
});
})
});
if(opts)iw.setOptions(opts);
return iw;
}
Instead of google.maps.InfoWindow() you must call now google.maps.InfoWindowZ()
It also returns a genuine InfoWindow, but with the mentioned listener applied to it. It also creates the node from the content when needed.
Demo: http://jsfiddle.net/doktormolle/tRwnE/
Updated version for visualRefresh(using mouseover instead of click) http://jsfiddle.net/doktormolle/uuLBb/

OpenLayers - clear 'map' div

I am using OpenLayers to display dynamically loaded images. The code I am using is:
var map;
function init(strURL) {
map = new OpenLayers.Map('map');
var options = { numZoomLevels: 3,
isBaseLayer: true, };
var graphic = new OpenLayers.Layer.Image(
'City Lights',
strURL + "?sc=page",
new OpenLayers.Bounds(-180, -88.759, 180, 88.759),
new OpenLayers.Size(580, 288),
options
);
// graphic.events.on({
// loadstart: function () {
// OpenLayers.Console.log("loadstart");
// },
// loadend: function () {
// OpenLayers.Console.log("loadend");
// }
// });
var jpl_wms = new OpenLayers.Layer.WMS("NASA Global Mosaic",
"http://t1.hypercube.telascience.org/cgi-bin/landsat7",
{ layers: "landsat7" }, options);
map.addLayers([graphic, jpl_wms]);
map.addControl(new OpenLayers.Control.LayerSwitcher());
map.zoomToMaxExtent();
}
I am calling this function on a button click event and passing the strURL (sources of the images) at that time. The result is, with each click a different image is loaded and displayed on the web page but is not clearing the previous image. So I 5 different images on the webpage are shown with 5 clicks and so on.
My javascript knowledge is limited, so my apologies if this is a stupid question. How to stop this behavior? Thanks for any assistance.
Also, I didn't quite understand the lines:
var jpl_wms = new OpenLayers.Layer.WMS("NASA Global Mosaic",
"http://t1.hypercube.telascience.org/cgi-bin/landsat7",
{ layers: "landsat7" }, options);
But I know these lines are needed since I'm getting js error if I remove them.
So currently you are calling init(strURL) with each button click? Divide that code into two parts:
On page load, create map and layer objects
On button click, just update URL of existing image layer. Image layer has setUrl(url) method for that: http://dev.openlayers.org/apidocs/files/OpenLayers/Layer/Image-js.html#OpenLayers.Layer.Image.setUrl
Here is sample, that should explain it: http://jsfiddle.net/mEHrN/6/
About var jpl_wms = ... - it creates WMS layer, that should display Landsat imagery (but that URL doesn't seem to work). If you remove it, remember also to remove it from map.addLayers:
map.addLayers([graphic]);
Probably this was reason, why you got JS error.

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);
}

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.