Google Maps idle event not firing - javascript

I'm doing some experimentation with Google maps, and my aim is to place markers on a map which will depend on when it is dragged or resized, so I'm planning to use the "idle" event listener. The problem is that I can't get it to work.
I've put an alert box inside the idle listener to test it, but it doesn't get fired.
This is what I have so far:
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=true"></script>
<script>
var map;
var geocoder;
var markers = [];
function initialize()
{
var myOptions = {
center: new google.maps.LatLng(<?php echo $latitude; ?>, <?php echo $longitude; ?>),
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP,
panControl: true,
zoomControl: true,
scaleControl: true
};
map = new google.maps.Map(document.getElementById('map_canvas'), myOptions);
//regenerateMarkers(); // 29/7/15
}
// Initializes the Google Map
google.maps.event.addDomListener(window, 'load', initialize);
google.maps.event.addListener(map, 'idle', function() {
//regenerateMarkers(); // 29/7/15
alert("inside idle");
});
</script>
The html to display the map is as follows:
<div id="map_canvas" style="height: 450px; width: 900px;"></div>
I cannot for the life of me see why the idle listener is not firing to bring up the alert box. Can anyone please help? Many thanks!

You should bind idle event inside initialize function otherwise map couldn't be already loaded and event can't be bound.

Related

Google Map API use LatLng or Address

I'm using Javascript to render an embedded Google Map canvas on my website.
The inputs to the rendering are lat/lng coordinates that are retrieved from a database. However, if lat/lng returns null, the map will render based on the corresponding address string retrieved from the database. The following script always renders correctly for lat/lng coordinates inputs, but doesn't work for address input. Strangely, when I refresh the page multiple times, the address input would work randomly. I'm trying to cut out this randomness. Think I'm pretty close but I can't seem to find the missing link.
Note: if lat/lng is null, a default value is applied to $lat and $lng so it doesn't mess up the JS below.
I would appreciate if anyone could tell me what's wrong with the below code that's causing the random rendering of address strings.
var map;
var marker;
var geocoder;
function initialize() {
var mapCanvas = document.getElementById('map-canvas');
var estLatLng = new google.maps.LatLng( <? php echo $lat; ?> , <? php echo $lng; ?> );
var mapOptions = {
center: estLatLng,
zoom: 17,
mapTypeId: google.maps.MapTypeId.ROADMAP,
disableDefaultUI: false,
streetViewControl: true,
scrollwheel: false
}
map = new google.maps.Map(mapCanvas, mapOptions);
marker = new google.maps.Marker({
position: estLatLng,
map: map,
draggable: false,
animation: google.maps.Animation.DROP,
title: "<?php echo $name;?>"
});
}
function toggleBounce() {
if (marker.getAnimation() != null) {
marker.setAnimation(null);
} else {
marker.setAnimation(google.maps.Animation.BOUNCE);
}
}
google.maps.event.addDomListener(window, 'load', initialize);
<? php
} ?>
$(".navbar").load("navbar.html", function() {
$("#navbarrestaurants").addClass("active");
});
$(document).ready(function() { <? php
if ($calcAddress) { ?> // this chunk of code is not loaded if lat/lng is not null
geocoder = new google.maps.Geocoder();
geocoder.geocode({
'address': "<?php echo $address;?>",
'componentRestrictions': {
country: 'Singapore'
}
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
}); <? php
} ?>
});
I believe your problem is that the code in $(document).ready is being executed before that in your initialize function (listening for window load). The load event is called once the page is completely loaded, including images, etc, while everything in your document ready block is called slightly earlier when the DOM is ready.
Because it is executed sooner, and acting upon variables like map, that haven't been set up yet by the initialize function, the code in your geocoding callback is probably causing errors when it tries to alter the map center and set marker coords.
Try executing your geocoding code after the map is initialized. ie: wrap it in its own function and call it at the end of the initialization function.
function initialize() {
var mapCanvas = document.getElementById('map-canvas');
var estLatLng = new google.maps.LatLng( <? php echo $lat; ?> , <? php echo $lng; ?> );
var mapOptions = {
center: estLatLng,
zoom: 17,
mapTypeId: google.maps.MapTypeId.ROADMAP,
disableDefaultUI: false,
streetViewControl: true,
scrollwheel: false
}
map = new google.maps.Map(mapCanvas, mapOptions);
marker = new google.maps.Marker({
position: estLatLng,
map: map,
draggable: false,
animation: google.maps.Animation.DROP,
title: "<?php echo $name;?>"
});
codeAddress();
}
ex: http://jsfiddle.net/j7pb7w3d/2/
This isn't great however, as the map starts with its default center, then visibly jerks a second later to the new address.
Instead you could determine whether or not geocoding is necessary first, and do this before the map is loaded, then use the result to set the map center and marker when the map is first created. Ex: http://jsfiddle.net/qsefxu5q/2/
Note these examples are hardly perfect and will need to be changed for your purposes. Hopefully they give you some ideas.

