I am trying to embed a weather widget from http://www.weather.com/services/oap/weather-widgets.html into an Info Window of a Google map, such that when I click on a marker, the weather widget is open in the Infowindow.
The code for embedding the weather widget is as follows (for San-Francisco, CA):
and it works fine when I put it into HTML:
<html>
<head>
</head>
<body>
<div style="width:270px;height:175px;border:1px solid blue;padding:10px">
<script type="text/javascript" src="http://voap.weather.com/weather/oap/USCA0987?template=GENXH&par=3000000007&unit=0&key=twciweatherwidget"></script>
</div>
</body>
</html>
However, when I try to use it in the following code that is supposed to show the widget in the InfoWindow on the Google map it does not work:
<html><head>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script type="text/javascript">
function initialize() {
var cpoint = new google.maps.LatLng(37.770728 ,-122.458199 );
var mapOptions = {
zoom: 4,
center: cpoint,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
var infowindow = new google.maps.InfoWindow();
var info1 = '<div style="width:270px;height:175px;border:1px solid blue;padding:10px"><script type="text/javascript" src="http://voap.weather.com/weather/oap/USCA0987?template=GENXH&par=3000000007&unit=0&key=twciweatherwidget"></script></div>';
var point1 = new google.maps.LatLng(37.770728 ,-122.458199 );
var marker1 = new google.maps.Marker({
position: point1 ,
map: map,
title: "Click here for details"
});
google.maps.event.addListener(marker1 , "click", function() {
infowindow.setContent(info1 );
infowindow.open(map,marker1 );
});
}google.maps.event.addDomListener(window, "load", initialize);
</script>
</head><body>
<div id="map-canvas" style="width:750px; height:450px; border: 2px solid #3872ac;"></div>
</body></html>
All I do is I put that div into info1 Javascript variable. I am not sure whether I do anything wrong, or InfoWindow does not allow to do that.
I finally was able to figure this out using iframe tag. See my blog post Weather forecasting with SAS-generated Google maps.
First, I created weather mini-pages:
%macro create_widgets;
%let dsid = %sysfunc(open(places));
%let num = %sysfunc(attrn(&dsid,nlobs));
%let rc = %sysfunc(close(&dsid));
%do j=1 %to #
data _null_;
p = &j;
set places point=p;
file "&proj_path\widgets\accuweather_com_widget&j..html";
put
'<html><body>' /
'' /
'<div id="' dataid +(-1) '" class="aw-widget-current" data-locationkey="' lockey +(-1) '" data-unit="f" data-language="en-us" data-useip="false" data-uid="' dataid +(-1) '" data-editlocation="false"></div>' /
'<script type="text/javascript" src="http://oap.accuweather.com/launch.js"></script>' /
'</body></html>'
;
stop;
run;
%end;
%mend create_widgets;
%create_widgets;
Then I defined an InfoWindow and a custom marker for the Google map as:
put
'var info' i '= ''<iframe style="width:400px;height:360px;" src="widgets/accuweather_com_widget' i +(-1) '.html">'';' /
'var point' i '= new google.maps.LatLng(' lat ',' lng ');' /
'var marker' i '= new google.maps.Marker({' /
'position: point' i ',' /
'icon: ''images/weather-icon.gif'',' /
'map: map,' /
'title: "Click here for weather details"' /
'});' /
. . .
The rest of the code is no different than in all other Google Map with SAS series.
This widget makes use of document.write to inject style and markup .
write can't be used without possible undesired side-effects after a document has been loaded, but the infowindow opens after the document has been loaded.
Possible workaround:
Use a (hidden)iframe.
Into the hidden iframe load the widget and when the iframe has been loaded
set the content of the infowindow to the node representing the widget
apply the style created for the widget to the current document
//an array with the details, I guess ou want more than 1 marker
//[locationname, latitude, longitude, widget-url]
infos = [
['San Francisco', 37.770728, -122.458199, 'http://voap.weather.com/weather/oap/USCA0987?template=GENXH&par=3000000007&unit=0&key=twciweatherwidget'],
['Atlanta', 33.7489954, -84.3879824, 'http://voap.weather.com/weather/oap/USGA0028?template=GENXV&par=3000000007&unit=0&key=twciweatherwidget']
]
function initialize() {
var mapOptions = {
zoom: 3,
center: new google.maps.LatLng(44.3396955, -100.509996),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
//create the iframe
var infoframe = document.createElement('iframe');
document.body.appendChild(infoframe);
var infowindow = new google.maps.InfoWindow();
//iterate over the infos-array
for (var i = 0; i < infos.length; ++i) {
//create the marker
var marker = new google.maps.Marker({
map: map,
position: new google.maps.LatLng(infos[i][1], infos[i][2]),
title: "Click here for the weather of \n" + infos[i][0],
script: infos[i][3]
});
//click-listener
google.maps.event.addListener(marker, 'click', function () {
var that = this;
infowindow.close();
//when the widget for this marker hasn't been parsed yet
if (!this.get('content')) {
//the window-object of the iframe
var win = infoframe.contentWindow;
google.maps.event.clearListeners(win, 'load');
//open document and write the widget-code
win.document.open();
win.document.write('\<script src="' + this.get('script') + '">\<\/script>');
//observe the load-event of the iframe
//will fire when widget is available
google.maps.event.addDomListener(win, 'load', function () {
//store style and widget-node as marker-properties
that.set('style', document.adoptNode(win.document.getElementsByTagName('style')[0]));
that.get('style').id = 'weatherstyle';
if (!document.getElementById('weatherstyle')) {
var weatherstyle = document.createElement('style');
weatherstyle.id = 'weatherstyle';
document.getElementsByTagName('head')[0].appendChild(weatherstyle);
}
that.set('content', document.adoptNode(win.document.body.firstChild));
//trigger the marker-click
//this will open the infowindow now
google.maps.event.trigger(that, 'click')
});
win.document.close();
}
//widget has been parsed, set infowindow-content and open it
else {
//inject widget-style into document
document.getElementById('weatherstyle').parentNode.replaceChild(that.get('style'), document.getElementById('weatherstyle'))
infowindow.setContent(that.get('content'));
infowindow.open(that.getMap(), that);
}
});
}
}
google.maps.event.addDomListener(window, "load", initialize);
Demo: http://jsfiddle.net/doktormolle/tvn4qtxL/
Related
I have this google map which is working, I want to add a button on infowindow which somehow is not working. Though the function is defined but still throw error
http://jsfiddle.net/mpgxn53q/
<div id="apptMap"></div>
//the js code
<script src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
var locations = [["158845-001 - Adas Israel Congregation",38.9369545,-77.0575097,1],["163888-137 - Construction LLC",43.1765812,-84.6986701,2.0],["163888-155 - Construction LLC",43.1765812,-84.6986701,3.0],["167176-007 - GLDB MTM10 GLR016",42.4894512,-95.5449508,4.0],["167195-003 - 91622 DB A4",42.8275053,-84.5717997,5.0],["167195-002 - 91622 DB A4",42.8275053,-84.5717997,6.0],["167176-005 - GLDB MTM10 GLR016",42.0023,-93.6110955,7.0],["167176-004 - GLDB MTM10 GLR016",42.0023,-93.6110955,8.0]];
var map;
var markers = [];
function init(){
map = new google.maps.Map(document.getElementById('apptMap'), {
zoom: 10,
center: new google.maps.LatLng(42.0023,-93.6110955),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var num_markers = locations.length;
for (var i = 0; i < num_markers; i++) {
markers[i] = new google.maps.Marker({
position: {lat:locations[i][1], lng:locations[i][2]},
map: map,
html: locations[i][0],
id: i,
});
google.maps.event.addListener(markers[i], 'click', function(){
var infowindow = new google.maps.InfoWindow({
id: this.id,
content:this.html +'<button onclick="mapsZoomMarker('+i+')">Click me</button>',
position:this.getPosition()
});
google.maps.event.addListenerOnce(infowindow, 'closeclick', function(){
markers[this.id].setVisible(true);
});
this.setVisible(false);
infowindow.open(map);
});
}
}
function mapsZoomMarker(wnMarker){
map.setCenter(markers[wnMarker].getPosition());
map.setZoom(15);
}
init();
There is a problem with scopes, and that's because of that how you wrote your script. I am not going to rewrite your script, but I will give you solution for your exact situation.
You need to define your function mapsZoomMarker in global scope (window object) like this:
window.mapsZoomMarker = function (wnMarker){
map.setCenter(markers[wnMarker].getPosition());
map.setZoom(15);
}
And there is also a mistake, in the function which is called when the marker is clicked. When you assign the html for the popup like this
content: this.html +'<button onclick="mapsZoomMarker('+i+')">Click me</button>'
the i variable is already set to 8, so instead of that just use this.id like this:
content: this.html +'<button onclick="mapsZoomMarker('+this.id+')">Click me</button>'
And this is the updated fiddle http://jsfiddle.net/rn27f05v/
I will propose a solution that I think is best for what you want. Instead call function inside var infowindow, you can only define a variable to put content your want.
You can change you var infowindow to:
var infowindow = new google.maps.InfoWindow({
id: this.id,
content: content, //here the variable that call your content
position:this.getPosition()
});
So... above your google.maps.event.addListener(markers[i], 'click', function(){... you can add:
var content = '<button onclick="mapsZoomMarker('+i+')">Click me</button>';
This way the click action will work.
Hope this tip help you.
I'm working on a web app that includes google map and a bunch of markers.
This morning I had working map+markers from db (but I used only one table with data).
ss this morning:
Now I'm trying to put marker custom icons and info windows to get something like this (this was made without laravel, only php).
This is my code:
#extends('layouts.app')
#section('content')
<script src="http://maps.google.com/maps/api/js?sensor=false"
type="text/javascript"></script>
<script type="text/javascript">
//<![CDATA[
function load() {
var map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 45.327168, lng: 14.442902},
zoom: 13
});
var infoWindow = new google.maps.InfoWindow;
#foreach($markers as $marker)
var sadrzaj = {{$marker->nazivMarkera}};
var adresa = {{$marker->adresa}};
var grad = {{$marker->nazivGrada}};
var postanskibroj = {{$marker->postanski_broj}};
var zupanija = {{$marker->nazivZupanije}};
var html = "<b>" + sadrzaj + "</b> <br/>" + adresa +",<br/>"+postanskibroj+" "+grad+",<br/>"+zupanija;
var lat = {{$marker->lat}};
var lng = {{$marker->lng}};
var image = {{$marker->slika}};
var markerLatlng = new google.maps.LatLng(parseFloat(lat),parseFloat(lng));
var mark = new google.maps.Marker({
map: map,
position: markerLatlng,
icon: image
});
bindInfoWindow(mark, map, infoWindow, html);
#endforeach
}
function bindInfoWindow(mark, map, infoWindow, html){
google.maps.event.addListener(marker, 'click', function(){
infoWindow.setContent(html);
infowWindow.open(map, mark);
});
}
function doNothing(){}
//]]>
</script>
<div class="container">
<div class="row">
<div class="col-md-10 col-md-offset-1">
<div class="panel panel-default">
<div class="panel-heading">Dobro došli!</div>
<div class="panel-body">
<!-- Moj kod -->
<div id="map"></div>
<!-- DO TU -->
</div>
</div>
</div>
</div>
</div>
#endsection
When I inspect the page I can see that my array with data is filled and I have all the data from db.
Can someone help me and explain to me where is the problem? Why when I remove functions for markers, and set only map init, I get map view with no problem, and now I don't even get the map.
Now:
It looks like load() is not getting called anywhere.
Also I noticed in your screen shots, the variables which have been echoed in by laravel don't have quotes around them.
I would leave laravel(blade) out of the javascript. Currently, your foreach loop will dump heaps of javascript code which will be overriding and re-declaring variables. This is generally messy, and considered bad practice.
I would also make map a global variable, incase you want to manipulate it later.
Try this:
var map;
var markers = {!! json_encode($markers) !!}; //this should dump a javascript array object which does not need any extra interperting.
var marks = []; //just incase you want to be able to manipulate this later
function load() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 45.327168, lng: 14.442902},
zoom: 13
});
for(var i = 0; i < markers.length; i++){
marks[i] = addMarker(markers[i]);
}
}
function addMarker(marker){
var sadrzaj = marker.nazivMarkera};
var adresa = marker.adresa;
var grad = marker.nazivGrada;
var postanskibroj = marker.postanski_broj;
var zupanija = marker.nazivZupanije;
var html = "<b>" + sadrzaj + "</b> <br/>" + adresa +",<br/>"+postanskibroj+" "+grad+",<br/>"+zupanija;
var markerLatlng = new google.maps.LatLng(parseFloat(marker.lat),parseFloat(marker.lng));
var mark = new google.maps.Marker({
map: map,
position: markerLatlng,
icon: marker.slika
});
var infoWindow = new google.maps.InfoWindow;
google.maps.event.addListener(mark, 'click', function(){
infoWindow.setContent(html);
infoWindow.open(map, mark);
});
return mark;
}
function doNothing(){} //very appropriately named function. whats it for?
I also fixed up several small errors in the code, such as
info window was spelt wrong inside your bind function "infowWindow"
your infoWindow listener need to bind to mark not marker
you don't really need to individually extract out each variable from marker
Also, you need to call the load() function from somewhere. Maybe put onLoad="load()" on your body object or top level div. Or use the google DOM listener:
google.maps.event.addDomListener(window, 'load', load);
This will execute your load() function when the window is ready.
You have lo leave
var map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 45.327168, lng: 14.442902},
zoom: 13
});
out of the commented area, otherwise you're not initializing it.
I want to retrieve and display updated infoWindow content at the time user click on marker. Problem I am having is how to insert new text on the relevant click event.
Here is relevant code.
// add listener on InfoWindow - close last infoWindow before opening new one
google.maps.event.addListener(marker, 'click', function() {
//Close active window if exists - [one might expect this to be default behaviour no?]
if(activeInfoWindow != null) activeInfoWindow.close();
// get latest text
var newText = fnGetNewTextForInfoWindow();
// this is clearly wrong
infoWnd.setContent(newText);
// Open InfoWindow
infoWnd.open(map, marker, newText);
// Store new open InfoWindow in global variable
activeInfoWindow = infoWnd;
});
and full simplified example...
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<style>
#map-canvas, #side-bar {
height: 500px;
width: 600px;
}
/* fix for unwanted scroll bar in InfoWindow */
.scrollFix {
line-height: 1.35;
overflow: hidden;
white-space: nowrap;
}
</style>
<script src="http://maps.googleapis.com/maps/api/js" type="text/javascript"></script>
<script src="../jquery/jquery.js" type="text/javascript"></script>
<script type="text/javascript">
// "use strict";
// variable to hold a map
var map;
// variable to hold current active InfoWindow
var activeInfoWindow ;
// ------------------------------------------------------------------------------- //
// initialize function
// ------------------------------------------------------------------------------- //
function initialize() {
// map options - lots of options available here
var mapOptions = {
zoom : 10,
draggable: true,
center : new google.maps.LatLng(44.9600, -93.1000),
mapTypeId : google.maps.MapTypeId.ROADMAP
};
// create map in div called map-canvas using map options defined above
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
// define two Google Map LatLng objects representing geographic points
var stPaul = new google.maps.LatLng(44.9522,-93.0892);
var minneapolis = new google.maps.LatLng(44.9792,-93.2662);
// place two markers
fnPlaceMarkers(stPaul,"St Paul");
fnPlaceMarkers(minneapolis,"Minneapolis");
}
// ------------------------------------------------------------------------------- //
// create markers on the map
// ------------------------------------------------------------------------------- //
function fnPlaceMarkers(myLocation,myCityName){
var marker = new google.maps.Marker({
position : myLocation
});
// Renders the marker on the specified map
marker.setMap(map);
// create an InfoWindow
var infoWnd = new google.maps.InfoWindow();
// add content to your InfoWindow
infoWnd.setContent('<div class="scrollFix">' + 'Welcome to ' + myCityName + '</div>');
// add listener on InfoWindow - close last infoWindow before opening new one
google.maps.event.addListener(marker, 'click', function() {
//Close active window if exists - [one might expect this to be default behaviour no?]
if(activeInfoWindow != null) activeInfoWindow.close();
// get latest text
var newText = fnGetNewTextForInfoWindow();
infoWnd.setContent(newText);
// Open InfoWindow
infoWnd.open(map, marker, newText);
// Store new open InfoWindow in global variable
activeInfoWindow = infoWnd;
});
}
function fnGetNewTextForInfoWindow(){
var newText = $('#idSomeNewText');
return newText;
}
// ------------------------------------------------------------------------------- //
// initial load
// ------------------------------------------------------------------------------- //
google.maps.event.addDomListener(window, 'load', initialize);
</script>
BACK<br>
<br/>
<h3></h3>
<ul>
<li>Enter some text in text box and click market to update text in InfoWindow, then show InfoWindow</li>
</ul>
Enter Some text to insert in marker:
<input id='idSomeNewText' type="text" name="firstname" value="test value">
<br/> <br/>
<div id="map-canvas"></div>
<br/>
<br/>
</body>
</html>
The Google maps setContent() function does that. For example:
google.maps.event.addListener(marker, 'click', function() {
//Close active window if exists
if(activeInfoWindow) {
activeInfoWindow.close();
} else {
activeInfoWindow = new google.maps.InfoWindow();
}
// get latest text
var newText = fnGetNewTextForInfoWindow();
// Update InfoWindow content
activeInfoWindow.setContent(newText);
// Open InfoWindow
activeInfoWindow.open(map, marker);
});
You can reuse the infoWindow as often as you like. Just change the content and position it at the proper marker.
complete working answer...
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<style>
#map-canvas, #side-bar {
height: 500px;
width: 600px;
}
/* fix for unwanted scroll bar in InfoWindow */
.scrollFix {
line-height: 1.35;
overflow: hidden;
white-space: nowrap;
}
</style>
<script src="http://maps.googleapis.com/maps/api/js" type="text/javascript"></script>
<script src="../jquery/jquery.js" type="text/javascript"></script>
<script type="text/javascript">
// "use strict";
// variable to hold a map
var map;
// variable to hold current active InfoWindow
var activeInfoWindow ;
// arrays to hold copies of the markers and html used by the side_bar
var gmarkers = [];
// ------------------------------------------------------------------------------- //
// initialize function
// ------------------------------------------------------------------------------- //
function initialize() {
// map options - lots of options available here
var mapOptions = {
zoom : 10,
draggable: true,
center : new google.maps.LatLng(44.9600, -93.1000),
mapTypeId : google.maps.MapTypeId.ROADMAP
};
// create map in div called map-canvas using map options defined above
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
// define two Google Map LatLng objects representing geographic points
var stPaul = new google.maps.LatLng(44.9522,-93.0892);
var minneapolis = new google.maps.LatLng(44.9792,-93.2662);
// place two markers
fnPlaceMarkers(stPaul,"St Paul");
fnPlaceMarkers(minneapolis,"Minneapolis");
//console.log(gmarkers);
}
// ------------------------------------------------------------------------------- //
// create markers on the map
// ------------------------------------------------------------------------------- //
function fnPlaceMarkers(myLocation,myCityName){
var marker = new google.maps.Marker({
position : myLocation
});
// Renders the marker on the specified map
marker.setMap(map);
// save the info we need to use later
gmarkers.push(marker);
// create an InfoWindow
var infoWnd = new google.maps.InfoWindow();
// add content to your InfoWindow
infoWnd.setContent('<div class="scrollFix">' + 'Welcome to ' + myCityName + '</div>');
// add listener on InfoWindow - close last infoWindow before opening new one
google.maps.event.addListener(marker, 'click', function() {
//Close previous active window if exists - [one might expect this to be default behaviour no?]
if(activeInfoWindow != null) activeInfoWindow.close();
//Close previous active window if exists
// if(activeInfoWindow) {
// activeInfoWindow.close();
// } else {
// activeInfoWindow = new google.maps.InfoWindow();
// }
// get latest text
var newText = fnGetNewTextForInfoWindow();
// Update InfoWindow content
infoWnd.setContent(newText);
// Open InfoWindow
infoWnd.open(map, marker);
// Open InfoWindow
//infoWnd.open(map, marker, newText);
// Store new open InfoWindow in global variable
activeInfoWindow = infoWnd;
});
}
function fnGetNewTextForInfoWindow(){
var newText = $('#idSomeNewText').val();
return newText;
}
// ------------------------------------------------------------------------------- //
// initial load
// ------------------------------------------------------------------------------- //
google.maps.event.addDomListener(window, 'load', initialize);
</script>
BACK<br>
<br/>
<h3>Update InfoWindow contents when marker is clicked</h3>
<p>This is useful when content of infoWindow changes frequently</p>
Enter Some text to insert in marker:
<input id='idSomeNewText' type="text" name="anyName" value="test value">
<br/> <br/>
<div id="map-canvas"></div>
<br/>
<br/>
</body>
</html>
I have a Jscript which using HTML5 geoloaction,
It works perfectly. i want to add a share button where it shows my position, But i cant find how i can add a button here
<script src="https://maps.googleapis.com/maps/api/js?secretapi&sensor=true"></script>
<script>
var map;
function initialize() {
var mapOptions = {
zoom: 18,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
// Try HTML5 geolocation
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
var infowindow = new google.maps.InfoWindow({
map: map,
position: pos,
content: 'your pos' +pos //**i want add a fb share button here**
});
map.setCenter(pos);
}, function() {
handleNoGeolocation(true);
});
} else {
// Browser doesn't support Geolocation
handleNoGeolocation(false);
}
}
function handleNoGeolocation(errorFlag) {
if (errorFlag) {
var content = 'Error: The Geolocation service failed.';
} else {
var content = 'Error: Your browser doesn\'t support geolocation.';
}
var options = {
map: map,
position: new google.maps.LatLng(60, 105),
content: content
};
var infowindow = new google.maps.InfoWindow(options);
map.setCenter(options.position);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
Infowindow can have html markup as content. So if you want to add a button you can simply
do
content: 'your pos' + pos + '<button></button>'
Consider it as a div that can take any html markup, which can be styled too (the markup, not the window).
A demo
UPDATE
For binding an event on a dynamic element (in your case the button) you could do the following
content: 'your pos' + pos + '<button id="myButton"></button>'
And in your js script do the following
$("body").on("click", "#myButton", function(e) {
// ...
});
Mind the fact that the above is a method of the jQuery object so be sure to include the jquery library.
A new demo press the button and see the alert that is being called in the binding
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.