google maps updating div with info window event on map and sidebar - google-maps

I am using the following code to display my map plus 2 seperate div. One has a list of features (sidebar) and one has the result of the infowindow click event.
I can get the expected behavior when I click on the map, but the sidebar features, while correctly label on the map, do not update the "BottomInfoWindow" DIV. I cannot seem to get the right place to make that happen. On a less related note, I also would like to show the fusion table card in the "BottomInfoWindow" DIV, but haven't figured out how to incorporate that into a google map. If you know of an example that would be great too.
<style type="text/css">
html, body, #map_canvas {
width: 900px;
height: 550px;
margin: 0;
padding: 0;
}
.infowindow * {font-size: 90%; margin: 0}
.auto-style1 {
font-size: small;
}
</style>
<!--Load the AJAX API-->
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<!-- Initialize -->
<script type="text/javascript">
google.load('visualization', '1', {'packages':['corechart', 'table', 'geomap']});
var tableId ='1aa5D73bkLrD6aY7W7MaU5C4z-v6HRM6aWnhg19N5';
function createSidebar() {
//set the query using the parameter
var queryText = encodeURIComponent("http://www.google.com/fusiontables/gvizdata?tq=SELECT * FROM "+tableId);
var query = new google.visualization.Query(queryText);
var queryText = encodeURIComponent("SELECT 'Sample Location', 'X', 'Y' FROM "+tableId);
var query = new google.visualization.Query('http://www.google.com/fusiontables/gvizdata?tq=' + queryText);
//set the callback function
query.send(getData);
}
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(createSidebar);</script>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var FTresponse = null;
//define callback function, this is called when the results are returned
function getData(response) {
if (!response) {
alert('no response');
return;
}
if (response.isError()) {
alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}
FTresponse = response;
//for more information on the response object, see the documentation
//http://code.google.com/apis/visualization/documentation/reference.html#QueryResponse
numRows = response.getDataTable().getNumberOfRows();
numCols = response.getDataTable().getNumberOfColumns();
//concatenate the results into a string, you can build a table here
fusiontabledata = "<table><tr>";
// for(i = 0; i < numCols; i++) {
fusiontabledata += "<th>" + response.getDataTable().getColumnLabel(0) + "</th>";
// }
fusiontabledata += "</tr><tr>";
for(i = 0; i < numRows; i++) {
// for(j = 0; j < numCols; j++) {
fusiontabledata += "<td><a href='javascript:myFTclick("+i+")'>"+response.getDataTable().getValue(i, 0) + "</a></td>";
// }
fusiontabledata += "</tr><tr>";
}
fusiontabledata += "</table>"
//display the results on the page
document.getElementById('sidebar').innerHTML = fusiontabledata;
document.getElementById('BottomInfoWindow').innerHTML = event.infoWindowHtml;
}
function myFTclick(row) {
//var description = FTresponse.getDataTable().getValue(row,0);
var name = FTresponse.getDataTable().getValue(row,0);
var lat = FTresponse.getDataTable().getValue(row,2);
var lng = FTresponse.getDataTable().getValue(row,1);
var position = new google.maps.LatLng(lat, lng);
openInfoWindow(name, position);
}
function openInfoWindow(name, position) {
// Set up and create the infowindow
if (!infoWindow) infoWindow = new google.maps.InfoWindow({});
infoWindow.setOptions({
content: '<div class="FT_infowindow"><h3>' + name +
'</h3></div>',
pixelOffset: new google.maps.Size(0, 2),
position: position
});
// Infowindow-opening event handler
infoWindow.open(map);
}
var map = null;
var infoWindow = null;
function initialize() {
//SET CENTER
map = new google.maps.Map(document.getElementById('map_canvas'), {
center: new google.maps.LatLng(47.68635054275792, -117.21382726097107),
zoom: 16,
scrollwheel:false,
mapTypeControl: true,
streetViewControl: false,
overviewMapControl: true,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
},
// CONTROLS
zoomControl: true,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.SMALL
},
mapTypeId: 'hybrid'
});
layer = new google.maps.FusionTablesLayer({suppressInfoWindows: true,
query: { from: tableId, select: 'Y, X'}});
layer.setMap(map);
google.maps.event.addListener(layer, "click", function(event) {
infoWindow.close();
// alert("click:"+event.latLng+","+event.infoWindowHtml);
openInfoWindow(event.row["Sample Location"].value, event.latLng);
// infoWindow.setContent(event.infoWindowHtml);
// infoWindow.setPosition(event.latLng);
// infoWindow.open(map);
document.getElementById('BottomInfoWindow').innerHTML = event.infoWindowHtml;
});
infoWindow = new google.maps.InfoWindow();
// createSidebar();
}
</script>
</head>
<body onload="initialize()">
<table style="width:100%;"><tr><td>
<div id="map_canvas">
</div>
</td><td>
<div id="sidebar" style="width:120px;height:550px; overflow:auto" class="auto-style1">
</div>
</td></tr>
<tr><td colspan="2">
<div id="BottomInfoWindow" class="auto-style1">
Result
</div>
</td></tr>
</table>

