google map - how to change google map infoWindow text - javascript

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>

Related

allow user to move marker position back (z-index?) in google maps custom map

I would like to allow user to be able to move order of custom google maps marker on a click inside an InfoWindow. This is to overcome issue of overlapping markers. I have considered other solutions (move lat/lon, marker clusters, "spider markers").
My code has 2 issues: 1) jquery listener not working 2) but more important how to implementing change of z-index (or other technique?) and redisplay.
<!DOCTYPE html>
<html>
<head>
<style>
#map-canvas, #side-bar {
height: 500px;
width: 600px;
}
</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">
// scoping for jquery
$( document ).ready(function() {
"use strict";
// variable to hold a map
var map;
// variable to hold current active InfoWindow
var activeInfoWindow ;
// ------------------------------------------------------------------------------- //
// initialize function
// ------------------------------------------------------------------------------- //
function initialize() {
// ------------------------------------------------------------------------------- //
// LISTENER ON CLICK EVENT
// ------------------------------------------------------------------------------- //
$( "a" ).on( "click", function() {
alert("got here!");
// do something to change z-index of this marker
//...
// my_index = my_index-1;
//...
return false;
});
// map options - lots of options available here
var mapOptions = {
zoom : 5,
draggable: true,
center : new google.maps.LatLng(44.960, -93.100),
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.95283,-93.08925);
var minneapolis = new google.maps.LatLng(44.97984,-93.26620);
// 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 + '<br/>Click to move this marker to the back</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();
// Open InfoWindow
infoWnd.open(map, marker);
// Store new open InfoWindow in global variable
activeInfoWindow = infoWnd;
});
}
// ------------------------------------------------------------------------------- //
// initial load
// ------------------------------------------------------------------------------- //
google.maps.event.addDomListener(window, 'load', initialize);
}); // end query
</script>
<div id="map-canvas"></div>
</body>
</html>
set zIndex for all the markers (otherwise it is not defined), good value is (latitude * -100000) << 5 (from Mike Williams in ancient history)
var marker = new google.maps.Marker({
position: myLocation,
zIndex: Math.round(myLocation.lat()*-100000)<<5
});
keep references to all your markers (array markers)
markers.push(marker);
decrement zIndex by -100000 when the link is clicked.
working fiddle
code snippet:
function setMarkerBack(i) {
var currentZ = markers[i].get('zIndex');
markers[i].set('zIndex', currentZ - 100000);
}
var markers = [];
// scoping for jquery
$(document).ready(function() {
"use strict";
// variable to hold a map
var map;
// variable to hold current active InfoWindow
var activeInfoWindow;
// ------------------------------------------------------------------------------- //
// initialize function
// ------------------------------------------------------------------------------- //
function initialize() {
// ------------------------------------------------------------------------------- //
// LISTENER ON CLICK EVENT
// ------------------------------------------------------------------------------- //
$("a").on("click", function() {
alert("got here!");
// do something to change z-index of this marker
//...
// my_index = my_index-1;
//...
return false;
});
// map options - lots of options available here
var mapOptions = {
zoom: 5,
draggable: true,
center: new google.maps.LatLng(44.960, -93.100),
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.95283, -93.08925);
var minneapolis = new google.maps.LatLng(44.97984, -93.26620);
// 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,
zIndex: Math.round(myLocation.lat() * -100000) << 5
});
// Renders the marker on the specified map
marker.setMap(map);
var i = markers.length;
markers.push(marker);
// create an InfoWindow
var infoWnd = new google.maps.InfoWindow();
// add content to your InfoWindow
infoWnd.setContent('<div class="scrollFix">' + 'Welcome to ' + myCityName + '<br/>Click to move this marker to the back<br>zIndex=' + marker.get('zIndex') + '</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();
// Open InfoWindow
infoWnd.open(map, marker);
// Store new open InfoWindow in global variable
activeInfoWindow = infoWnd;
});
}
// ------------------------------------------------------------------------------- //
// initial load
// ------------------------------------------------------------------------------- //
google.maps.event.addDomListener(window, 'load', initialize);
}); // end query
html,
body,
#map-canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map-canvas" style="border: 2px solid #3872ac;"></div>

Embedding weather widget into info window of Google map

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 &num;
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/

google map only loads half of its portion,i have used some extra javascript for some effects on the map but its only loading half

