GoogleMaps API working only when dev tools is open - javascript

Hey I am trying to have a map in my project. I got my API_KEY from google for GoogleMaps... I have no error in console but map doesnt display anything, till I open developers tools on google Chrome...
2
After that is working but marker is in work palce.. Still no errors in console.
WHat am I doing wrong?
Style:
#map {
width: 100%;
height: 300px;
background-color: grey;
}
Code:
<div id="map"></div>
<script>
function initMap() {
var myLatLng = {lat: -0.250608, lng: 52.025528};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: myLatLng
});
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
title: 'Title!'
});
}
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=MYKEY&callback=initMap">
</script>

You are init-ing the map in a container that is not visible/has no dimensions.
Opening dev tools triggers a resize on your browser which causes the map to resize itself.**
You can fix it by either:
either waiting to init the map until it's container is visible
or calling google.maps.event.trigger('resize',map) (where map is an
instance of the map) when your container becomes visible.
** Proof that this is what's happening: undock your dev tools so it's a floating window. Then refresh your page (with dev tools closed) and open dev tools again after you fail to see the map, it still won't be visible because your browser never resized (because your dev tools is floating and not docked)

Have you made sure to register your URL / domain with Google for the use of the Maps API? https://developers.google.com/maps/premium/previous-licenses/clientside/auth#register-urls

Related

Google Map API marker not appearing on map on mobile

I am using Google Map Javascript API with marker clustering and InfoBox on a Laravel Website
https://developers.google.com/maps/documentation/javascript/marker-clustering
The native red marker shows properly on desktop but doesnt appear on mobile.
However if i click at the location where it should be, my infobox does appear and everything else if ok.
Is there a special setting to be taken into account (as maybe the png used for this marker on mobile display or else?)
<!DOCTYPE html>
<html>
<head>
<style>
/* Set the size of the div element that contains the map */
#map {
height: 400px; /* The height is 400 pixels */
width: 100%; /* The width is the width of the web page */
}
</style>
</head>
<body>
<h3>My Google Maps Demo</h3>
<!--The div element for the map -->
<div id="map"></div>
<script>
// Initialize and add the map
function initMap() {
// The location of Uluru
var uluru = {lat: -25.344, lng: 131.036};
// The map, centered at Uluru
var map = new google.maps.Map(
document.getElementById('map'), {zoom: 4, center: uluru});
// The marker, positioned at Uluru
var image = 'https://developers.google.com/maps/documentation/javascript/examples/full/images/beachflag.png';
var marker = new google.maps.Marker({position: uluru, map: map,icon: image});
}
</script>
<!--Load the API from the specified URL
* The async attribute allows the browser to render the page while the API loads
* The key parameter will contain your own API key (which is not needed for this tutorial)
* The callback parameter executes the initMap() function
-->
<script async defer
src="https://maps.googleapis.com/maps/api/js?callback=initMap">
</script>
</body>
</html>
After checking, it was not related to Google Map but to my server .env environment file (I am using Laravel)
APP_URL variable was refering to 'localhost' in .env file and this APP_URL variable was used in Javascript code (using PHP-Vars-To-Js-Transformer) for retrieving some server img ressources:
This caused on desktop the ressources to be properly loaded on google map api but not on mobile.
Replacing localhost by my website url in .env file solved the issue.

Google Maps Controls panel size is displayed wrong

I have a weird problem with Google Maps Control.
I've tested in a blank page my custom maps with custom markers and everything seems to be ok, also with the control panel.
When I tried to import all my code in the page I'm working with ( I use a full screen fluid grid system ) the control panel is displayed with strange size.
I tried everything for disable/enable the ui of the Google Maps but the problem remain.
The code of my maps are exactly the same, both in my blank page and in my site, but in the site the ui control panel is displayed very strange.
Here's the code:
<div id="map_canvas2" style="height: 580px; width: 100%;"></div>
<script>
var image = 'path/to/your/image.png';
var mapOptions = {
zoom: 17,
center: new google.maps.LatLng(45.499290, 12.621510),
mapTypeId: google.maps.MapTypeId.ROADMAP,
scrollwheel: false
}
var map = new google.maps.Map(document.getElementById('map_canvas2'), mapOptions);
var myPos = new google.maps.LatLng(45.499290,12.621510);
var myMarker = new google.maps.Marker({position: myPos, map: map, icon: 'http://www.factory42.it/jtaca/wordpress/wp-content/uploads/2014/06/pin-map.png' });
</script>
</div>
Here's an img:
http://www.factory42.it/jtaca/wordpress/wp-content/uploads/2014/06/img-maps.png
there is a global rule on images style that is applied on your page
Are you including the same .css files ?
Is your page accessible online? Otherwise, you can inspect your image yourself from your favorite console debugger and see what styles are applied on it You can try removing them one by one to detect your problem

Half grey google map while dynamically creating it for more then once with javascript live function

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.

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

Google Map V3 not centering, displays only part of map

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.

Categories

Resources