Embed google map is wrong displayed until resizing webpage - javascript

I am trying to display a map in my webpage to get coordinates from it. It works fine, I can drag and drop a marker and get coordinates in input boxes.
But my problem comes when I load the webpage. Everything is well displayed but the map, here you can see how the map is displayed:
But if in this moment I resize the webpage, I mean, if it was full screen, put it half. Or make it a little big bigger or smaller if it was just a part of the screen. Then, You will see the correct map:
(It is not the same place, I know. I took the image from 2 reloads)
I create the webpage in HTML but I call it as if they were distinct webpages. When you load the index, you get a button with this
href:<a href="#openMap">
And, the part showed will be:
<div data-role="page" id="openMap" data-theme="e">
<div data-role="header" data-id="fixedNav" data-position="fixed">
blablabla
<div data-role="content">
<form action="">
<div id="map_canvas" style="width:500px; height:300px"></div>
blablabla
And all divs, forms... properly closed. I have many input boxes and fields which I haven't put them here.
Then, in my google map script I have this:
var map;
function initializeNewMap() {
var myLatlng = new google.maps.LatLng(43.462119485,-3.809954692009);
var myOptions = {
zoom: 14,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var marker = new google.maps.Marker({
draggable: true,
position: myLatlng,
map: map,
title: "Your location"
});
}
But I have no idea why I need to resize. Is it a way to solve it?
EDIT: I add more info:
I call the part of the webpage which has the map this way:
$(document).on("pageinit", '#openMap', function() {
I tried to put
google.maps.event.trigger(map, 'resize');
just after it but nothing happens.
SOLUTION:
I found the solution in other question (Google Maps v3 load partially on top left corner, resize event does not work, Ian Devlin post):
As one user said here, I need to resize map. But just that line didn't work. I added this code at the end of the initialize function:
google.maps.event.addListenerOnce(map, 'idle', function() {
google.maps.event.trigger(map, 'resize');
});
So it is just called after the map is shown.

I too faced this issue, I solved it by triggering the Google maps resize event.
google.maps.event.trigger(map, 'resize');
Updates:
var map;
function initializeNewMap() {
// add your code
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
google.maps.event.trigger(map, 'resize');
}
Hope you understand.

I had a similar issue but you couldn't see any of the map (the entire box was grey).
What solved it for me was realising that the div that contained the map was starting off as hidden using
display:none;
If you instead use
visibility:hidden;
The div retains its size while still appears as hidden, so the map when initialised uses its correct height and width, rather than 0 values
Hope this helps!

If you use JavaScript-based layout helpers (such as Foundation Equalizer) you need to ensure that the map container has the definitive size before you load the map so you don't get the infamous grey map and certain attributes like center work as expected—or use the third-party plug-in's events to trigger a custom callback that fixes the map. E.g.:
var map = new google.maps.Map(/*...*/);
$(document).on("after-height-change.fndtn.equalizer", function(){
google.maps.event.trigger(map, 'resize');
});

My map was hidden in a Twitter Bootstrap tab, and so wasn't visible when the map initialised, so I needed to call resize when the tab was selected like so:
$('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
google.maps.event.trigger(map, 'resize');
})

How it should be fixed:
You must have to initialize the map after the container (where you place the map) get's visible,
Remember that loading and visibility is not same, you need visibility.
Like, I have many tabs & last tab contains the map,
I fixed this issue by:
$('#map-tab').click(function() {
// init map
});
Here, I first making sure that the container gets visibility (as clicking that element reveals the section contains the map) then initialized the map
This worked fine for me;

Related

Google Map Api: Map Greyed Out The First Load and The Greyed Area Cannot Load

I have a super weird problem with google map. There is no error on the console, but every time the map loads, it shows only grey box with all the tools are shown.
The bottom-right tools are shown, but there are no icons (icons are not showing, only the white boxes).
If I move the map to the left, All the left areas are loaded well, but if I move it to the right, the right to the initial position and so, the greyed area are still greyed, the map does not rendering the initial position area and to the right.
If zoom out the map, I can see there is a straight line border from north pole to south pole dividing the are which are rendered well (the left side from my initial position) and the right side (my initial position and to the right of it).
Is this a bug? How to fix this?
I tried to call "resize" event to the map, but the problem still persist.
Here are the codes:
Razor:
var googleMapSrc = #"https://maps.googleapis.com/maps/api/js?key=" + #ETrackerUser.ETrackerUserConfig._MapApiKey.Trim() + #"&callback=initMap";
The Html:
<div id="mapContainer" style="width:100%; height:100%">
</div>
Script:
<script type="text/javascript">
var locations = JSON.parse($('#CoordinatesModel').val());
var geocoder;
var map;
function initMap() {
setTimeout(function () {
var html = '<div id="map" style="height:600px;"></div>';
$('#mapContainer').html(html);
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
center: {lat: -25.363, lng: 131.044},
mapTypeId: google.maps.MapTypeId.ROADMAP
});
google.maps.event.addListener(map, "idle", function () {
google.maps.event.trigger(map, 'resize');
});
}, 2000);
setTimeout(function () {
google.maps.event.trigger(map, 'resize');
map.setZoom(map.getZoom());
}, 5000);
}
</script>
<script async defer src="#googleMapSrc"></script>
Images:
Initial Load:
Move to the left of initial load:
Zoomed Out:
Note:
I even try to use simple map example code and it still produce the same error.
Found the problem
This is very very stupid. When I use Internet Explorer, everything is fine. Currently my default browser is google chrome. Google chrome messed up this google map (so weird and so stupid).
I do not know if this is a bug or there is something wrong with my chrome configuration.
If someone know the problem, help me.
For now I am just gonna using Internet Explorer.
Ok there was something wrong with my site css. The img should have max-width: none !important only for the page.