i have tried to use some hide/show functionality to my google map where a certain portion of the map is showed initially and after clicking on a button the whole map shows up.everything is working fine but when i click on the button and try to see the whole map,only half of the map shows up and the other half is covered with some gray color.here is the code
<html>
<head>
<style>
#thediv {
height: 100px;
}
</style>
<body>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script type="text/javascript">
function initialize() {
var locations = [
['Nepcreation,sydney branch', -33.867487, 151.20699, 3],
['Nepcreation,kaulalampur branch', 3.140345, 101.689206, 2],
['Nepcreation,kathmandu', 27.689390, 85.335494, 1]
];
var map = new google.maps.Map(document.getElementById('thediv'), {
zoom: 2,
center: new google.maps.LatLng(27.689390, 85.335494),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow();
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.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
}
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
<div id="thediv" class="reveal-closed"></div>
<input type="submit" onClick="gmap()">
<script>
function gmap(){
var x=document.getElementById("thediv");
if(x.style.height=="100px"){
x.style.height="600px";}
else{
x.style.height="100px";
}
}
</script>
</body>
</html>
This is a common problem faced by many users(including myself).
First you have initialized the Google maps within given dimension(auto x 100px), based on it the map images(called as tiles) are loaded into it.
Then based on the button 's click you're changing it dimension (auto x 600px) therefore the excess part of Google images are not rendered but showing only the grey area. In order to fix it what you have to do is to trigger the resize event as mentioned below
google.maps.event.trigger(map, "resize");
In your code, the map variable is scoped within the initialize() whereas the click event of button calls gmap(). So lets keep the map variable as global and then follow the below code:
function gmap() {
var x = document.getElementById("thediv");
if (x.style.height == "100px") {
x.style.height = "600px";
} else {
x.style.height = "100px";
}
google.maps.event.trigger(map, "resize");
}
PS: In order to give a detailed explanation to this new user I have added this as my answer instead of marking it as duplicate.

Google Maps v3 Listener (click) - Change URL

I have a Google Maps map with a markercluster, and various points. Generating the points like below with the event listener, it goes off for every single point on page load.
function mappyfuntime() {
var mapOptions = {
center: new google.maps.LatLng(51.481581,-3.17909),
zoom: 4,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("bigmap"), mapOptions);
<?php echo prepare_javascript(); ?>
var markers = [];
var marker = [];
linkto = new Array();
for(g=0; g<LocationsArray.length; g++) {
var latlng = new google.maps.LatLng(LocationsArray[g][0], LocationsArray[g][1]);
marker[g] = new google.maps.Marker({'position': latlng});
markers.push(marker[g]);
google.maps.event.addListener(marker[g], 'click', click_handler(PermalinksArray[g]));
}
var markerCluster = new MarkerClusterer(map, markers);
}
mappyfuntime();
function click_handler(link) {
alert(link);
}
However, if I change the google.maps.event.addListener to the following, the alert comes back undefined.
google.maps.event.addListener(marker[g], 'click', function() {
alert(PermalinksArray[g]);
});
And if I pass PermalinksArray[g] to the function, the same thing happens. Is there any way to get a piece of information from an array (which is globally defined) when its corresponding point is clicked on the map?
I guess the Permalinks Array comes from the php insert? Well then its not in global scope. Try puttung that php-insert at the top of your javascript script.
// set globals
var map;
var markers = [];
var PermalinksArray = ['...'];
var LocationsArray = ['...'];
function mappyfuntime() {
// init map
var mapOptions = {
center: new google.maps.LatLng(51.481581,-3.17909),
zoom: 4,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("bigmap"), mapOptions);
// create markers
for(g=0; g<LocationsArray.length; g++) {
// create new Position
var latlng = new google.maps.LatLng(LocationsArray[g][0], LocationsArray[g][1]);
// create new marker with position
var marker = new google.maps.Marker({'position': latlng});
// add event to marker
google.maps.event.addListener(marker, 'click', function() {
click_handler(marker, PermalinksArray[g]);
});
// push marker into markers array
markers.push(marker);
}
var markerCluster = new MarkerClusterer(map, markers);
}
function click_handler(marker, link) {
alert(link);
}
mappyfuntime();
I have created a Google Map with 2 markers and when a marker is clicked then the area's name appears in the info window. The information in the markers is loaded through a global defined array named cityList. You can find my code below.
<!doctype html>
<html lang="en">
<head>
<title>jQuery mobile with Google maps - Google maps jQuery plugin</title>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.css" />
<script src="http://code.jquery.com/jquery-1.8.2.min.js"></script>
<script src="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.js"></script>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?v=3&sensor=false&language=en"> </script>
<script type="text/javascript">
var cityList = [
['Chicago', 41.850033, -87.6500523, 1],
['Illinois', 40.797177,-89.406738, 2]
],
demoCenter = new google.maps.LatLng(41,-87),
map;
function initialize()
{
map = new google.maps.Map(document.getElementById('map_canvas'), {
zoom: 7,
center: demoCenter,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
}
function addMarkers()
{
var marker, i;
var infowindow = new google.maps.InfoWindow();
for (i = 0; i < cityList.length; i++)
{
marker = new google.maps.Marker({
position: new google.maps.LatLng(cityList[i][1], cityList[i][2]),
map: map,
title: cityList[i][0]
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(cityList[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
}
}
$(document).on("pageinit", "#basic-map", function() {
initialize();
});
$(document).on('click', '.add-markers', function(e) {
e.preventDefault();
addMarkers();
});
</script>
</head>
<body>
<div id="basic-map" data-role="page">
<div data-role="header">
<h1><a data-ajax="false" href="/">jQuery mobile with Google maps v3</a> examples</h1>
<a data-rel="back">Back</a>
</div>
<div data-role="content">
<div class="ui-bar-c ui-corner-all ui-shadow" style="padding:1em;">
<div id="map_canvas" style="height:350px;"></div>
</div>
Add Some More Markers
</div>
</div>
</body>
</html>
I hope this helps.

Google Map API V3 - Click on Marker show more info content as overlay (like in Google Maps)

We use Google Map Api V3 to load google map in HTML container. We have a location search form. On submit, we will get the available locations and set markers in map. Once markers are loaded, on click on each marker we need to show Title, address details and design like what we have in google map. (In google maps - When clicking on red marker, we can see the more info overlay box with additional details like Stars, Directions, Search nearby, Save to Map, More..)
Do we have built in api function to load the overlay box like above. Or we don't have the function to load the details like what we have in google map currently.
When i searched in google and map docs, i can see options to show overlay window and write content inside the box. But i didn't see options to load the content as required.
I have pasted the code below for reference.
var map = null;
gmap_ready = function (){
var myLatlng = new google.maps.LatLng(43.834527,-103.564457);
var myOptions = {
zoom: 3,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
}
function fnLoadMarkers(){
var locations = [
['S Dakota', 43.834527,-103.564457, 1],
['Texas', 31.428663,-99.418947, 2],
['California', 36.668419,-120.249025, 3],
['Newyork', 43.197167,-76.743166, 4],
['Missouri', 38.410558,-92.73926, 5]
];
setMarkers(map,locations);
}
function setMarkers(map, locations) {
var image = 'images/marker.gif';
for (var i = 0; i < locations.length; i++) {
var currLocation = locations[i];
var latLng = new google.maps.LatLng(currLocation[1], currLocation[2]);
var marker = new google.maps.Marker({
position: latLng,
map: map,
icon: image,
title: currLocation[0],
zIndex: currLocation[3]
});
google.maps.event.addListener(marker, 'click', function() {
var latitude = this.position.lat();
var longitude = this.position.lng();
window.open("http://maps.google.com/maps?f=q&source=s_q&hl=en&geocode=&q="+latitude+","+longitude+"&sll="+latitude+","+longitude+"&sspn=0.172749,0.4422&ie=UTF8&ll="+latitude+","+longitude+"&spn=0.162818,0.4422&z=11&iwloc=A");
});
}
}
If there is any hint on how to achieve these results, it will be helpful. Also, please guide, whether it is possible through Google API V3.
Thanks in Advance,
Regards
Srinivasan.C
I don't understand why are you opening a new window to Google Maps from a Google Maps API marker?
You cannot add info window on Google Maps via URL.
This is how I do it.
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<link href="http://code.google.com/apis/maps/documentation/javascript/examples/default.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
// Initiate map
function initialize(data) {
// Make position for center map
var myLatLng = new google.maps.LatLng(data.lng, data.lat);
// Map options
var myOptions = {
zoom: 10,
center: myLatLng,
mapTypeId: google.maps.MapTypeId.HYBRID
};
// Initiate map
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
// Info window element
infowindow = new google.maps.InfoWindow();
// Set pin
setPin(data);
}
// Show position
function setPin(data) {
var pinLatLng = new google.maps.LatLng(data.lng, data.lat);
var pinMarker = new google.maps.Marker({
position: pinLatLng,
map: map,
data: data
});
// Listen for click event
google.maps.event.addListener(pinMarker, 'click', function() {
map.setCenter(new google.maps.LatLng(pinMarker.position.lat(), pinMarker.position.lng()));
map.setZoom(18);
onItemClick(event, pinMarker);
});
}
// Info window trigger function
function onItemClick(event, pin) {
// Create content
var contentString = pin.data.text + "<br /><br /><hr />Coordinate: " + pin.data.lng +"," + pin.data.lat;
// Replace our Info Window's content and position
infowindow.setContent(contentString);
infowindow.setPosition(pin.position);
infowindow.open(map)
}
</script>
</head>
<body onload="initialize({lat:-3.19332,lng:55.952366,text:'<h2>Edinburgh</h2><i>Nice city!</i>'})">
<div id="map_canvas">
</div>
</body>
</html>

Categories

Resources