Google maps adding streetview to each infowindow - google-maps

I would like to add streetview to each infowindow but I can't figure out how to integrate the code. I tried putting the code where the comments are set and that works half. Still have to learn a lot about programming.
html += '<div id="content" style="width:200px;height:200px;"></div>';
var pano = null;
google.maps.event.addListener(infoWindow, 'domready', function () {
if (pano != null) {
pano.unbind("position");
pano.setVisible(false);
}
pano = new google.maps.StreetViewPanorama(document.getElementById("content"), {
navigationControl: true,
navigationControlOptions: { style: google.maps.NavigationControlStyle.ANDROID },
enableCloseButton: false,
addressControl: false,
linksControl: false
});
pano.bindTo("point", marker);
pano.setVisible(true);
});
I'm using this code:
function load() {
var map = new google.maps.Map(document.getElementById("map_canvas"), {
center: new google.maps.LatLng(41.640078, -102.669433),
zoom: 3,
mapTypeId: 'roadmap'
});
var infoWindow = new google.maps.InfoWindow;
downloadUrl("mymap.php", function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var name = markers[i].getAttribute("name");
var address = markers[i].getAttribute("address");
var type = markers[i].getAttribute("type");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var html = "<b>" + name + "</b> <br/>" + point;
// comment *** streetview here ****
var marker = new google.maps.Marker({
map: map,
position: point
});
bindInfoWindow(marker, map, infoWindow, html);
}
});}
function bindInfoWindow(marker, map, infoWindow, html) {
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(html);
infoWindow.open(map, marker);
});
}

Working example using DOM elements (rather than using string content):
// this variable will collect the html which will eventually be placed in the side_bar
var side_bar_html = "";
// arrays to hold copies of the markers used by the side_bar
var gmarkers = [];
// global "map" variable
var map = null;
var sv = new google.maps.StreetViewService();
var clickedMarker = null;
var panorama = null;
// Create the shared infowindow with three DIV placeholders
// One for a text string, oned for the html content from the xml, one for the StreetView panorama.
var content = document.createElement("DIV");
var title = document.createElement("DIV");
content.appendChild(title);
var streetview = document.createElement("DIV");
streetview.style.width = "200px";
streetview.style.height = "200px";
content.appendChild(streetview);
var htmlContent = document.createElement("DIV");
content.appendChild(htmlContent);
var infowindow = new google.maps.InfoWindow({
size: new google.maps.Size(150, 50),
content: content
});
// A function to create the marker and set up the event window function
function createMarker(latlng, name, html) {
var contentString = html;
var marker = new google.maps.Marker({
position: latlng,
map: map,
title: name,
zIndex: Math.round(latlng.lat() * -100000) << 5
});
marker.myHtml = html;
google.maps.event.addListener(marker, "click", function() {
clickedMarker = marker;
sv.getPanoramaByLocation(marker.getPosition(), 50, processSVData);
// openInfoWindow(marker);
});
// save the info we need to use later for the side_bar
gmarkers.push(marker);
// add a line to the side_bar html
side_bar_html += '<a href="javascript:myclick(' + (gmarkers.length - 1) + ')">' + name + '<\/a><br>';
}
// This function picks up the click and opens the corresponding info window
function myclick(i) {
google.maps.event.trigger(gmarkers[i], "click");
}
function processSVData(data, status) {
if (status == google.maps.StreetViewStatus.OK) {
var marker = clickedMarker;
openInfoWindow(clickedMarker);
if (!!panorama && !!panorama.setPano) {
panorama.setPano(data.location.pano);
panorama.setPov({
heading: 270,
pitch: 0,
zoom: 1
});
panorama.setVisible(true);
google.maps.event.addListener(marker, 'click', function() {
var markerPanoID = data.location.pano;
// Set the Pano to use the passed panoID
panorama.setPano(markerPanoID);
panorama.setPov({
heading: 270,
pitch: 0,
zoom: 1
});
panorama.setVisible(true);
});
}
} else {
openInfoWindow(clickedMarker);
title.innerHTML = clickedMarker.getTitle() + "<br>Street View data not found for this location";
htmlContent.innerHTML = clickedMarker.myHtml;
panorama.setVisible(false);
// alert("Street View data not found for this location.");
}
}
function initialize() {
// Create the map
// No need to specify zoom and center as we fit the map further down.
map = new google.maps.Map(document.getElementById("map_canvas"), {
mapTypeId: google.maps.MapTypeId.ROADMAP,
streetViewControl: false
});
google.maps.event.addListener(map, 'click', function() {
infowindow.close();
});
// Read the data from example.xml
// downloadUrl("example.xml", function(doc) {
var xmlDoc = xmlParse(xmlData);
var markers = xmlDoc.documentElement.getElementsByTagName("marker");
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < markers.length; i++) {
// obtain the attribues of each marker
var lat = parseFloat(markers[i].getAttribute("lat"));
var lng = parseFloat(markers[i].getAttribute("lng"));
var point = new google.maps.LatLng(lat, lng);
var html = markers[i].getAttribute("html");
var label = markers[i].getAttribute("label");
// create the marker
var marker = createMarker(point, label, html);
bounds.extend(point);
}
// put the assembled side_bar_html contents into the side_bar div
document.getElementById("side_bar").innerHTML = side_bar_html;
// Zoom and center the map to fit the markers
map.fitBounds(bounds);
// });
}
// Handle the DOM ready event to create the StreetView panorama
// as it can only be created once the DIV inside the infowindow is loaded in the DOM.
var pin = new google.maps.MVCObject();
google.maps.event.addListenerOnce(infowindow, "domready", function() {
panorama = new google.maps.StreetViewPanorama(streetview, {
navigationControl: false,
enableCloseButton: false,
addressControl: false,
linksControl: false,
visible: true
});
panorama.bindTo("position", pin);
});
// Set the infowindow content and display it on marker click.
// Use a 'pin' MVCObject as the order of the domready and marker click events is not garanteed.
function openInfoWindow(marker) {
title.innerHTML = marker.getTitle();
htmlContent.innerHTML = marker.myHtml;
pin.set("position", marker.getPosition());
infowindow.open(map, marker);
}
// This Javascript is based on code provided by the
// Community Church Javascript Team
// http://www.bisphamchurch.org.uk/
// http://econym.org.uk/gmap/
// from the v2 tutorial page at:
// http://econym.org.uk/gmap/basic3.htm
google.maps.event.addDomListener(window, 'load', initialize);
var xmlData = '<markers> <marker lat="43.65654" lng="-79.90138" html="Some stuff to display in the<br>First Info Window" label="Marker One" /> <marker lat="43.91892" lng="-78.89231" html="Some stuff to display in the<br>Second Info Window" label="Marker Two" /> <marker lat="43.82589" lng="-79.10040" html="Some stuff to display in the<br>Third Info Window" label="Marker Three" /></markers> ';
/**
* Parses the given XML string and returns the parsed document in a
* DOM data structure. This function will return an empty DOM node if
* XML parsing is not supported in this browser.
* #param {string} str XML string.
* #return {Element|Document} DOM.
*/
function xmlParse(str) {
if (typeof ActiveXObject != 'undefined' && typeof GetObject != 'undefined') {
var doc = new ActiveXObject('Microsoft.XMLDOM');
doc.loadXML(str);
return doc;
}
if (typeof DOMParser != 'undefined') {
return (new DOMParser()).parseFromString(str, 'text/xml');
}
return createElement('div', null);
}
html,
body {
height: 100%;
}
<script src="https://maps.google.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<!-- you can use tables or divs for the overall layout -->
<table border="1">
<tr>
<td>
<div id="map_canvas" style="width: 550px; height: 450px"></div>
</td>
<td valign="top" style="width:150px; text-decoration: underline; color: #4444ff;">
<div id="side_bar"></div>
</td>
</tr>
</table>

