Using Google Maps Javascript V3, I have a map set up with some markers. I have a listener on each marker that pops up an InfoWindow on a click event. This works just fine. The problem is when I click on any link on the page and then browse back to the original page, the InfoWindows stop displaying. I have put in alert statements in the listener, so I know the listener is running, but I cannot figure out why the InfoWindows are not showing up.
Here is my code:
<script type="text/javascript">
var map;
var viewable;
var markerArray = new Array();
var infoWindow;
function initialize() {
infoWindow = new google.maps.InfoWindow({ content: "holding..." });
var mapOptions = {
mapTypeId: google.maps.MapTypeId.ROADMAP,
zoom: 15,
};
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
var bounds = new google.maps.LatLngBounds();
var loop_latlng = new google.maps.LatLng( 42.341111, -71.080707 );
marker = addMarker( loop_latlng, "<strong>$1,495.00</strong> <br> Columbus Ave <br> 0 beds / 1 baths <br> <img src='/images/71428455_0.jpg' width=150> <br> <a href='/mls_rn/8305'>get more details</a>" );
bounds.extend(loop_latlng);
var loop_latlng = new google.maps.LatLng( 42.340022, -71.0657278 );
marker = addMarker( loop_latlng, "<strong>$2,000.00</strong> <br> Union Park St <br> 2 beds / 1 baths <br> <img src='/images/71426623_0.jpg' width=150> <br> <a href='/mls_rn/8253'>get more details</a>" );
bounds.extend(loop_latlng);
map.setCenter(bounds.getCenter());
map.fitBounds(bounds);
showMarkers();
}
function addMarker(location,contentString) {
var iw = new google.maps.InfoWindow({
content: contentString
});
var marker = new google.maps.Marker({
position: location,
animation: google.maps.Animation.DROP,
content: contentString,
map: map
});
google.maps.event.addListener(marker,'click',function(){
infoWindow.setContent(this.content);
infoWindow.open(map,this);
});
markerArray.push(marker);
return marker;
}
// display all the markers on the map
function showMarkers() {
if (markerArray) {
for ( i in markerArray ) {
markerArray[i].setMap(map);
}
}
}
function loadScript() {
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "http://maps.googleapis.com/maps/api/js?key=AIzaSyCICKRjJ3Vo_l2hy5uV7GdkYBot6jCtZzI&sensor=true&callback=initialize";
document.body.appendChild(script);
}
window.onload = loadScript;
</script>
I think this actually may be a Rails issue. If I cut and paste this into an HTML document, it seems to work just fine; however, within my Rails app, I'm seeing the off behaviour. The one thing I notice is that the maps seems to reinitialize in the pure HTML case, but doesn't seem to do so in Rails. I'll look into this more and comment. If anyone has seen this before; however, please chime in!
The behavior you describe doesn't happen for me on the official info windows samples, so i'd expect your code to behave the exact same way.
You would need to manually program for such functionality. On HTML5 compliant browsers, you can use the pageshow event to open the info window manually. However all current (less than 10.0) versions of Internet Explorer don't support the event so you would also have to handle this in the window load event.
Related
Want to output the latitude and longitude of the marker point in the 2 input boxes below and then also save them but that can happen later. As the user drags around the marker, the latitude and longitude should keep updating. This is the code I have already:
Output
JS
HTML
Please help, I've tried to debug by adding the console.log but it isn't outputting anything which may suggest where the problem is. At least I can't see anything in Chrome dev tools. When I try to debug using Visual Studio breakpoints, none of it loads so I can't do it that way. I've tried a bunch of other stuff as well.
This is the javascript:
var map;
var marker = false;
function initMap() {
var centerOfMap = new google.maps.LatLng(51.487987, -0.237269); // St Paul's School
var options = {
center: centerOfMap,
zoom: 10
};
// extantiate a map object
map = new google.maps.Map(document.getElementById('map'), options);
marker = new google.maps.Marker({
position: centerOfMap,
map: map,
title: 'Drag me around',
draggable: true
});
google.maps.event.addListener(marker, 'dragend', function (event) {
markerLocation();
});
markerLocation();}
function markerLocation() {
// give the information back to the HTML
var currentLocation = marker.getPosition();
console.log(currentLocation.lat());
document.getElementById("lat").value = String.valueOf( currentLocation.lat());
document.getElementById("lng").value = String.valueOf( currentLocation.lng());
}
google.maps.event.addDomListener(window, 'load', initMap);
This is the HTML:
<div class="insert-location">
<p>Select a location where the task will be carried out. Click on a location to select it. Drag the marker to change it.</p>
<div id="map"></div>
<input type="text" id="lat" readonly="readonly"><br>
<input type="text" id="lng" readonly="readonly">
</div>
Ok, here is a working example of how I solved it (add you api key):
http://jsbin.com/rinayek/1/edit?html,css,js,output
1st replace this:
document.getElementById("lat").value = String.valueOf( currentLocation.lat());
document.getElementById("lng").value = String.valueOf( currentLocation.lng());
for this:
document.getElementById("lat").value = currentLocation.lat();
document.getElementById("lng").value = currentLocation.lng();
2nd make your <div id="map"> that is not children of <div class="insert-location">
For the rest you are ok, check the example for more clarity
I am trying to make tabs using js to have more data on the site.
Please view: http://dev.ateo.dk/officelab-konferencecenter/
The two tabs at the top ("Billeder" and "kort") are made using js.
If i go into the tap called "kort", the google maps will not load completely - however if i right-click and choose "Inspect Element (Q)" using firefox, the map suddenly loads.
Also, the map is not centered. on the specific location - the location is in the top left corner.
You may notice a blank square below the tab div. This is the exact same code as used within the js tab. If i comment out the in js tab, the square which is blank, will work perfectly. So it somehow seems that the js tab combined with the js google maps are not working. Can this be the case, and if so, how is it fixed?
Below i am showing the code which will init the google maps and the taps on the page:
if($('body.single-konferencested').length > 0)
{
tabs();
}
if($('body.single-konferencested').length > 0)
{
$(document).ready(function() {
function initialize() {
var myLatlng = new google.maps.LatLng(place_lat,place_lng);
var mapOptions = {
zoom: 9,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById('gmap'), mapOptions);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
clickable : true
});
var pinIcon = new google.maps.MarkerImage(
"http://dev.ateo.dk/wp-content/themes/ateo/img/pin_marker.png",
null, /* size is determined at runtime */
null, /* origin is 0,0 */
null, /* anchor is bottom center of the scaled image */
new google.maps.Size(24, 40)
);
marker.setIcon(pinIcon);
var content_string = '<div id="gmap_info">'+
'<div id="siteNotice">'+
'</div>'+
'<h3 id="firstHeading" class="firstHeading">'+place_title+'</h3>'+
'<div id="bodyContent">'+
'<p>'+place_address+'<br />'+place_city_zip+'</div>'+
'</div>';
var infowindow = new google.maps.InfoWindow({
content: content_string
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map, marker);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
});
}
This following is the html showing the DOM for the "Kort" tab:
<div class="tabContent" id="kort" style="padding: 5px 10px;">
<h2>Kort</h2>
<div id="gmap" style="width: 600px; height: 400px;"></div>
<h2>test</h2>
</div>
Best regards
Patrick
If the div in which the map is going to live is not visible on page load the map will not load correctly. You should fire a resize once the div has come into view.
google.maps.event.trigger(map, 'resize');
You should bind this to the first click of the map tab.
It looks like the map is commented out of the second tab currently. If you could uncomment it it would be easier to help you more specifically!
EDIT:
to bind the function once, try this:
var tab = jQuery('ul#tabs li')[1]
jQuery(tab).one('click', function(){
google.maps.event.trigger(map, 'resize');
});
In order for the resize to work you will need access to the map variable from your init function.
It would also be easier to select the correct tab if you drop a class on it. That would be more reliable then getting the 2nd li in the tabs ul.
EDIT 2:
try adding the click function in your initialize code. Something similar to the following
var mapOptions = {
zoom: 9,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById('gmap'), mapOptions);
//add the code here, after the map variable has been instantiated
var tab = jQuery('ul#tabs li')[1]
jQuery(tab).one('click', function(){
google.maps.event.trigger(map, 'resize');
//fire a center event after the resize, this is also useful
// if bound to a window resize
map.setCenter(myLatlng)
});
//end of new code
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
clickable : true
});
It can be solved easily by re-initialize the Google Map on Tab click.
$('#kort').click(function(e) {
initialize();
resetMap(map);
});
This simple solution has found from here - How to Display Google Map Inside of a Hidden Div
Wonder if anyone can help me, I have setup a google map all works nicely. The only thing I cant work out how to do is to open an info window based on ID from an external html link that's not in the JS.
function initialize() {
// Create the map
// No need to specify zoom and center as we fit the map further down.
var map = new google.maps.Map(document.getElementById("map"), {
mapTypeId: google.maps.MapTypeId.ROADMAP,
disableDefaultUI: true
});
infowindow = new google.maps.InfoWindow();
// Custom markers
var icon = "img/marker.png";
// Define the list of markers.
// This could be generated server-side with a script creating the array.
var markers = [
{ val:0, lat: -40.149049, lng: 172.033095, title: "Title", html: "<div style='text-align:left'><h4 style='color:#0068a6;font-size:16px;margin:0px 0px 10px 0px;'>Title</h4><strong>Telephone</strong><br /><br />Address</div>" },
{ val:1, lat: -41.185765, lng: 174.827516, title: "Title", html: "<div style='text-align:left'><h4 style='color:#0068a6;font-size:16px;margin:0px 0px 10px 0px;'>Title</h4><strong>Telephone</strong><br /><br />Address</div>" },
];
// Create the markers ad infowindows.
for (index in markers) addMarker(markers[index]);
function addMarker(data) {
// Create the marker
var marker = new google.maps.Marker({
position: new google.maps.LatLng(data.lat, data.lng),
map: map,
title: data.title,
icon: icon,
id: data.val
});
// Create the infowindow with two DIV placeholders
// One for a text string, the other for the StreetView panorama.
var content = document.createElement("DIV");
var title = document.createElement("DIV");
title.innerHTML = data.html;
content.appendChild(title);
// Open the infowindow on marker click
google.maps.event.addListener(marker, "click", function() {
infowindow.setContent(content);
infowindow.open(map, this);
map.setCenter(this.position);
console.log(this.id);
});
}
// Zoom and center the map to fit the markers
// This logic could be conbined with the marker creation.
// Just keeping it separate for code clarity.
var bounds = new google.maps.LatLngBounds();
for (index in markers) {
var data = markers[index];
bounds.extend(new google.maps.LatLng(data.lat, data.lng));
}
map.fitBounds(bounds);
}
<p id="1">link to open marker</p>
Any help would be gratefully appreciated
Richard :)
The Golden Goose
Then in your js have a function to open the infowindow (such as show()) which takes the properties from that link (opening id 7).
function show(id){
myid = id;
if(markers[myid]){
map.panTo(markers[myid].getPoint());
setTimeout('GEvent.trigger(markers[myid], "click")',500);
map.hideControls();
}
}
That's the function I used previously with one of the marker managers from v2. You have to make sure you set an id for each marker as you set it and then you can call it.
The one thing I made sure of (to simplify matters) was to make sure the map marker set/array was exactly the same as the sql result I used on the page. That way, using id's was a piece of cake.
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.
I have multiple locations of my company's regional offices and have to show each location whenever user clicks at a locations like:
location1
location2
location3
When user clicks at location 1 it will show location 1 on the map. I also have those locations in my maps. I have never worked with Google maps before, so I just need some idea to get started.
When your user clicks a link, run a piece a javascript that calls setCenter(latlng:LatLng) on the map to center the map to a certain location.
If you really don't know where to begin, then start by reading the Google Maps API documentation. It's easy to read, and it contains lots of working examples.
You can do something like this: (I'm sure it could be optimized with a for loop, its early/late right now.
<html>
<head>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
function initialize() { //Initalize JS after onload
var map = new google.maps.Map(document.getElementById('map_canvas'), {
mapTypeId: google.maps.MapTypeId.ROADMAP,
});
var randomPoint1 = new google.maps.LatLng(44.6479, -63.5744); //First Location
var marker1 = new google.maps.Marker({ //Set up marker
position: randomPoint1,
map: map
});
google.maps.event.addDomListener(document.getElementById('locationid1'), 'click', //Set up DOM listener 1
function(){
map.setZoom(13);
map.setCenter(marker1.getPosition());
});
var randomPoint2 = new google.maps.LatLng(45.5081, -73.5550); //Second Location
var marker2 = new google.maps.Marker({
position: randomPoint2,
map: map
});
google.maps.event.addDomListener(document.getElementById('locationid2'), 'click',//Set up DOM listener 2
function(){
map.setZoom(13);
map.setCenter(marker2.getPosition());
});
var randomPoint3 = new google.maps.LatLng(43.6481, -79.4042); //Third Location
var marker3 = new google.maps.Marker({
position: randomPoint3,
map: map
});
google.maps.event.addDomListener(document.getElementById('locationid3'), 'click', //Set up DOM listener 3
function(){
map.setZoom(13);
map.setCenter(marker3.getPosition());
});
map.setCenter(marker2.getPosition());
map.setZoom(5);
}
</script>
</head>
<body onload="initialize()"> <!--Initalize JS after onload--->
Halifax
Montreal
Toronto
<div id="map_canvas" style="height:100%; width:100%"></div>
</body>
</html>
And after I write this I realize the post was from last August. Oh well, may help someone at some point.