Google Maps API: Trying to drop multiple markers using an array

I'm not sure what is wrong with my code, but this is what I have so far:
<script type="text/javascript">
function initialize() {
var locations = [
['Passage Island', 49.343085, -123.305938],
['Point Atkinson', 49.329925, -123.264994]
];
var mapOptions = {
center: new google.maps.LatLng(49.343085, -123.305938),
zoom: 13,
mapTypeControl: false,
panControl: false,
streetViewControl: false,
zoomControl: false,
disableDoubleClickZoom: true,
};
var map = new google.maps.Map(document.getElementById('map'),
mapOptions);
var marker, i;
for(i=0; i < locations.length; i++){
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map
});
}
google.maps.event.addDomListener(window, 'load', initialize);
}
</script>
Before I tried using the array to drop markers, I was able to load up the map with markers. But each marker was var marker = new google.maps.Marker({.... so I figured that I should be using arrays if I want to do more than one marker. And now since I have started trying to use arrays, the map won't even load to begin with. Any help would be appreciated!
You shouldn't include this line: google.maps.event.addDomListener(window, 'load', initialize); inside a function if it is not being called on load. Your code is fine except that you called the initialize function from within itself , hence it's not getting called at all.
Place google.maps.event.addDomListener(window, 'load', initialize); outside the function.
Demo: http://jsfiddle.net/lotusgodkk/pGBZD/160/
I think you have written google.maps.event.addDomListener(window, 'load', initialize); statement inside your initialize() function. You should write it outside.

map click event is not being triggered

Update at the bottom
Although the map does appear, the alert inside the click function below is not appearing when I click on the map. The cursor looks like a hand, not like a pointer, by the way. The console.log() result does appear in the browser log.
My goal is to determine the position of the click and place a draggable marker there, but I cannot even get the listener to trigger.
The code below runs without the
// == Display the map, with some controls and set the initial location
var start = new google.maps.LatLng({{center_lat}},{{center_lng}});
var map = new google.maps.Map(document.getElementById("map-canvas"),{
center: start,
zoom: {{map_zoom}},
mapTypeId: google.maps.MapTypeId.ROADMAP
});
console.log("HERE");
google.maps.event.addListener(map,'click',function(){
alert('You clicked the map.');
});
I have constructed the minimal code below to demonstrate my problem. However the code only works without the phrase google.maps.event.addListener(map, 'click', function() {}. When that phrase is included I get the error as follows Uncaught ReferenceError: map is not defined click:24 (anonymous function)
I hope this helps.
<!DOCTYPE html>
<html>
<head>
<script src="//maps.googleapis.com/maps/api/js?sensor=false"
type="text/javascript"></script>
<style type="text/css">
html, body, #map-canvas { height: 100%; margin: 0; }
</style>
<script type="text/javascript">
function initialize() {
var map = new google.maps.Map(
document.getElementById('map-canvas'), {
center: new google.maps.LatLng(37.4419, -122.1419),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var marker = new google.maps.Marker({
position: new google.maps.LatLng(37.4419, -122.1419),
map: map
});
}
google.maps.event.addListener(map, 'click', function() {
alert('You clicked the map.');
});
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas"></div>
</body>
</html>
I get Uncaught ReferenceError: map is not defined in the javascript console.
Because your map variable is not defined. You need to initialize the click listener inside the initialize function where the map is defined (it is local to the initialize function).
function initialize() {
var map = new google.maps.Map(
document.getElementById('map-canvas'), {
center: new google.maps.LatLng(37.4419, -122.1419),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var marker = new google.maps.Marker({
position: new google.maps.LatLng(37.4419, -122.1419),
map: map
});
google.maps.event.addListener(map, 'click', function() {
alert('You clicked the map.');
});
}
google.maps.event.addDomListener(window, 'load', initialize);
working fiddle
fiddle that exhibits error

Google Map API inside a Reveal Modal not showing fully

I am having problems with a Google Map that I have inside a div, which upon button click, pops up on screen. The Google Map is only partially showing. I know that I need to that I need to create a resize event, but do not know how, or where to put it. Any help would be much appreciated! Please keep in mind that I have little knowledge of JS!
Link to test site: CLICK ON GOOGLE MAP BUTTON TO SEE THE PROBLEM AT HAND:
http://simplicitdesignanddevelopment.com/Fannie%20E%20Zurb/foundation/contact_us.html#
My Google API script:
<script type="text/javascript">
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(39.739318, -89.266507),
zoom: 5,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
}
</script>
The div which contains the map:
<div id="myModal" class="reveal-modal large">
<h2>How to get here</h2>
<div id="map_canvas" style="width:600px; height:300px;"></div>
<a class="close-reveal-modal">×</a>
</div>
The script which calls the map upon button click:
<script type="text/javascript">
$(document).ready(function() {
$('#myModal1').click(function() {
$('#myModal').reveal();
});
});
</script>
Following Two solutions worked for me
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(39.739318, -89.266507),
zoom: 5,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
return map;
}
<div id="myModal" class="reveal-modal" data-reveal>
<div id="map_canvas" style="height: 300px"></div>
<a class="close-reveal-modal">×</a>
</div>
$(document).ready(function() {
var myMap;
$('#myModal').bind('open', function() {
if(!myMap) {
var myMap = initialize();
setTimeout(function() {
google.maps.event.trigger(myMap, 'resize');
}, 300);
}
});
}
OR
$(document).ready(function() {
var myMap;
$('#myModal').bind('opened', function() {
if(!myMap) {
var myMap = initialize();
google.maps.event.addDomListener(window, 'load', initialize);
}
});
});
First, based on the source linked to, the script which calls the map upon button click is doing nothing but throwing an error because you have it in the page before jQuery is loaded. You can see it in the error console. You need to move that to the bottom of the page after the rest of the scripts.
Your reveal is "working" because you are using the data-reveal-id attribute on the menu item and the reveal script wires it up automatically.
You are creating the map onload which is bad practice. Don't create it until/unless it is needed.
So to fix your issue, this is what I did. Remove the data-reveal-id from the menu item and replace it with an ID, or you can just use some other selector to access it. I changed it to id="myModal1" since that is what you had in your event code already.
Move your script which calls the map upon button click to the bottom, and change it to look like this:
$(document).ready(function() {
var map;
$('#myModal1').click(function() {
if(!map){
var mapOptions = {
center: new google.maps.LatLng(39.739318, -89.266507),
zoom: 5,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
}
$('#myModal').reveal();
});
});
This will create the map only when the user clicks the link to show it and only creates it once. That should fix it for you. If you have to, you can pass an opened callback to the reveal() call and trigger resize there but in my limited testing it was not necessary.
You can also get rid of the entire initialize function.
Now go get a band-aid and put some ice on that head.
Removing width: 600px; on the <div id="map_canvas"> and triggering resize on your map after opening the modal should do the trick:
$(".reveal-modal").on("reveal:opened", function(e) {
google.maps.event.trigger(map, 'resize')
});
Try this
<script type="text/javascript">
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(39.739318, -89.266507),
zoom: 5,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
}
$( document ).bind( "pageshow", function( event, data ){
google.maps.event.trigger(map, 'resize');
});
</script>
$("#myModal").on('shown.bs.modal', function(){
google.maps.event.trigger(map, 'resize')
});

Google Maps API V3 not rendering competely on tabbed page using Twitter's Bootstrap

I'm using Twitter's Bootstrap for defining my CSS. I have made a page with three tabs. The second tab contains a map built with Google Maps. However when opening the page and switching to the second page with the map, the map is not rendered completely. Once I reload the page with the google maps tab as the selected tab the map loads entirely.
I read some posts that advised people with the same problem to add the following code to the javascript:
google.maps.event.addDomListener(window, 'resize', function() {
map.setCenter(homeLatlng);
});
However this doesn't seem to be the solution. Please find the complete code below:
Javascript:
<script type="text/javascript">
function initialize() {
google.maps.event.addDomListener(window, 'resize', function() {
map.setCenter(homeLatlng);
});
var myLatlng = new google.maps.LatLng(37.4419, -122.1419);
var myOptions = {
zoom: 13,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
downloadUrl("data.xml", function(data) {
var markers = data.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var latlng = new google.maps.LatLng(parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var marker = new google.maps.Marker({position: latlng, map: map});
}
});
}
</script>
HTML:
<div class="tab-pane" id="orange" style="background-color:#E3F2FF;">
<div id="map_canvas" style="width:780px; height:400px; overflow:;"></div>
</div>
How can I resolve this? Maybe I can add some javascript that reloads the google maps part once the tab is selected but I don't know how to do this....
Updated code still shows the error:
<div class="tab-pane" id="orange" style="background-color:#E3F2FF;">
<div id="map_canvas" style="width:780px; height:400px; overflow:;"></div>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript" src="util.js"></script>
<script type="text/javascript">
function initialize() {
google.maps.event.addDomListener(window, 'resize', function() {
map.setCenter(homeLatlng);
});
var myLatlng = new google.maps.LatLng(37.4419, -122.1419);
var myOptions = {
zoom: 13,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
downloadUrl("data.xml", function(data) {
var markers = data.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var latlng = new google.maps.LatLng(parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var marker = new google.maps.Marker({position: latlng, map: map});
}
});
map.checkResize();
}
</script>
</div>
I was battling with this issue as well. I was using a modal form and it rendered the map when it was hidden. When the tab is shown, you need to trigger this code:
google.maps.event.trigger(map, 'resize');
map.setZoom( map.getZoom() );
Hopefully it will work for you. If that doesn't work, here is the link where I found the solution. Maybe there will be another helpful comment.
http://code.google.com/p/gmaps-api-issues/issues/detail?id=1448
There's a lot of solutions here and frankly they're all wrong. If you have to hi-jack the default functionality of Bootstrap tabs, you might as well not use Bootstrap tabs. If you're only calling resize after the tab is shown, you may still have issues with the GMaps interface (zoom level and such). You simply have to initialize the map after the tab is visible.
var myCenter=new google.maps.LatLng(53, -1.33);
var marker=new google.maps.Marker({
position:myCenter
});
function initialize() {
var mapProp = {
center:myCenter,
zoom: 14,
draggable: false,
scrollwheel: false,
mapTypeId:google.maps.MapTypeId.ROADMAP
};
var map=new google.maps.Map(document.getElementById("map-canvas"),mapProp);
marker.setMap(map);
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(contentString);
infowindow.open(map, marker);
});
};
$('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
initialize();
});
You can see a working example in this bootply: http://www.bootply.com/102241
Note: if your interface is still glitchy, it could be this issue:
Google Maps API V3 : weird UI display glitches (with screenshot)
Using the most recent gmaps api, you just need to add this to your styling:
.gm-style img { max-width: none; }
.gm-style label { width: auto; display: inline; }
Works for me after testing different delays :
$(window).resize(function() {
setTimeout(function() {
google.maps.event.trigger(map, 'resize');
}, 300)
});
Hope it helps.
I have solved the problem by using
google.maps.event.trigger(map, 'resize');
inside show function in bootstrap-tab.js means at the time of showing the box you should trigger resize event and will work..
Edit: I have seen another link with the same answer
Google Maps API v3, jQuery UI Tabs, map not resizing
I have seen this link after solving the problem to find out the reason which is still unanswered that why resize event does not works on the click event of the tabs but works in the tab js
this works fine for me, I use jquery tabs
setTimeout(function() {
google.maps.event.trigger(map, "resize");
map.setCenter(new google.maps.LatLng(default_lat, default_lng));
map.setZoom(default_map_zoom);
}, 2000);
from this link https://code.google.com/p/gmaps-api-issues/issues/detail?id=1448
To show a google maps in a hidden div, the div must show before the map is created and loaded. Below is an example:
<div id="map_canvas" style="width:500px; height:500px"></div>
<script>
$(document).ready(function(){
$('#button').click(function() {
$('#map_canvas').delay('700').fadeIn();
setTimeout(loadScript,1000);
});
});
function initialize() {
var title= "Title";
var lat = 50;
var lng = 50;
var myLatlng = new google.maps.LatLng(parseFloat(lat),parseFloat(lng));
var myOptions = {
zoom: 8,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var marker = new google.maps.Marker({
position: myLatlng,
title:artTitle
});
// To add the marker to the map, call setMap();
marker.setMap(map);
}
function loadScript() {
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "http://maps.google.com/maps/api/js?sensor=false&callback=initialize";
document.body.appendChild(script);
}
</script>
For me, what it worked was to call the function that renders the map after the, in my case, the modal had shown.
All I had to do was:
$(document).on("shown", "#eventModal", function(){
bindMap(coordinates);
});
You can do the same with the tabs, because they also have a "shown" event.

Categories

Resources