I get a javascript error Uncaught TypeError: Cannot read property 'infoWindowHtml' of undefined in the posted code on this line:
document.getElementById('BottomInfoWindow').innerHTML = event.infoWindowHtml;
There is no event inside the getData function
If you want to use the code that exists, add that to openInfoWindow()
function openInfoWindow(name, position) {
// Set up and create the infowindow
if (!infoWindow) infoWindow = new google.maps.InfoWindow({});
infoWindow.setOptions({
content: '<div class="FT_infowindow"><h3>' + name +
'</h3></div>',
pixelOffset: new google.maps.Size(0, 2),
position: position
});
// Infowindow-opening event handler
infoWindow.open(map);
document.getElementById('BottomInfoWindow').innerHTML = infoWindow.getContent();
}
proof of concept fiddle
Note that the infoWindowHtml defined by the fusionTable (what your click listener is displaying in the "BottomInfoWindow" DIV) is not accessible from the sidebar, but you can recreate it in the openInfoWindow function.
To make them both the same (formated by the openInfoWindow function) change the fusionTablesLayer "click" handler as well:
google.maps.event.addListener(layer, "click", function (event) {
infoWindow.close();
// alert("click:"+event.latLng+","+event.infoWindowHtml);
openInfoWindow(event.row["Sample Location"].value, event.latLng);
// infoWindow.setContent(event.infoWindowHtml);
// infoWindow.setPosition(event.latLng);
// infoWindow.open(map);
document.getElementById('BottomInfoWindow').innerHTML = infoWindow.getContent();
});

Related

How to get a list of strings from FusionTablesLayer and associate it with the map

