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
Related
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.
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;
Our code starts with live function and whole page content is created by js live function,below code used for creating google maps within javascript code, for the first creation everything is fine (map seems correctly on screen) but after that time when google map is created again at the same page half of the map comes up and half is grey, that is our problem.
JQuery version 1.8.0
Bootstrap version 2.2.2
var idz = 'mapg';
tr.append($('<td>').append($('<div>', {
'id': idz,
'style': 'width: 100%; height: 300px'
})));
var latlng = new google.maps.LatLng(40.988921, 29.021326);
var options = {
zoom: 10,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
rootMap = new google.maps.Map(document.getElementById(idz), options);
I would appreciate any help with this issue, thanks in advance.
I too had the same problem, I solved it by triggering the resize of Google maps.
Here is the below code:
google.maps.event.trigger(rootMap , 'resize'); //For v3
Add this after initializing the Google maps.
You can take a look at this SO Question.
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.
I'm developing a jQTouch-based app for the iPhone and part of it uses the Google Maps API (V3). I want to be able to pass the geolocation coordinates to the map and have it center the location with a marker. What I'm getting now is the map at the proper zoom level but the desired center-point appears in the upper-righthand corner. It's also showing only about a third of the map area (the rest is gray) and it behaves somewhat erratically when you pan or zoom. Here's the code:
var coords = { latitude : "35.510630", longitude : "-79.255374" };
var latlng = new google.maps.LatLng(coords.latitude, coords.longitude);
var myOptions = {
zoom: 12,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map($("#map_canvas").get(0), myOptions);
var marker = new google.maps.Marker({
position: latlng,
map: map,
});
BTW: It looks and behaves the same on other platforms/browsers as well.
Thoughts?
Thanks in advance,
Mark
Added
Here's a link that'll show exactly what's happening:
Screen shot of iPhone emulator
I'm guessing you're using AJAX to display the map, or have the map hidden at some point and then display it based on an action?
In this case Google doesn't know the size of the map container and it will draw only part of the map, usually off-centered.
To fix this, resize the map, then re-center on your lat/lng. Something like this:
google.maps.event.trigger(map, 'resize');
// Recenter the map now that it's been redrawn
var reCenter = new google.maps.LatLng(yourLat, yourLng);
map.setCenter(reCenter);
The solution for getting the map renedered correctly is to execute your Maps-Code on pageAnimationEnd-Event of jQTouch.
Example within Page #div:
<div id="map_canvas" style="width:100%; height:100%; min-height:400px; background:#ccc;"></div>
<script type="text/javascript">
$('#map').bind('pageAnimationEnd', function() {
var mapOptions = {
zoom: 13,
disableDefaultUI: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = new google.maps.LatLng(position.coords.latitude, position.coords.longitude)
var marker = new google.maps.Marker({
map: map,
draggable: false,
position: pos
});
map.setCenter(pos);
}, function() {
console.log('Device Environment Capable of Geolocation but not Available - Geolocation failed');
}
);
} else {
console.log('Device Environment Not Capable of Geolocation - Geolocation failed');
}
});
</script>
Though, i find myself having trouble to make the Map fullscreen-height. Any help in this case is appreciated. Note that im using DataZombies bars extension for fixed footer navigation.
see my answer on Google Maps API 3 & jQTouch
basically, your #map_canvas div is not visible at the time you're constructing the map as the div it's in has been hidden by jqtouch. the api can't deal with this and get's the size wrong.
would be much easier if gmaps v3 allowed setting explicit size in the constructor (as v2 did).
anyway, delay constucting map until 'pageAnimationEnd'.
Make sure you have set the width/height of the canvas absolutely (i.e.)
$("#map_canvas").width(window.innerWidth).height(window.innerHeight - $('.toolbar').height());
Of course that assumes you have the jqtouch toolbar up and running...
Had the same exact issue loading a map with directions after loading content with AJAX and showing and hiding the map-canvas div.
You have to trigger the resize event, like Brett DeWoody says, but I found that my global variable went out of scope and I had to refer to them, i.e. the google map variable, INSIDE my functions explicitly on the window object. Here's what I have inside my directionsService response:
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
google.maps.event.trigger(window.map, 'resize');
}
Brett DeWoody's solution worked, but as I'm showing the map in modal the only solution for me was to add setTimeout like this:
setTimeout(function() {
google.maps.event.trigger(map, 'resize');
var reCenter = new google.maps.LatLng(lat, lng);
map.setCenter(reCenter);
}, 500);
After adding setTimeout the map renders and centers perfectly.