Google Maps Not Loading Image and Marker

This is my gmaps avscript code, i print maps as many as my data database, these gmaps are inside at collapsed div:
var maps = {!! $maps !!};
var googlemaps = [];
$.each(maps, function( key, item ) {
googlemaps[key] = new GMaps({
div: '#gmaps-' + key,
lat: item.latitude,
lng: item.longitude,
width: '100%',
height: '100%',
});
googlemaps[key].addMarker({
lat: item.latitude,
lng: item.longitude,
width: '100px',
draggable: false,
title: 'Marker'
});
googlemaps[key].setCenter( item.latitude, item.longitude );
googlemaps[ key ].setZoom( 15 );
});
The div by default is collapsed, after i open the div and show the gmaps, it's just showing blank grey maps, i try drag my map to search my marker, it only view a little part of the gmaps panel at the top left.
after i resize my browser the marker finaly can drag to center of panel but still grey.
I zoomed out/in and the image loaded, the image only loaded when i zoom in and out.
I really confused searching so many answer but not solving my problem.
Please help me..
When the map div, or it's parent, or it's parent parent (any predecessor) has display:none style, and you create the map, the map view won't initialize properly. You have to trigger resize event on map for it to reinitialize the map view.
In GMaps the google.maps.Map object is accessible using .map attribute, so your code will have to look something like this:
google.maps.event.trigger(googlemaps[key].map, "resize");
Remember to trigger it AFTER the div is visible. To be sure you can put the resize trigger into a timeout, when they click the div to display.
Side note: I am not sure if you are aware, but every map you create is a separate API call so to have multiple maps results in lot of separate API calls and if you don't have maps for business license you can hit limits pretty fast.

google maps v3 appears distorted and doubled