I have a google map built using FusionTablesLayer
How to get a list of strings from this FusionTablesLayer and associate it with the map. To click on an item from the list, a baloon was opened on the map.
Here is an example of the map http://air-in.ru/ajax/chat/test.php
This is an example of how a map should look.
<body>
<style type="text/css">
html, body, #googft-mapCanvas {
height: 100% !important;
margin: 0;
padding: 0;
width: 100% !important;
}
</style>
<script type="text/javascript" src="https://maps.google.com/maps/api/js?key=AIzaSyBxMTfLhegh_rO8w0-vRP_oKdaJOvhOUUI"></script>
<script type="text/javascript">
function initialize() {
var isMobile = (navigator.userAgent.toLowerCase().indexOf('android') > -1) ||
(navigator.userAgent.match(/(iPod|iPhone|iPad|BlackBerry|Windows Phone|iemobile)/));
if (isMobile) {
var viewport = document.querySelector("meta[name=viewport]");
viewport.setAttribute('content', 'initial-scale=1.0, user-scalable=no');
}
var mapDiv = document.getElementById('googft-mapCanvas');
mapDiv.style.width = isMobile ? '100%' : '500px';
mapDiv.style.height = isMobile ? '100%' : '300px';
var map = new google.maps.Map(mapDiv, {
center: new google.maps.LatLng(56.32085914650647, 62.40977352913535),
zoom: 4,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
map.controls[google.maps.ControlPosition.RIGHT_BOTTOM].push(document.getElementById('googft-legend-open'));
map.controls[google.maps.ControlPosition.RIGHT_BOTTOM].push(document.getElementById('googft-legend'));
layer = new google.maps.FusionTablesLayer({
map: map,
heatmap: { enabled: false },
query: {
select: "col0",
from: "1XlnmbK0m0s4rHdadG_hkmZP-dSr2ruBzQxnMK4Uv",
where: ""
},
options: {
styleId: 2,
templateId: 2
}
});
if (isMobile) {
var legend = document.getElementById('googft-legend');
var legendOpenButton = document.getElementById('googft-legend-open');
var legendCloseButton = document.getElementById('googft-legend-close');
legend.style.display = 'none';
legendOpenButton.style.display = 'block';
legendCloseButton.style.display = 'block';
legendOpenButton.onclick = function() {
legend.style.display = 'block';
legendOpenButton.style.display = 'none';
}
legendCloseButton.onclick = function() {
legend.style.display = 'none';
legendOpenButton.style.display = 'block';
}
}
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
<div id="googft-mapCanvas"></div>
</body>
You are looking for a "sidebar". The FustionTablesLayer doesn't allow direct access to the FusionTable data, but you can use the visualization API to query the table and display information in the sidebar, then like that information to the map.
From my example at http://www.geocodezip.com/v3_FusionTables_AfricaMap_kml_sidebar.html
code snippet:
google.load('visualization', '1', {
'packages': ['corechart', 'table', 'geomap']
});
function createSidebar() {
//set the query using the parameter
var queryText = encodeURIComponent("https://www.google.com/fusiontables/gvizdata?tq=SELECT * FROM 564705");
var query = new google.visualization.Query(queryText);
queryText = encodeURIComponent("SELECT 'description', 'name', 'Citizens', 'Country', 'Latitude', 'Longitude' FROM 564705");
query = new google.visualization.Query('https://www.google.com/fusiontables/gvizdata?tq=' + queryText);
//set the callback function
query.send(getData);
}
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(createSidebar);
var FTresponse = null;
//define callback function, this is called when the results are returned
function getData(response) {
if (!response) {
alert('no response');
return;
}
if (response.isError()) {
alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}
FTresponse = response;
//for more information on the response object, see the documentation
//http://code.google.com/apis/visualization/documentation/reference.html#QueryResponse
numRows = response.getDataTable().getNumberOfRows();
numCols = response.getDataTable().getNumberOfColumns();
//concatenate the results into a string, you can build a table here
fusiontabledata = "<table><tr>";
fusiontabledata += "<th>" + response.getDataTable().getColumnLabel(1) + "</th>";
fusiontabledata += "</tr><tr>";
for (i = 0; i < numRows; i++) {
fusiontabledata += "<td><a href='javascript:myFTclick(" + i + ")'>" + response.getDataTable().getValue(i, 1) + "</a></td>";
fusiontabledata += "</tr><tr>";
}
fusiontabledata += "</table>"
//display the results on the page
document.getElementById('sidebar').innerHTML = fusiontabledata;
}
function myFTclick(row) {
var description = FTresponse.getDataTable().getValue(row, 0);
var name = FTresponse.getDataTable().getValue(row, 1);
var lat = FTresponse.getDataTable().getValue(row, 4);
var lng = FTresponse.getDataTable().getValue(row, 5);
var position = new google.maps.LatLng(lat, lng);
// Set up and create the infowindow
if (!infoWindow) infoWindow = new google.maps.InfoWindow({});
infoWindow.setOptions({
content: '<div class="FT_infowindow"><h3>' + name +
'</h3><div>' + description + '</div></div>',
pixelOffset: new google.maps.Size(0, 2),
position: position
});
infoWindow.open(map);
}
var map = null;
var infoWindow = null;
function initialize() {
var africa = new google.maps.LatLng(1.56, 16.07);
map = new google.maps.Map(document.getElementById('map_canvas'), {
center: africa,
zoom: 3,
mapTypeId: 'hybrid'
});
layer = new google.maps.FusionTablesLayer(564705, {
suppressInfoWindows: true
});
layer.setMap(map);
google.maps.event.addListener(layer, "click", function(event) {
infoWindow.close();
infoWindow.setContent(event.infoWindowHtml);
infoWindow.setPosition(event.latLng);
infoWindow.open(map);
});
infoWindow = new google.maps.InfoWindow();
}
google.maps.event.addDomListener(window, 'load', initialize);
html,
body,
#map_canvas {
width: 100%;
height: 100%;
margin: 0px;
padding: 0px;
background-color: white;
}
.infowindow * {
font-size: 90%;
margin: 0
}
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="https://maps.google.com/maps/api/js"></script>
<table style="width:100%;height:100%">
<tr style="width:100%;height:100%">
<td style="width:100%;height:100%">
<div id="map_canvas"></div>
</td>
<td>
<div id="sidebar" style="width:260px;height:100%; overflow:auto"></div>
</td>
</tr>
</table>

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>

Integrating OverlappingMarkerSpidifier with our code

My team and I are working on a group project that plots incidents around College Station, TX. Most of the markers are located at one coordinate, so we're trying to integrate the OverlappingMarkerSpidifier code with ours, but I'm not quite sure how to do it. Could anyone help with this?
The code works for the most part, or at least the markers populate where they need to and I can get an infowindow to pop up for the topmost marker. The main issue is figuring out to transform this (from the above website):
for (var i = 0; i < window.mapData.length; i ++) {
var datum = window.mapData[i];
var loc = new L.LatLng(datum.lat, datum.lon);
var marker = new L.Marker(loc);
marker.desc = datum.d;
map.addLayer(marker);
oms.addMarker(marker); // <-- here
}
into something that will loop through our data instead.
Note: The original code had JSON values within it, but those have been removed for this post. Additionally, since this will probably make a difference, we hard coded our JSON data (I know, it's terrible practice, but we needed to do it at the time to start working with the map code itself)
<html>
<head>
<style>
#mapcanvas {
height: 300px;
margin: 0px;
padding: 300px;
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="http://jawj.github.io/OverlappingMarkerSpiderfier/bin/oms.min.js"></script>
<script>
//Load and center map on college station
var map;
function initialize() {
var mapOptions = {
zoom: 12,
center: new google.maps.LatLng(30.628769, -96.334816)
};
map = new google.maps.Map(document.getElementById('mapcanvas'), mapOptions);
//Create info window
var infowindow = new google.maps.InfoWindow({
content: ''
});
//Get and parse JSON data
$(document).ready(function(){
$("button").click(function(){
$.each(data.items, handleItem);
});
});
function handleItem(i, items) {
$('#placeholder').append("<li>Coord: " + items.lat + items.long + "Category:" + items.category + "</li>");
//Info window content
var contentString = '<div id=content">'+
'Incident Notice'+
'</div>'+
'<p id = "firstHeading" class="firstHeading">' + items.category + '<br></br>' + items.lat + ", " + items.long + '</p>' +
'</div>'
'Location: Texas A&M'
var img = 'http://www.google.com/mapfiles/marker.png';
var myLatLng = new google.maps.LatLng(items.lat, items.long);
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
icon: img
});
//Create info window on click and close when clicking a new marker
var oms = new OverlappingMarkerSpiderfier(map);
oms.addListener('click', function(marker, event) {
infowindow.setContent(contentString);
infowindow.open(map, marker);
});
oms.addListener('spiderfy', function(markers) {
for(var i = 0; i < markers.length; i ++) {
markers[i].setIcon(iconWithColor(spiderfiedColor));
markers[i].setShadow(null);
}
iw.close();
});
oms.addListener('unspiderfy', function(markers) {
for(var i = 0; i < markers.length; i ++) {
markers[i].setIcon(iconWithColor(usualColor));
markers[i].setShadow(shadow);
}
});
oms.addMarker(marker);
}
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="mapcanvas"></div>
<button>Get and Parse</button>
<p>
</p>
<ul id="placeholder">
</ul>
</body>
</html>
There are many problems with your code:
declare oms as global variable, only one instance, this will facilitate the use;
iconWithColor is not defined;
shadow is not defined;
on spiderfy listener, you are calling iw.close();. iw is not defined and is not the added in click listener. Change body of function to infoWindow.close();;
Se an example, may can help you:
<html>
<head>
<style>
#mapcanvas {
height: 300px;
margin: 0px;
padding: 300px;
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="http://jawj.github.io/OverlappingMarkerSpiderfier/bin/oms.min.js"></script>
<script>
var map;
var oms;
//Create info window (need only one)
var infowindow = new google.maps.InfoWindow();
function initialize() {
var mapOptions = {
zoom: 12,
center: new google.maps.LatLng(30.628769, -96.334816)
};
//Load and center map on college station
map = new google.maps.Map(document.getElementById('mapcanvas'), mapOptions);
oms = new OverlappingMarkerSpiderfier(map);
// listeners need to be registered only once
oms.addListener('click', function(marker, event) {
infowindow.setContent(marker.description);
infowindow.open(map, marker);
});
oms.addListener('spiderfy', function(markers) {
for(var i = 0; i < markers.length; i++) {
// markers[i].setIcon(iconWithColor(spiderfiedColor));
markers[i].setShadow(null);
}
infowindow.close();
});
oms.addListener('unspiderfy', function(markers) {
for(var i = 0; i < markers.length; i++) {
// markers[i].setIcon(iconWithColor(usualColor));
// markers[i].setShadow(shadow);
}
});
function handleItem(items) {
$('#placeholder').append("<li>Coord: " + items.lat + items.long + " Category: " + items.category + "</li>");
//Info window content
var contentString = '<div id=content">'+
'Incident Notice'+
'</div>'+
'<p id = "firstHeading" class="firstHeading">' + items.category + '<br></br>' + items.lat + ", " + items.long + '</p>' +
'</div>'
'Location: Texas A&M'
var img = 'http://www.google.com/mapfiles/marker.png';
var myLatLng = new google.maps.LatLng(items.lat, items.long);
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
icon: img
});
// to be possible in "click" show specific content
marker.description = contentString;
oms.addMarker(marker);
}
//Get and parse JSON data
$(document).ready(function(){
$("button").click(function(){
$.each(data.items, handleItem);
});
});
var item = {
lat: 30.628769,
long: -96.334816,
category: "Category - "
};
// for test only
for(var i = 5; i >= 0; i--) {
item.category += i;
handleItem(item);
}
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="mapcanvas"></div>
<button>Get and Parse</button>
<p></p>
<ul id="placeholder">
</ul>
</body>
</html>

Google maps adding streetview to each infowindow

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>

Google Maps V3: Draw German State Polygons?

I need to draw colored polygons over certain German states. What's the best way (or easiest, fastest, any really...) to do this? Do I need to somehow get all the outlines as lat/lon points and draw a polygon based on those? Or is there a better way?
You want to do something like this?
http://www.geocodezip.com/geoxml3_test/v3_FusionTables_query_sidebarF_local.html?country=Germany
It uses publicly available data in FusionTables, the Natural Earth Data set.
encrypted ID:
https://www.google.com/fusiontables/DataSource?docid=19lLpgsKdJRHL2O4fNmJ406ri9JtpIIk8a-AchA
numeric ID:
https://www.google.com/fusiontables/DataSource?dsrcid=420419
You can style them (color them) as you like.
code snippet:
// globals
var map = null;
var infoWindow = null;
var geoXml = null;
var geoXmlDoc = null;
var myLatLng = null;
var myOptions = null;
var mapCenter = null;
var geocodeTheCountry = true;
var gpolygons = [];
// Fusion Table data ID
var FT_TableID = "19lLpgsKdJRHL2O4fNmJ406ri9JtpIIk8a-AchA"; // 420419;
var CountryName = "Germany";
google.load('visualization', '1', {
'packages': ['corechart', 'table', 'geomap']
});
function createSidebar() {
// set the query using the parameters
var FT_Query2 = "SELECT 'name_0', 'name_1', 'kml_4326' FROM " + FT_TableID + " WHERE name_0 = '" + CountryName + "' ORDER by 'name_1'";
var queryText = encodeURIComponent(FT_Query2);
// alert("createSidebar query="+FT_Query2);
var query = new google.visualization.Query('http://www.google.com/fusiontables/gvizdata?tq=' + queryText);
//set the callback function
query.send(getData);
}
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(createSidebar);
var FTresponse = null;
myLatLng = new google.maps.LatLng(37.422104808, -122.0838851);
// these set the initial center, zoom and maptype for the map
// if it is not specified in the query string
var lat = 37.422104808;
var lng = -122.0838851;
var zoom = 18;
var maptype = google.maps.MapTypeId.ROADMAP;
if (!isNaN(lat) && !isNaN(lng)) {
myLatLng = new google.maps.LatLng(lat, lng);
}
infoWindow = new google.maps.InfoWindow();
//define callback function, this is called when the results are returned
function getData(response) {
if (!response) {
alert('no response');
return;
}
if (response.isError()) {
alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}
FTresponse = response;
//for more information on the response object, see the documentation
//http://code.google.com/apis/visualization/documentation/reference.html#QueryResponse
numRows = response.getDataTable().getNumberOfRows();
numCols = response.getDataTable().getNumberOfColumns();
fusiontabledata = "<table><tr>";
fusiontabledata += "<th>" + response.getDataTable().getColumnLabel(1) + "</th>";
// }
fusiontabledata += "</tr><tr>";
for (i = 0; i < numRows; i++) {
fusiontabledata += "<td><a href='javascript:myFTclick(" + i + ")'>" + response.getDataTable().getValue(i, 1) + "</a></td>";
// }
fusiontabledata += "</tr><tr>";
}
fusiontabledata += "</table>";
//display the results on the page
document.getElementById('sidebar').innerHTML = fusiontabledata;
}
function infoWindowContent(name, description) {
content = '<div class="FT_infowindow"><h3>' + name +
'</h3><div>' + description + '</div></div>';
return content;
}
function myFTclick(row) {
var description = FTresponse.getDataTable().getValue(row, 0);
var name = FTresponse.getDataTable().getValue(row, 1);
if (!gpolygons[row]) {
var kml = FTresponse.getDataTable().getValue(row, 2);
// create a geoXml3 parser for the click handlers
var geoXml = new geoXML3.parser({
map: map,
zoom: false,
infoWindow: infoWindow,
singleInfoWindow: true
});
geoXml.parseKmlString("<Placemark>" + kml + "</Placemark>");
geoXml.docs[0].gpolygons[0].setMap(null);
gpolygons[row] = geoXml.docs[0].gpolygons[0].bounds.getCenter();
}
var position = gpolygons[row];
if (!infoWindow) infoWindow = new google.maps.InfoWindow({});
infoWindow.setOptions({
content: infoWindowContent(name, description),
pixelOffset: new google.maps.Size(0, 2),
position: position
});
infoWindow.open(map);
}
function initialize() {
myOptions = {
zoom: zoom,
center: myLatLng,
mapTypeId: maptype
};
map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
var geocoder = new google.maps.Geocoder();
if (geocoder && geocodeTheCountry) {
geocoder.geocode({
'address': CountryName + " Country"
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
map.setCenter(results[0].geometry.location);
map.fitBounds(results[0].geometry.viewport);
} else {
alert("No results found");
}
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
var FT_Query = "SELECT 'kml_4326' FROM " + FT_TableID + " WHERE 'name_0' = '" + CountryName + "';";
var FT_Options = {
suppressInfoWindows: true,
query: {
from: FT_TableID,
select: 'kml_4326',
where: "'name_0' = '" + CountryName + "';"
},
styles: [{
polygonOptions: {
fillColor: "#FF0000",
fillOpacity: 0.35
}
}]
};
layer = new google.maps.FusionTablesLayer(FT_Options);
layer.setMap(map);
google.maps.event.addListener(layer, "click", function(event) {
infoWindow.close();
infoWindow.setContent(infoWindowContent(event.row.name_1.value, event.row.name_0.value));
infoWindow.setPosition(event.latLng);
infoWindow.open(map);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
html,
body {
width: 100%;
height: 100%;
margin: 0;
padding: 0;
}
#map_canvas {
width: 300px;
height: 100%
}
.infowindow * {
font-size: 90%;
margin: 0
}
<script src="https://geoxml3.googlecode.com/svn/branches/polys/geoxml3.js"></script>
<script src="http://www.google.com/jsapi"></script>
<script src="https://maps.googleapis.com/maps/api/js"></script>
<table style="width:100%; height:100%;">
<tr style="width:100%; height:90%;">
<td style="width:60%; height:100%;">
<div id="map_canvas"></div>
</td>
<td>
<div id="sidebar" style="width:300px;height:400px; overflow:auto"></div>
</td>
</tr>
</table>
Also, you could take a look at the Google GeoChart API, which is not that feature-rich but pretty easy to use. Try the following code in the API playground:
function drawVisualization() {
var data = google.visualization.arrayToDataTable([
['Province', 'Popularity'],
['Bremen', 100],
['Niedersachsen', 900],
['Saksen', 700],
['Saarland', 300],
['Bayern', 400]
]);
var options = {
region: 'DE',
displayMode: 'regions',
colorAxis: {colors: ['green', 'blue']},
resolution:'provinces'
};
var geochart = new google.visualization.GeoChart(
document.getElementById('visualization'));
geochart.draw(data, options, {width: 556, height: 347});
}
​