Google Maps V3 JavaScript works only in Chrome? - javascript

I wrote a script that first geocodes an address and then displays a map of that address.
The trouble is, it only works in Chrome / Chromium. Other browsers (Firefox 10 & IE9) display a grey box. A problem that could be related, if I add a marker to the map, the marker does not show in Chrome.
I know that :
I connect with the API successfully with my API key.
The address is properly geocoded.
I use jQuery UI dialog to display the map. This, however, does not seem to be a problem. Removing the dialog and using a static div creates the same "grey box" result.
Below is my script, how I invoke it, and the website that I am using this on.
Here's the script:
function Map(properties)
{
var that = this;
// the HTML div
this.element = properties.element;
// address string to geocode
this.address = properties.address;
// title to use on the map and on the jQuery dialog
this.title = properties.title;
this.latlng = null;
this.map = null;
this.markers = [];
// geocode address and callback
new google.maps.Geocoder().geocode({'address': this.address}, function(data)
{
// geocoded latitude / longitude object
that.latlng = data[0].geometry.location;
// map options
var options =
{
zoom: 16,
center: that.latlng,
zoomControl: false,
streetViewControl: false,
mapTypeControl: false,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
// create a map
that.map = new google.maps.Map(that.element, options);
// add a marker
that.markers.push(new google.maps.Marker({map: that.map,
position: that.latlng,
title: that.title + "\n" +
that.address}));
});
this.get_google_map = function()
{
return that.map;
}
// creates a jQuery UI dialog with a map
this.show_in_dialog = function()
{
// because the dialog can resize, we need to inform the map about this
$(that.element).dialog({ width: 400, height: 300, title: that.title,
resizeStop: function(event)
{
google.maps.event.trigger(that.map, 'resize');
},
open: function(event)
{
google.maps.event.trigger(that.map, 'resize');
}});
}
this.center = function()
{
that.map.setCenter(that.latlng);
}
}
Here's how I invoke it :
// grab the address via HTML5 attribute
var address = $("#address").attr("data-address");
// ... and the title
var title = $("#address").attr("data-title") + " Map";
var map_element = document.createElement('div');
// append the newly created element to the body
$("body").append(map_element);
// create my own map object
var map = new Map({ element : map_element,
address : address,
title : title });
// bind a link to show the map
$("#map_link").click(function()
{
map.center();
map.show_in_dialog();
return false;
});
And here's the URL of the problem (click on map):
http://testing.fordservicecoupons.com/dealer/30000/premium_coupon_page
Last but not least, I combine and obfuscate my JavaScripts, so what you see above is not exactly the same as in the source on the website.

This doesn't look good:
resizeStop: function(event) { google.maps.event.trigger(that.element, 'resize'); },
open: function(event) { google.maps.event.trigger(that.element, 'resize'); }
you trigger the resize-event on the element that contains the map(that.element), but you must trigger resize on the google.maps.Map-object (what should be that.map in this case)

Wow... Here was the issue.
The layout that I built was a fluid layout. So, one of the first CSS rules that I have written was:
img, div { max-width: 100%; }
So that divs and images can scale. Well, for whatever reason, Google maps DOES NOT like this rule with the end result being a grey box.
And so I added another rule - an exception for Google maps:
img.no_fluid, div.no_fluid { max-width: none; }
And then, in javascript:
// AFTER DIALOG CREATION
$(dialog).find('*').addClass("no_fluid");
The find('*') will get us all the descendants.
Viola!

Related

Google Map - Onclick re-render (height bug)

I have a working google map via JS with custom styles. I am looking to use this twice on the site, however with a fixed element, the element is set # 0px then transitions to 800px in height. However I need to call the google resize event in order for the map to re-size otherwize it results in a bad UI (clipped map).
Resize Code:
google.maps.event.trigger(map, 'resize');
I have the following code:
function google_map_custom(){
function GoogleMapOptions(){
var markerPosition = new google.maps.LatLng([variable],[variable]),
mapCenter = new google.maps.LatLng([variable],[variable]);
var mapOptions = {
zoom: 15,
scrollwheel: false,
panControl:true,
zoomControl:true,
rotateControl:true,
disableDefaultUI:true,
center: mapCenter,
styles: [
{
"CUSTOM Google JSON": "styles"
},
{}]
};
// ASSOCIATE VARIABLE WITH HTML ID
var mapElement = document.getElementById('google-map');
// Align Settings to DOM Element
var map = new google.maps.Map(mapElement, mapOptions);
// RETINA MARKER (CUSTOM RE-SIZE) - USE VARIABLE BELOW
var image = new google.maps.MarkerImage("[path-to-url]", null, null, null, new google.maps.Size(44,65));
// Tailor Custom Marker (SVG / PNG ACCEPTED) - USE CDN
var marker = new google.maps.Marker({
position: markerPosition,
map: map,
icon:image
});
}
// Trigger map with element id and specific settings above
google.maps.event.addDomListener(window, 'load', GoogleMapOptions);
}
My question is, how do I call the resize event on a click handler? I have this code as an example:
$('[class selector]').click(function(){
$('#google-map.hidden--homepage').toggleClass('[active selector 800px in height]');
// INVOKE FUNCTION
google_map_custom();
});
Just to confirm, transition works, styles work, map loads. I just need to trigger the map when the element is enlarged.
thanks!
COMMENT IMG (this is the styles for the google container:

Trigger event when google maps fusiontable layer is loading or finished loading?

I'm loading in quite a lot of data from a fusion table using Google Maps Api. I'm adding the data as a layer to the map using the code below (code not relevant has been omitted)
function initialize() {
var tableId = 'xyxyxyxyxyxyxyxyxy';
map = new google.maps.Map(document.getElementById('map-canvas'), {
center: new google.maps.LatLng(51.522416,-0.11673),
zoom: 9,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var layer = new google.maps.FusionTablesLayer();
google.maps.event.addDomListener(
document.getElementById('checkbox_id'),
'click',
function() { filterMap(layer, tableId, map); }
);
}
function filterMap(layer, tableId, map, generated) {
var the_where_query = generate_where()
layer.setOptions({
query: {
select: 'geometry',
from: tableId,
where: the_where_query
},
options : {suppressInfoWindows:true}
});
}
My issue is that there is a big gap between clicking on the the checkbox and the data appearing on the map. I want to be able to listen for an event somehow so that I can
Display a loading div element when the user clicks the checkbox
When layer.setOptions has returned hide the loading div element.
I understand how to do the DOM work with the div, I just can't seem to find a good way of telling if the query has returned from the fusiontable lookup (which can take 1 - 2 seconds sometimes)
You can put a listener to capture if its loaded. status_changed event is created for this.
google.maps.event.addListener(layer, 'status_changed', function() {
--your code here
});
Or, you can use properties_changed event which will be fired after it is loaded.

js singleton - how to avoid accessing class members via the namespace

I'm trying to improve my Javascript coding style and have been reading that it's good to namespace stuff.
However I can't seem to use the "this" keyword everywhere that I would like to - instead I can only access my class properties via the namespace (in this case "oldMap") from within anonymous functions. This means that I can't change the namespace id without changing the code too - this seems like it's probably wrong.
Here's the class I built - it actually appears to work properly though. (sorry it's quite long).
Any suggestions / hints on what I'm doing right / wrong gratefully received. Thanks
var oldMap = {
map : null,
center : {lat:50, lng:20, zoom:3},
drawn : false,
data : {},
divId : "oldMap",
url : "php/getMapData.php",
infowindow : new google.maps.InfoWindow({
size: new google.maps.Size(150,50)
}),
init : function () {
if (!this.drawn){
$.getJSON(
this.url,
function(d){
if(d){
$.extend(oldMap.data,d);
var latlng = new google.maps.LatLng(oldMap.center.lat, oldMap.center.lng);
var myOptions = {
zoom: oldMap.center.zoom,
center: latlng,
mapTypeId: google.maps.MapTypeId.TERRAIN
};
// create the map
map = new google.maps.Map(document.getElementById("oldMap"),myOptions);
// create the legend
var legendDiv = document.createElement('DIV');
legendDiv.innerHTML = '<div id="legend"><img src="images/markers/legend-blur.png"></div>';
map.controls[google.maps.ControlPosition.TOP_LEFT].push(legendDiv);
google.maps.event.addListener(map, 'click', function() {
infowindow.close();
});
// Set the info window html template
var infoWindowTemplate = "<div id='balloon'>{{#url2}}<img src='{{url2}}' />{{/url2}}<h2>{{project_name}}</h2><p><b>Amount</b> € {{cost}}</p><p><b>Country</b> {{country}}</p><p><b>Year</b> {{year}}</p><p><b>Project Type</b> {{project_type}}</p><p>{{description}}</p>{{#url}}<p><a target='_blank' href='{{url}}'>More info</a></p>{{/url}}</div>"
// loop through the projects
for(var m in oldMap.data) {
// if the project has a marker type defined
if (oldMap.data[m].marker) {
// point
var point = new google.maps.LatLng(oldMap.data[m].lat, oldMap.data[m].longtd);
// create HTML for info window
var infoHtml = Mustache.to_html(infoWindowTemplate, oldMap.data[m]);
// icon
var icon = new google.maps.MarkerImage(
"images/markers/33px/" + oldMap.data[m].marker + ".png",
new google.maps.Size(33,33)
);
// create a marker for this project
var marker = oldMap.createMarker(point,infoHtml,icon);
}
}
oldMap.drawn = true;
}
}
)
}
},
createMarker : function (latlng, html, icon) {
// create the marker
var marker = new google.maps.Marker({
position: latlng,
icon: icon,
map: map,
zIndex: Math.round(latlng.lat()*-100000)<<5
});
// open info window when marker clicked
google.maps.event.addListener(marker, 'click', function() {
oldMap.infowindow.setContent(html);
oldMap.infowindow.open(map,marker);
});
}
};
First line of your functions directly on the object should be...
function () {
var that = this;
...
}
Then, in your inner functions, swap references to this with that.
This is because inner functions' this points to window.
If you're using jQuery as it looks like you are, take a look at the proxy() method:
http://api.jquery.com/jQuery.proxy/
This method is specifically designed to force the scope of this to a particular object. I personally prefer the syntax of PrototypeJS bind():
http://api.prototypejs.org/language/Function/prototype/bind/
...but much though I prefer PrototypeJS to jQuery, it seems that battle has been fought and lost already.

When a marker lies behind open infobox - Event mouseover with InfoBox plugin Google Maps API v3

I'm having trouble with v3 of the Google Maps API and using the InfoBox plugin specifically with respect to this usability issue use case:
Since my map requires a custom infobox to be opened upon hovering the mouse over each respective marker, when the map has 2 markers on it that are close in proximity, even when/if one of the markers lies behind an infobox that is currently open after hovering the other close-by marker, it is triggered when mousing over it marker (even though it's behind the currently open infobox) and the other infobox obstructs the currently/previously opened infobox
I've followed the question and answer process by another poster here: Google Maps API v3 Event mouseover with InfoBox plugin and have followed the recommended code, but i can't wrap my mind around how to prevent markers that lie BEHIND an open infobox to not be triggered until that infobox is closed.
var gpoints = [];
function initializeMap1() {
var Map1MileLatLang = new google.maps.LatLng(39.285900,-76.570000);
var Map1MileOptions = {
mapTypeControlOptions: {
mapTypeIds: [ 'Styled']
},
mapTypeControl: false,
zoom: 14,
center: Map1MileLatLang,
//mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeId: 'Styled'
};
var Map1Mile = new google.maps.Map(document.getElementById("map_canvas"), Map1MileOptions);
var styledMapType = new google.maps.StyledMapType(styles, { name: 'Styled' });//new
Map1Mile.mapTypes.set('Styled', styledMapType);//new
for ( var i=0; i<5; i++ ) {
gpoints.push( new point(Map1Mile) );
gpoints.push( new point2(Map1Mile) );
}
function popup(_point) {
_point.popup = new InfoBox({
content: _point.content,
pane: 'floatPane',
closeBoxURL: '',
alignBottom: 1
});
_point.popup.open(_point.marker.map, _point.marker);
google.maps.event.addListener(_point.popup, 'domready', function() {
//Have to put this within the domready or else it can't find the div element (it's null until the InfoBox is opened)
$(_point.popup.div_).hover(
function() {
//This is called when the mouse enters the element
},
function() {
//This is called when the mouse leaves the element
_point.popup.close();
}
);
});
}
function point(_map) {
this.marker = new google.maps.Marker({
position: new google.maps.LatLng(39.291003,-76.546234),
map: _map
});
this.content = '<div class="map-popup" style="width:100px;"><div class="map-popup-window"><div class="map-popup-content">Just try to click me!<br/>Hovering over this text will result in a <code>mouseout</code> event firing on the <code>map-popup</code> element and this will disappear.</div></div>';
// Scope
var gpoint = this;
// Events
google.maps.event.addListener(gpoint.marker, 'mouseover', function() {
popup(gpoint);
});
}
function point2(_map) {
this.marker = new google.maps.Marker({
position: new google.maps.LatLng(39.295003,-76.545234),
map: _map
});
this.content = '<div class="map-popup" style="width:100px;"><div class="map-popup-window"><div class="map-popup-content">Just try to click me!<br/>Hovering over this text will result in a <code>mouseout</code> event firing on the <code>map-popup</code> element and this will disappear.</div></div>';
// Scope
var gpoint = this;
// Events
google.maps.event.addListener(gpoint.marker, 'mouseover', function() {
popup(gpoint);
});
}
After doing experimenting, i suspect this issue is irrelevant to z-index... am i correct in understanding this needs to be caught in the javascript?
Any help or advice would be greatly appreciated!
Adding optimized: false attribute for your markers should solve the problem.
this.marker = new google.maps.Marker({
position: new google.maps.LatLng(39.295003,-76.545234),
map: _map,
optimized: false
});

Google Maps JS v3: Map display: none; after map initialization causing corrupted map

This certainly touches on previous questions regarding map display during initialization. Yet the issue here is with map display being set to none after map should have already initialized. The last line of my widow.onload sets the map to display: none; The map initialization should have already completed by that time, but the fact remains, the final call is causing the problem.
window.onload(); function...
window.onload = function(){
changeTheme(me); // do it now so current_theme is avaible to switchTabs();
switchTabs("tab3"); // sets map div visible
initMaps(); // map initialization. code included.
loadFavoritePlaces(); // asynch $getJSON call, adds markers. No matter the condition of map, markers appear in their proper locations.
closePopup("images");
closePopup("location"); // sets maps.mini_map display: none; Problems if we loadUserTable() later. Otherwise OK. Odd!
closePopup("tweet");
centerDiv();
document.title = '#'+me.screen_name+' - PithyTwits.com';
users[me.id_str] = me;
getPage(); // asynch $.getJSON loads tweets. Not an issue.
// Append a scroll event handler to tweet_div
$("#tweet_div").scroll(function() {
var pos = $(this)[0].scrollHeight - $(this).scrollTop();
if(pos != prev_scroll){ // hack to prevent scroll function from firing twice
prev_scroll = pos;
if (pos == $(this).outerHeight()) {
$("#throbber").fadeIn();
getPage();
}
}
});
loadUserTable(me.id_str);
/* loadUserTable(); calls switchTabs("tab1"); which sets map div display: none;
if I comment this out the map initialization completes properly, but my 'tab1'
doesn't get populated properly. And page doesn't start on 'tab1', which is required. */
// end window.onload()
}
initMaps(); function...
function initMaps() {
// markers list
maps.markers = new Object;
// visibility status'
maps.markerStatus = new Object;
maps.markerStatus['query'] = true;
maps.markerStatus['tweet'] = true;
maps.markerStatus['favorite'] = true;
// define marker images
maps.reticleImage = new google.maps.MarkerImage('images/reticle.png',
new google.maps.Size(63, 63),
new google.maps.Point(0,0),
...
Declarations removed to streamline post.
...
new google.maps.Point(0,0),
new google.maps.Point(1, 13));
maps.markerShape = {
type: "poly",
coords: [9,22,16,11,16,5,11,1,6,1,2,5,2,11,9,22]
}
// setup map options
var latlng = new google.maps.LatLng(39.520427, -94.770621);
var latlng2 = new google.maps.LatLng(46.1912, -122.1944);
var myOptions = {
zoom: 3,
center: latlng,
mapTypeId: google.maps.MapTypeId.HYBRID
};
var myOptions2 = {
zoom: 13,
center: latlng2,
disableDefaultUI: true,
draggable: false,
keyboardShortcuts: false,
mapTypeControl: false,
scrollwheel: false,
mapTypeId: google.maps.MapTypeId.HYBRID
};
// initialize maps
maps.main_map = new google.maps.Map(document.getElementById("map_div"), myOptions);
maps.mini_map = new google.maps.Map(document.getElementById("mini_map"), myOptions2);
// default map center markers
maps.mini_map_marker = new google.maps.Marker({
position: latlng2,
map: maps.mini_map,
icon: maps.favoriteMarker,
shadow: maps.markerShadow,
});
maps.reticleMarker = new google.maps.Marker({
position: latlng,
map: maps.main_map,
shape: reticleShape,
icon: maps.reticleImage,
});
// event handlers
google.maps.event.addListener(maps.main_map, 'zoom_changed', mapZoomed);
google.maps.event.addListener(maps.main_map, 'bounds_changed',
function(){maps.reticleMarker.setPosition(maps.main_map.getCenter());});
//idle event listener provided by #Guan in the marked answer.
google.maps.event.addListenerOnce(maps.main_map, 'idle', function() {
var div = document.getElementById("tab3_content");
div.style.display = "none";
div.style.position = "relative";
div.style.left = "0px";
});
// initialize controls
var controls = document.getElementById("visibility_controls");
maps.main_map.controls[google.maps.ControlPosition.TOP_CENTER].push(controls);
controls.style.display = "inline";
var controls = document.getElementById("control_controls");
maps.main_map.controls[google.maps.ControlPosition.RIGHT_CENTER].push(controls);
controls.style.display = "inline";
var controls = document.getElementById("query_controls");
maps.main_map.controls[google.maps.ControlPosition.BOTTOM_CENTER].push(controls);
controls.style.display = "inline";
}
If I call loadUserTable(); at the end of window.onload(); I get this... (munged)
If I don't call loadUserTable(); at the end of window.onload(); I get this... (correct)
Since the problem stems from the maps display being set to none after the maps should have initialized, it would lead one to believe that the map initialization is actually happening non-syncronously. So how do I know when it is finished, and it is safe to hide the maps div? And also there is the question of why the mini_map seems to be dependent on visibility of the main_map, rather than its own visibility? I get the same results in both Chrome and Firefox, on Linux.
Any help is help :)
Skip
UPDATE: I changed the final call to setTimeout("loadUserTable();", 1000); and 1 second is enough of a pause to let things work, but isn't what I want! Since #Jobsz verifies this is known issue, I'm going to resort to off screen initialization, and move the map into position either when needed for display, or hide it and put it in position after a short timeout.
SOLUTION: Provided by #Guan (Checked answer)
I did not want the map visible during initialization. But wanted it initialized and ready when the user chose that tab.
The map div is initially set thus...
id="tab3_content" style="display: block;position: absolute; left: -1000px;"
That makes it visible, but offscreen to the left.
And then set a listener for the idle event in the map initialization...
google.maps.event.addListenerOnce(maps.main_map, 'idle', function() {
var div = document.getElementById("tab3_content");
div.style.display = "none";
div.style.position = "relative";
div.style.left = "0px";
});
That event fires once when the map is idle(ready). It hides the div and moves it into position on screen.
The loadUserTable() function is called in the normal program flow, and life is good. :)
Could you try calling
//map hold's a reference to your current map
google.maps.event.trigger(map, 'resize');
After the map/div containing it becomes visible?
google.maps.event.addListenerOnce(map, 'idle', function() {
$('#addstop').css({
display: 'none',
left: '0',
top: '0'
});
});
This event happens only once after the map is fully loaded and 'idle'
Yup -- I had this same problem.
What I did was trigger the initialization after the event button that displays the hidden map is clicked.
So I have a hidden div, when it's clicked to shown, i display it and then initalize it. Is this doable for what you're trying to achieve? I'm assuming you want performance in that you'd prefer the click to instantly show a populated map -- however it isn't too slow to populate the small area you're tying to if you do it on the click event.
Just this may help you.
I just have an application that uses tabs mixed with gmap divs.
I was fix same problems. Console just show corruption image message. Your ideas help a lot!
I just use this
$("#tab-3").click(function(){
$(".tab-3").removeClass("ui-screen-hidden");
$(".tab-1").addClass("ui-screen-hidden");
$(".tab-2").addClass("ui-screen-hidden");
initializedonationlocation();
})
function initializedonationlocationdr() {
var directionsDisplay = new google.maps.DirectionsRenderer();
geocoder2 = new google.maps.Geocoder();
infowindow2 = new google.maps.InfoWindow();
var myOptions = {
zoom: 10,
center: new google.maps.LatLng(38.7,-121.59),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map2 = new google.maps.Map(document.getElementById('my_map_donation_donationreceipt'),
myOptions);
google.maps.event.addListener(map2, 'click', function(e) {
geocoder.geocode(
{'latLng': e.latLng},
function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
if (marker2) {
marker2.setPosition(e.latLng);
} else {
marker2 = new google.maps.Marker({
position: e.latLng,
map: map2});
}
infowindow2.setContent(results[0].formatted_address);
var postCode = extractFromAdress(results[0].address_components, "postal_code");
var street = extractFromAdress(results[0].address_components, "route");
var town = extractFromAdress(results[0].address_components, "locality");
var country = extractFromAdress(results[0].address_components, "country");
var state = extractFromAdress(results[0].address_components, "administrative_area_level_1");
$("#city_donationdr").val(town);
$("#state_donationdr").val(state);
$("#zip_donationdr").val(postCode);
$("#address_donationdr").val(street);
infowindow2.open(map2, marker2);
// Changing window
var prevSelection3 = $("#tabmap").val();
var newSelection3 = $("#navbar2 ul li").children("a").attr("data-tab-class");
$("."+prevSelection3).addClass("ui-screen-hidden");
$("."+newSelection3).removeClass("ui-screen-hidden");
prevSelection3 = newSelection3;
$("#tabmap").val(prevSelection3);
document.getElementById('geocoding').innerHTML = "";
$("#coords_donationdr").val(e.latLng);
$("#address_donationdr").focus();
GetCurbSideCoordsDR(directionsDisplay,map2);
} else {
document.getElementById('geocoding').innerHTML =
'No results found';
}
} else {
document.getElementById('geocoding').innerHTML =
'Geocoder failed due to: ' + status;
}
});
});
}
I only call initialization only when tab that contain gmap is showed. NOT before. Many forums show gmap initialization at pages loading. In conbination with tabs, just only call initialization after tab appears.

Categories