Related

Add custom image (or marker color) to markers (using markerCluster)

Can someone please help me how to bind a custom image marker to this script?
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false&v=3"></script>
<script type="text/javascript" src="http://google-maps-utility-library-v3.googlecode.com/svn/trunk/markerclusterer/src/markerclusterer.js"></script>
<script type="text/javascript" src="scripts/downloadxml.js"></script>
<style type="text/css">
html, body { height: 100%; }
</style>
<script type="text/javascript">
//<![CDATA[
// this variable will collect the html which will eventually be placed in the side_bar
var side_bar_html = "";
// arrays to hold copies of the markers and html used by the side_bar
// because the function closure trick doesnt work there
var gmarkers = [];
// global "map" variable
var map = null;
var markerclusterer = null;
// A function to create the marker and set up the event window function
function createMarker(latlng, name, html) {
var contentString = html;
var marker = new google.maps.Marker({
position: latlng,
// map: map,
zIndex: Math.round(latlng.lat()*-100000)<<5
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(contentString);
infowindow.open(map,marker);
});
// save the info we need to use later for the side_bar
gmarkers.push(marker);
// add a line to the side_bar html
side_bar_html += '<a href="javascript:myclick(' + (gmarkers.length-1) + ')">' + name + '<\/a><br>';
}
// This function picks up the click and opens the corresponding info window
function myclick(i) {
google.maps.event.trigger(gmarkers[i], "click");
}
function initialize() {
// create the map
var myOptions = {
zoom: 7,
center: new google.maps.LatLng(52.13263,5.29127),
mapTypeControl: true,
mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU},
navigationControl: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
google.maps.event.addListener(map, 'click', function() {
infowindow.close();
});
// Read the data from example.xml
downloadUrl("dataxml.cfm", function(doc) {
var xmlDoc = xmlParse(doc);
var markers = xmlDoc.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
// obtain the attribues of each marker
var lat = parseFloat(markers[i].getAttribute("lat"));
var lng = parseFloat(markers[i].getAttribute("lng"));
var marker_image = parseFloat(markers[i].getAttribute("markerimage"));
var image = {
url: marker_image,
size: new google.maps.Size(71, 132),
origin: new google.maps.Point(0, 0),
scaledSize: new google.maps.Size(71, 132)
};
var point = new google.maps.LatLng(lat,lng);
var id = markers[i].getAttribute("id");
var country = markers[i].getAttribute("country");
var html="<b>"+country+"</b><br><span style='color:white'>"+id+"</span>";
// create the marker
var marker = createMarker(point,country+" "+id,html);
}
markerCluster = new MarkerClusterer(map, gmarkers);
});
}
var infowindow = new google.maps.InfoWindow(
{
size: new google.maps.Size(150,50)
});
// This Javascript is based on code provided by the
// Community Church Javascript Team
// http://www.bisphamchurch.org.uk/
// http://econym.org.uk/gmap/
// from the v2 tutorial page at:
// http://econym.org.uk/gmap/basic3.htm
//]]>
</script>
</head>
<body style="margin:0px; padding:0px;" onload="initialize()">
<div id="map_canvas" style="width: 752px; height: 600px"></div>
</body>
</html>
The XML is simple:
<markers>
<marker markerimage="https://developers.google.com/maps/documentation/javascript/examples/full/images/beachflag.png" id="value" lat="value" lng="value" country="value" />
I have tried to add "icon: image" to the create marker part, but I can't figured it out.I have tried to add "icon: image" to the create marker part, but I can't figured it out.
You need to pass the custom icon into the createMarker function:
// create the marker
var marker = createMarker(point, country + " " + id, html, marker_image);
updated createMarker function:
// A function to create the marker and set up the event window function
function createMarker(latlng, name, html, icon) {
var contentString = html;
var marker = new google.maps.Marker({
position: latlng,
icon: icon,
// map: map,
zIndex: Math.round(latlng.lat() * -100000) << 5
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(contentString);
infowindow.open(map, marker);
});
// save the info we need to use later for the side_bar
gmarkers.push(marker);
// add a line to the side_bar html
side_bar_html += '<a href="javascript:myclick(' + (gmarkers.length - 1) + ')">' + name + '<\/a><br>';
}
proof of concept fiddle
code snippet:
function initialize() {
map = new google.maps.Map(
document.getElementById("map_canvas"), {
center: new google.maps.LatLng(40.735657, -74.1723667),
zoom: 10,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
google.maps.event.addListener(map, 'click', function() {
infowindow.close();
});
// Read the data from dataxml.cfm
// downloadUrl("dataxml.cfm", function(doc) {
var xmlDoc = xmlParse(xmlData);
var markers = xmlDoc.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
// obtain the attribues of each marker
var lat = parseFloat(markers[i].getAttribute("lat"));
var lng = parseFloat(markers[i].getAttribute("lng"));
var marker_image = markers[i].getAttribute("markerimage");
var image = {
url: marker_image,
size: new google.maps.Size(71, 132),
origin: new google.maps.Point(0, 0),
scaledSize: new google.maps.Size(71, 132)
};
var point = new google.maps.LatLng(lat, lng);
var id = markers[i].getAttribute("id");
var country = markers[i].getAttribute("country");
var html = "<b>" + country + "</b><br><span style='color:blue'>" + id + "</span>";
// create the marker
var marker = createMarker(point, country + " " + id, html, marker_image);
}
markerCluster = new MarkerClusterer(map, gmarkers);
// });
}
var infowindow = new google.maps.InfoWindow({
size: new google.maps.Size(150, 50)
});
// A function to create the marker and set up the event window function
function createMarker(latlng, name, html, icon) {
var contentString = html;
var marker = new google.maps.Marker({
position: latlng,
icon: icon,
zIndex: Math.round(latlng.lat() * -100000) << 5
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(contentString);
infowindow.open(map, marker);
});
// save the info we need to use later for the side_bar
gmarkers.push(marker);
// add a line to the side_bar html
side_bar_html += '<a href="javascript:myclick(' + (gmarkers.length - 1) + ')">' + name + '<\/a><br>';
}
// global variables
var side_bar_html = "";
var gmarkers = [];
var map = null;
var markerclusterer = null;
// This function picks up the click and opens the corresponding info window
function myclick(i) {
google.maps.event.trigger(gmarkers[i], "click");
}
google.maps.event.addDomListener(window, "load", initialize);
//New York, NY, USA (40.7127837, -74.0059413
//Newark, NJ, USA (40.735657, -74.1723667)
var xmlData = '<markers><marker markerimage="https://developers.google.com/maps/documentation/javascript/examples/full/images/beachflag.png" id="NYC" lat="40.7127837" lng="-74.0059413" country="USA" /><marker markerimage="https://developers.google.com/maps/documentation/javascript/examples/full/images/beachflag.png" id="NWK" lat="40.735657" lng="-74.1723667" country="USA" /></markers>';
function xmlParse(str) {
if (typeof ActiveXObject != 'undefined' && typeof GetObject != 'undefined') {
var doc = new ActiveXObject('Microsoft.XMLDOM');
doc.loadXML(str);
return doc;
}
if (typeof DOMParser != 'undefined') {
return (new DOMParser()).parseFromString(str, 'text/xml');
}
return createElement('div', null);
}
html,
body,
#map_canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<script src="https://google-maps-utility-library-v3.googlecode.com/svn/trunk/markerclusterer/src/markerclusterer.js"></script>
<div id="map_canvas"></div>

Refresh DownloadUrl on google map v3 and remove old markers

Hi I had a script and a xml file with 10.000 markers in it. I use markercluster to display the markers, but in order to fill the mobile browsers requierement I must begin the map at a certain zoom level (not to display to many markers). So I want to dynamically load the markers when the user change the zoom or viewport.
Here is my script. I thing I can't get the lat and lng of the LatLngBounds of the current viewport :
var customIcons = {
chambrehote: {
icon: '/wp-content/themes/codium-extend/images/chambre.png',
shadow: '/wp-content/themes/codium-extend/images/icon-shadow.png'
}
};
function initialize() {
var cluster = [];
var map = new google.maps.Map(document.getElementById("map_canvas"), {
center: new google.maps.LatLng('45.7676067','4.8351733'),
scrollwheel: false,
zoom: 12,
mapTypeId: 'roadmap'
});
var mcOptions = {gridSize: 100, styles: [
{
textColor: 'black',
height: 80,
url: "/wp-content/themes/codium-extend/images/cluster-m1.png",
width: 90
},
{
textColor: 'black',
height: 80,
url: "/wp-content/themes/codium-extend/images/cluster-m2.png",
width: 90
},
{
textColor: 'black',
height: 80,
url: "/wp-content/themes/codium-extend/images/cluster-m3.png",
width: 90
}
]};
var infoWindow = new google.maps.InfoWindow;
var bounds = new google.maps.LatLngBounds();
var swPoint = bounds.getSouthWest();
var nePoint = bounds.getNorthEast();
var swLat = swPoint.lat();
var swLng = swPoint.lng();
var neLat = nePoint.lat();
var neLng = nePoint.lng();
downloadUrl("/wp-content/themes/codium-extend/search/search_chambres.php?&type=chambrehote&codgeo=<?php echo $CODGEO ; ?>&radius=200&lat1="+swLat+"&lng1="+swLng+"&lat2="+neLat+"&lng2="+neLng+"", function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var name = markers[i].getAttribute("name");
var address = markers[i].getAttribute("ville");
var slug = markers[i].getAttribute("slug");
var stars = markers[i].getAttribute("stars");
var type = markers[i].getAttribute("type");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var html = "<b>" + name + "</b> " + "<br/>" + "" + "><a href=" + "/chambre-d-hote/" + slug + "/>lien vers la fiche</a>";
var icon = customIcons[type] || {};
//var icon = customIcons[type] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
icon: icon.icon,
shadow: icon.shadow
});
bindInfoWindow(marker, map, infoWindow, html);
//bounds.extend(point);
//map.fitBounds(bounds);
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() { infowindow.setContent(markers[i].getAttribute("name"));
infowindow.open(map, marker);
}
})(marker, i));
cluster.push(marker);
}
var mc = new MarkerClusterer(map,cluster,mcOptions);
});
}
function bindInfoWindow(marker, map, infoWindow, html) {
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(html);
infoWindow.open(map, marker);
});
}
function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function doNothing() {}
function changePosition() {
var position = document.getElementById('position').value;
adUnit.setPosition(google.maps.ControlPosition[position]);
}
First point :
I think I couldn't get the value of swLat, swLng... for passing them to downloadUrl
And second point I certainly miss a listener somewhere but don't know where !
Thanks for your inputs
---- EDIT ----
Right now I can load dynamically the data when the idle is changed, but (there is a but) now each change a new marker is add even if it's already on the map. Is there a way to clean all the markers when the idle change before loading the new ones?
var cluster = [];
var map = new google.maps.Map(document.getElementById("map"), {
zoom: 12,
center: new google.maps.LatLng('45.7676067','4.8351733'),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var mcOptions = {gridSize: 100, styles: [
{
textColor: 'black',
height: 80,
url: "/wp-content/themes/codium-extend/images/cluster-m1.png",
width: 90
},
{
textColor: 'black',
height: 80,
url: "/wp-content/themes/codium-extend/images/cluster-m2.png",
width: 90
},
{
textColor: 'black',
height: 80,
url: "/wp-content/themes/codium-extend/images/cluster-m3.png",
width: 90
}
]};
var infoWindow = new google.maps.InfoWindow;
google.maps.event.addListener(map, 'idle', function() {
var bounds = map.getBounds();
var swPoint = bounds.getSouthWest();
var nePoint = bounds.getNorthEast();
var swLat = swPoint.lat();
var swLng = swPoint.lng();
var neLat = nePoint.lat();
var neLng = nePoint.lng();
// alert(swLng);
downloadUrl("/wp-content/themes/codium-extend/search/search_chambres.php?lat=45.7676067&lng=4.8351733&type=chambrehote&codgeo=<?php echo $CODGEO ; ?>&radius=2000&lat1="+swLat+"&lng1="+swLng+"&lat2="+neLat+"&lng2="+neLng+"", function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var name = markers[i].getAttribute("name");
var address = markers[i].getAttribute("ville");
var slug = markers[i].getAttribute("slug");
var stars = markers[i].getAttribute("stars");
var type = markers[i].getAttribute("type");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var html = "<b>" + name + "</b> " + "<br/>" + "" + "><a href=" + "/chambre-d-hote/" + slug + "/>lien vers la fiche</a>";
var icon = customIcons[type] || {};
//var icon = customIcons[type] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
icon: icon.icon,
shadow: icon.shadow
});
bindInfoWindow(marker, map, infoWindow, html);
//bounds.extend(point);
//map.fitBounds(bounds);
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(markers[i].getAttribute("name"));
infowindow.open(map, marker);
}
})(marker, i));
cluster.push(marker);
}
var mc = new MarkerClusterer(map,cluster,mcOptions);
});
});
function bindInfoWindow(marker, map, infoWindow, html) {
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(html);
infoWindow.open(map, marker);
});
}
function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function doNothing() {}
function changeFormat() {
var format = document.getElementById('format').value;
adUnit.setFormat(google.maps.adsense.AdFormat[format]);
}
function changePosition() {
var position = document.getElementById('position').value;
adUnit.setPosition(google.maps.ControlPosition[position]);
}