This code works perfectly on jsfiddle and any other JavaScript sandbox app, but it doesn't work on my website.
HTML :
<div id="mapcontainer" style="position:absolute;width:280px;height:160px;"></div>
JS :
<script src="http://maps.googleapis.com/maps/api/js?key=*********************************&sensor=false"></script>
<script>
var myCenter = new google.maps.LatLng(33.436150, -117.623090);
function initialize() {
var mapProp = {
center: myCenter,
zoom: 9,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("mapcontainer"), mapProp);
var marker = new google.maps.Marker({
position: myCenter,
});
marker.setMap(map);
google.maps.event.trigger(map, 'resize')
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
It looks like this:
Notice how the top 2/3 is distorted and the bottom 1/3 is fine. How can I fix this?
It seems there must be some other problem in code.
Your google maps code looks perfect, I have made a fiddle to show the difference.
From your script it seems you're using key for google maps. I think that is not necessary in v3. so try replacing it as shown below.
<script src="http://maps.google.com/maps/api/js?sensor=false"></script>
I stumbled over this page after I had the same problem myself on a google map I was developing. The solution I came up with was to add the following code after the google map javascript.
$(window).resize(function(){ initMap(); });
The "initMap();" part is so it just refreshes the map function. If you named the function something different that is what you need to use.
Ultimately I realize this is a patch to the problem. But it works like a charm and is barely noticeable to the end user. All you are doing is refreshing the map function when you resize the window.
I figured out a similar issue due to the solution to this problem in comments.
It was a case of looking at one of the images in the map with a css debugger and seeing if it was affected by any other styles on the page

Place the Google Maps pegman underneath markers

I have a Google V3 map which uses steetView and some map markers.
The little yellow streetView pegman sits on the map on top of the markers.
Is there a way to change the z-indexes so that my markers will be above the pegman
(so that they can be easlly clicked on without having to zoom in)?
In case anything is not clear, here is a fiddle....
http://jsfiddle.net/spiderplant0/BRkCA/
After a bit of experimenting I came up with this...
$("#map_canvas img[src*=cb_scout]").parent("div").css({'zIndex': -200});
$($("#map_canvas img[src*=cb_scout]")[1]).parent("div").parent("div").css({'zIndex': -200});
This forces the pegman to sit beneath the markers but now the pegman is no longer dragable and each time the map is moved etc, the pegman jumps above the markers again.
To keep the pegman under your markers you can watch for the pov_changed event and reset the z-index after a short delay
$google.maps.event.addListener(panorama, 'pov_changed', function() {
var func=function(){
$("#map_canvas img[src*=cb_scout]").parent("div").css({'zIndex': -200});
}
setTimeout(func,1000);
}
});
You will also need to change the depth of the pegman after the maps moves, which can be accomplished with the following snippet
google.maps.event.addListener(map, 'idle', function() {
google.maps.event.trigger(panorama, 'pov_changed');
})
If you want to be able to drag the pegman, you must first place it above the markers by having a toggle button swap the pegman's depth and add an exception to the pov_changed event handler preventing the pagman from dropping depths when the toggle button is active.
Okay, this may be a bit hacky... (and I hope I understood what you were doing)
1) Disable street view control
2) Make another control with a lower zIndex than the marker you have.
3) Update street view control with the position of the fake street view marker.
http://jsfiddle.net/z7Lp8/
You can set the zIndex of the marker above google.maps.Marker.MAX_ZINDEX in order for the pegman to remain under the marker. MAX_ZINDEX is the maximum default z-index that the API will assign to a marker. Marker z-indexes only work when optimizations are turned off on all markers on the map.
Forked fiddle from question to illustrate: http://jsfiddle.net/brendaz/t4v8nhoq/
var marker1 = new google.maps.Marker({
position: new google.maps.LatLng(54.975, -2.020),
map: map,
zIndex: google.maps.Marker.MAX_ZINDEX + 1,
optimized: false
});

Google map generating incorrectly

I have a program that takes in a zip code and makes a google map. The div that the map is set tohidden until the map is made. Once the map is made the div is set to display : block. The problem is that the first time the map is generated (and only the first time) it looks like this:
Once I hit the find a store button again it looks like this:
I have already tried to make a initial call to the map method (which I kept hidden until a real call is made) but this does not fix the issue. I don't want to show all my code (there is a lot) but here is how I make the map.
<div id = "map_canvas" style = " height: 300px; width: 300px;"></div>
//Creates a new center location for the google map
var latlng = new google.maps.LatLng(lat, lng);
//The options for the google map
var mapOptions = {
zoom: 7,
maxZoom: 12,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
//Creates the new map
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
Also note that both images below have the correct markers in the correct place.
Any suggestions?
this is a common problem. you need to trigger a map redraw after changing the container. most of the time this is caused by showing/hiding the div.
in v3 it's:
google.maps.event.trigger(map, 'resize')
in v2 it's:
map.checkResize()
It looks like when you initialize the map, it is completely zoomed out, which brings out the single 250x250 tile that google uses.
I would suspect that possibly an error is occurring on your first "Find Store" button click that might prevent the map creation code from being reached and executing properly.

Categories

Resources