Infobubble only displaying content from last marker added via PHP/Mysql with tabs

I've been trying to get Infobubbles to work with 2 tabs on a map populated with markers from a Mysql database with an ajax call.
The problem is that every infobubble is displaying the same content in the tabs, from the last marker added. Here is the entire js script, any help is greatly appreciated.
var script = '<script type="text/javascript" src="http://google-maps-' +
'utility-library-v3.googlecode.com/svn/trunk/infobubble/src/infobubble';
script += '.js"><' + '/script>';
document.write(script);
var customIcons = {
free: {
icon: 'http://labs.google.com/ridefinder/images/mm_20_blue.png',
animation: google.maps.Animation.DROP,
shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
},
paid: {
icon: 'http://labs.google.com/ridefinder/images/mm_20_red.png',
animation: google.maps.Animation.DROP,
shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
}
};
// End Custom Icons
var map, infoBubble;
function initialize() {
var myOptions = {
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map'),
myOptions);
// Try HTML5 geolocation
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position)
{
var pos = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
var marker = new google.maps.Marker({
map: map,
position: pos,
icon:'images/markers/you.png',
animation: google.maps.Animation.DROP,
title: 'Your Location.'
});
infoBubble = new InfoBubble({
maxWidth: 300,
borderRadius: 10,
borderWidth: 1,
borderColor: '#2c2c2c',
shadowStyle: 1
});
var infoWindow = new google.maps.InfoWindow;
// Change this depending on the name of your PHP file
downloadUrl("phpsqlajax_genxml.php", function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++)
{
var name = markers[i].getAttribute("name");
var address = markers[i].getAttribute("address");
var citystate = markers[i].getAttribute("citystate");
var phone = markers[i].getAttribute("phone");
var type = markers[i].getAttribute("type");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var html = "<b>" + name + "</b> <br/>" + address + "<br/>" + citystate + "<br/>" + phone; //html inside InfoWindow
var description = "<b>" + name + "</b> <br/>" + address + "<br/>" + citystate + "<br/>" + phone; //html inside InfoWindow
var icon = customIcons[type] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
icon: icon.icon,
shadow: icon.shadow,
animation: google.maps.Animation.DROP
});
bindInfoWindow(marker, map, infoBubble, html, description);
}
infoBubble.addTab('Tab 1', html);
infoBubble.addTab('Tab 2', description);
});
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 infoBubble = new google.maps.infoBubble(options);
map.setCenter(options.position);
}
// Additional functions related to the DB Listing function
function bindInfoWindow(marker, map, infoBubble, html) {
google.maps.event.addListener(marker, 'click', function() {
//infoBubble.setContent(html);
infoBubble.open(map, marker);
});
}
function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function doNothing() {}
function addTab() {
var title = document.getElementById('tab-title').value;
var content = document.getElementById('tab-content').value;
if (title != '' && content != '') {
infoBubble.addTab(title, content);
}
}
google.maps.event.addDomListener(window, 'load', initialize);
The code that sets the content depending on the marker is commented out:
//infoBubble.setContent(html);
Therefor the content of the last infowindow created is always displayed.
working example, including the tab content
Q problem in google map information window on marker click when click on next marker it opens the info window with tabs but when again click on next marker then it oepns the info window with tabs but the prevoius tabs did not closed herte is the code
google.maps.event.addListener(marker, 'click', (function(marker, contentString) {
return function() {
infoBubble.addTab('Tab 1', contentString);
infoBubble.addTab('Tab 2', contentString12);
infoBubble.setContent(contentString);
infoBubble.close('Tab 1', contentString);
infoBubble.open(map,marker);

Trouble clearing overlay when i reload a new set of markers in gmaps

I have a gmap and I only want to display markers in the viewable area. I have added a listener to get the bounds of the map and call gather the markers within the bounds. the problem is that when i bounds change, i want to clear the map and reload with the updated markers. currently the map will just continue to reload the markers on top of each other which makes the map extremely slow. I have tried:
google.maps.event.addListener(map, 'bounds_changed', function () {
clearOverlays();
loadMapFromCurrentBounds(map);
});
And that will not load any markers at all. I have also tried:
function loadMapFromCurrentBounds(map) {
clearOverlays();
And this will not load any markers either. Below is the code that will load all markers and functions as i want it to with the exception of clearing the old markers when the bounds change.
function load() {
var map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(40, -100),
zoom: 4,
mapTypeId: 'roadmap'
});
google.maps.event.addListener(map, 'bounds_changed', function () {
loadMapFromCurrentBounds(map);
});
}
function clearOverlays() {
if (markers) {
for (i in markers) {
markers[i].setMap(null);
}
}
}
function loadMapFromCurrentBounds(map) {
clearOverlays();
var infoWindow = new google.maps.InfoWindow;
var bounds = map.getBounds(); // First, determine the map bounds
var swPoint = bounds.getSouthWest(); // Then the points
var nePoint = bounds.getNorthEast();
// Change this depending on the name of your PHP file
var searchUrl = 'Viewport_Search.php?west=' + swPoint.lat() + '&east=' + nePoint.lat() + '&south=' + swPoint.lng() + '&north=' + nePoint.lng();
downloadUrl(searchUrl, function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var name = markers[i].getAttribute("name");
var address = markers[i].getAttribute("address");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var html = "<b>" + name + "</b> <br/>" + address;
var marker = new google.maps.Marker({
map: map,
position: point,
});
bindInfoWindow(marker, map, infoWindow, html);
}
});
}
function bindInfoWindow(marker, map, infoWindow, html) {
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(html);
infoWindow.open(map, marker);
});
}
function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function doNothing() {}
Please help... I have been beating my head against the computer all night researching and trying to figure this out. Feel free to email and/or ask for any questions.
You cant remove all markers, but it is possible to setMap to null on every visible marker.
I am doing it like that
add markers array to map object
add clearAllMarkers function to map object
every marker is added to the map is also added to markers array
clearAllMarkers function is something like that:
for (var idx=0;idx<=map.markers.length;idx++){
map.markers[idx].setMap(null);
}
I belive you are adding separate markers object to you're markers array. You're markers array should be full of markers references!!!
var map = []; //elrado's code
function load() {
var map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(40, -100),
zoom: 4,
mapTypeId: 'roadmap'
});
map.markers = [];//elrado's code (add narkers.array to map object)
google.maps.event.addListener(map, 'bounds_changed', function () {
loadMapFromCurrentBounds(map);
});
}
function clearOverlays() {
if (map.markers) {
for (i in map.markers) { //Might be you'll need to use map.markers.length
markers[i].setMap(null);
}
map.markers = [];//reinit map.markers.array
}
}
function loadMapFromCurrentBounds(map) {
clearOverlays();
var infoWindow = new google.maps.InfoWindow;
var bounds = map.getBounds(); // First, determine the map bounds
var swPoint = bounds.getSouthWest(); // Then the points
var nePoint = bounds.getNorthEast();
// Change this depending on the name of your PHP file
var searchUrl = 'Viewport_Search.php?west=' + swPoint.lat() + '&east=' + nePoint.lat() + '&south=' + swPoint.lng() + '&north=' + nePoint.lng();
downloadUrl(searchUrl, function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var name = markers[i].getAttribute("name");
var address = markers[i].getAttribute("address");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var html = "<b>" + name + "</b> <br/>" + address;
var marker = new google.maps.Marker({
map: map,
position: point,
});
map.markers.push(marker);//elrado's code
bindInfoWindow(marker, map, infoWindow, html);
}
});
}
function bindInfoWindow(marker, map, infoWindow, html) {
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(html);
infoWindow.open(map, marker);
});
}
function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function doNothing() {}
I have to warn you that this was written from the head (no test), but something like that should work. Basicly you are setting setMap(null) on separate markers not on objects you're showing on the map.
Below is the complete code solution to the problem.. Thanks for your help.
var map; //elrado's code
var markersArray = []; //elrados's code create array for markers
function load() {
map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(33.553029,-112.054017),
zoom: 13,
mapTypeId: 'roadmap'
});
google.maps.event.addListener(map, 'tilesloaded', function () {
clearOverlays()
loadMapFromCurrentBounds(map);
});
}
function clearOverlays() { //clear overlays function
if (markersArray) {
for (i in markersArray) {
markersArray[i].setMap(null);
}
}
}
function loadMapFromCurrentBounds(map) {
var infoWindow = new google.maps.InfoWindow;
var bounds = map.getBounds(); // First, determine the map bounds
var swPoint = bounds.getSouthWest(); // Then the points
var nePoint = bounds.getNorthEast();
// Change this depending on the name of your PHP file
var searchUrl = 'Viewport_Search.php?west=' + swPoint.lat() + '&east=' + nePoint.lat() + '&south=' + swPoint.lng() + '&north=' + nePoint.lng();
downloadUrl(searchUrl, function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var name = markers[i].getAttribute("name");
var address = markers[i].getAttribute("address");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var html = "<b>" + name + "</b> <br/>" + address;
var marker = new google.maps.Marker({
map: map,
position: point,
});
markersArray.push(marker); //eldorado's code Define the array to put markers in
bindInfoWindow(marker, map, infoWindow, html);
}
});
}
function bindInfoWindow(marker, map, infoWindow, html) {
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(html);
infoWindow.open(map, marker);
});
}
function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function doNothing() {}

Disable point-of-interest information window using Google Maps API v3

I have a custom map with an information bubble and custom markers. When I zoom into points of interest such as parks and universities appear and when I click an information window opens. How do I disable the info window?
My code is as follows:
var geocoder;
var map;
var infoBubble;
var dropdown = "";
var gmarkers = [];
var hostel_icon = new google.maps.MarkerImage('/resources/hostel_blue_icon.png',
new google.maps.Size(28,32),
new google.maps.Point(0,0),
new google.maps.Point(14,32));
var bar_icon = new google.maps.MarkerImage('/resources/bar_red_icon.png',
new google.maps.Size(28,32),
new google.maps.Point(0,0),
new google.maps.Point(14,32));
var icon_shadow = new google.maps.MarkerImage('/resources/myicon_shadow.png',
new google.maps.Size(45,32),
new google.maps.Point(0,0),
new google.maps.Point(12,32));
var customIcons = {
hostel: {
icon: hostel_icon,
shadow: icon_shadow
},
bar: {
icon: bar_icon,
shadow: icon_shadow
}
};
function initialize() {
var latlng = new google.maps.LatLng(12.82364, 26.29987);
var myMapOptions = {
zoom: 2,
center: latlng,
panControl: false,
scaleControl: true,
mapTypeId: google.maps.MapTypeId.TERRAIN,
mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR},
navigationControlOptions: {style: google.maps.NavigationControlStyle.DEFAULT}
}
map = new google.maps.Map(document.getElementById("map_canvas"), myMapOptions);
infoBubble = new InfoBubble({
shadowStyle: 0,
padding: 0,
backgroundColor: 'rgb(57,57,57)',
borderRadius: 5,
arrowSize: 10,
borderWidth: 1,
maxWidth: 400,
borderColor: '#2c2c2c',
disableAutoPan: false,
hideCloseButton: true,
arrowPosition: 50,
backgroundClassName: 'phoney',
arrowStyle: 0
});
// Change this depending on the name of your PHP file
downloadUrl("phpsqlajax_genxml_2.php", function(data) {
var xml = parseXml(data);
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var bar_name = markers[i].getAttribute("bar_name");
var hostel_name = markers[i].getAttribute("hostel_name");
var street = markers[i].getAttribute("street");
var city = markers[i].getAttribute("city");
var postcode = markers[i].getAttribute("postcode");
var country = markers[i].getAttribute("country");
var page = markers[i].getAttribute("page");
var map_photo = markers[i].getAttribute("map_photo");
var type = markers[i].getAttribute("type");
var category = markers[i].getAttribute("category");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var html = '<div class="infowindow"><div class="iwPhoto" style="width: 105px; height: 65px;">' + "' + "<a href='" + page + "'>" + hostel_name + "" + '</div><div class="iwCategory" style="height: 15px;">' + category + '</div><div class="iwCity" style="height: 29px;">' + "' + "<a href='" + page + "'><img src='/resources/arrow.png'/>" + '</div></div></div>';
var icon = customIcons[type] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
icon: icon.icon,
shadow: icon.shadow,
title: bar_name
});
marker.bar_name = bar_name;
marker.category = category;
bindInfoBubble(marker, map, infoBubble, html, bar_name);
gmarkers.push(marker);
str = '<option selected> - Select a club - </option>';
for (j=0; j < gmarkers.length; j++){
str += '<option value="'+gmarkers[j].bar_name+'">'+gmarkers[j].bar_name+', '+gmarkers[j].category+'</option>';
}
var str1 ='<form name="form_city" action=""><select style="width:150px;" id="select_city" name="select_cityUrl" onchange="handleSelected(this);">';
var str2 ='</select></form>';
dropdown = str1 + str + str2;
}
document.getElementById("dd").innerHTML = dropdown;
});
}
function handleSelected(opt) {
var indexNo = opt[opt.selectedIndex].index;
google.maps.event.trigger(gmarkers[indexNo-1], "click");
}
function bindInfoBubble(marker, map, infoBubble, html) {
google.maps.event.addListener(marker, 'click', function() {
infoBubble.setContent(html);
infoBubble.open(map, marker);
google.maps.event.addListener(map, "click", function () {
infoBubble.close();
});
});
}
function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request.responseText, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function parseXml(str) {
if (window.ActiveXObject) {
var doc = new ActiveXObject('Microsoft.XMLDOM');
doc.loadXML(str);
return doc;
} else if (window.DOMParser) {
return (new DOMParser).parseFromString(str, 'text/xml');
}
}
function doNothing() {}
UPDATE Google Maps JavaScript API V3
You can set clickableIcons to false in MapOptions. This will keep the POI icons but disable the infowindows just as you want.
function initialize() {
var myMapOptions = { clickableIcons: false }
}
Further details here...
https://developers.google.com/maps/documentation/javascript/3.exp/reference#MapOptions
See the other answers for the clickable: false answer.
However, if you want it clickable, but no infowindow, call stop() on the event to prevent the infowindow from showing, but still get the location info:
map.addListener('click', function (event) {
// If the event is a POI
if (event.placeId) {
// Call event.stop() on the event to prevent the default info window from showing.
event.stop();
// do any other stuff you want to do
console.log('You clicked on place:' + event.placeId + ', location: ' + event.latLng);
}
}
For more info, see the docs.
Other option: completely remove the POI-icons, and not only the infoWindow:
var mapOptions = {
styles: [{ featureType: "poi", elementType: "labels", stylers: [{ visibility: "off" }]}]
};
var map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
You can do this by creating a styled map without labels for the points of interest.
This maintains the topography and other nice pieces of information on the map, but removes the markers.
var remove_poi = [
{
"featureType": "poi",
"elementType": "labels",
"stylers": [
{ "visibility": "off" }
]
}
]
map.setOptions({styles: remove_poi})
You could consider the following approach to disable POI Info Window:
function disablePOIInfoWindow(){
var fnSet = google.maps.InfoWindow.prototype.set;
google.maps.InfoWindow.prototype.set = function () {
};
}
Example
function initMap() {
var latlng = new google.maps.LatLng(40.713638, -74.005529);
var myOptions = {
zoom: 17,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
disablePOIInfoWindow();
}
function disablePOIInfoWindow(){
var fnSet = google.maps.InfoWindow.prototype.set;
google.maps.InfoWindow.prototype.set = function () {
alert('Ok');
};
}
google.maps.event.addDomListener(window, 'load', initMap);
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#map_canvas {
height: 100%;
}
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<div id="map_canvas"></div>
The above example affects all the info windows, so if you need to disable only POI Info Window, then we could introduce flag to determine whether it is POI Info Window or not:
function disablePOIInfoWindow(){
var fnSet = google.maps.InfoWindow.prototype.set;
google.maps.InfoWindow.prototype.set = function () {
if(this.get('isCustomInfoWindow'))
fnSet.apply(this, arguments);
};
}
Example
function initMap() {
var latlng = new google.maps.LatLng(40.713638, -74.005529);
var myOptions = {
zoom: 17,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var infowindow = new google.maps.InfoWindow({
content: ''
});
infowindow.set('isCustomInfoWindow',true);
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
disablePOIInfoWindow();
google.maps.event.addListener(map, 'click', function (event) {
infowindow.setContent(event.latLng.lat() + "," + event.latLng.lng());
infowindow.setPosition(event.latLng);
infowindow.open(map, this);
});
}
function disablePOIInfoWindow(){
var fnSet = google.maps.InfoWindow.prototype.set;
google.maps.InfoWindow.prototype.set = function () {
if(this.get('isCustomInfoWindow'))
fnSet.apply(this, arguments);
};
}
//google.maps.event.addDomListener(window, 'load', initMap);
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#map_canvas {
height: 100%;
}
<div id="map_canvas"></div>
<script src="https://maps.googleapis.com/maps/api/js?callback=initMap"
async defer></script>
Simply style the map to not show Points of Interest. This is simple and does not breach Google's terms of service.
eg
mapOpts = {
styles: [
{
featureType: "poi",
stylers: [
visibility: "off"
]
}
]
};
$("#my-map").gmap(mapOpts).on("init", function(evt, map){
// do stuff with the initialised map
});
If you want the data without getting the InfoWindow HTML showing at all, you simply have to re-work the prototype of google.maps.InfoWindow:
google.maps.InfoWindow.prototype.open = function () {
return this; //prevent InfoWindow to appear
}
google.maps.InfoWindow.prototype.setContent = function (content) {
if (content.querySelector) {
var addressHTML = content.querySelector('.address');
var address = addressHTML.innerHTML.replace(/<[^>]*>/g, ' ').trim();
var link = content.querySelector('a').getAttribute('href');
var payload = {
header: 'event',
eventName: 'place_picked',
data: {
name: content.querySelector('.title').innerHTML.trim(),
address: address,
link: link
}
};
console.log('emit your event/call your function', payload);
}
};
We can do it by handling clicks on poi, Google api has provided a way to detect clicks on POI as per this article
Based on article above Here is a simpler version of code that can be used to stop the clicks on POI
function initMap() {
map = new google.maps.Map(document.getElementById('map'), myOptions);
var clickHandler = new ClickEventHandler(map, origin);
}
var ClickEventHandler = function (map, origin) {
this.origin = origin;
this.map = map;
this.map.addListener('click', this.handleClick.bind(this));
};
ClickEventHandler.prototype.handleClick = function (event) {
//console.log('You clicked on: ' + event.latLng);
if (event.placeId) {
//console.log('You clicked on place:' + event.placeId);
// Calling e.stop() on the event prevents the default info window from
// showing.
// If you call stop here when there is no placeId you will prevent some
// other map click event handlers from receiving the event.
event.stop();
}
}