Open Fusion Table Layer info window onchange - google-fusion-tables

Using generated code from FusionTablesLayer Wizard, I am trying to determine how to open the info window onchange. The code below displays the marker perfectly, but I would like the info window to open when a different selection (state) is selected, rather than clicking on the marker to trigger info window. Thanks.
Followup:
Following geocodezip's remarks below, the following code works well and has given me a great start! Now to use drop down selector rather than sidebar links...
New working code
<!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"/>
<title>Fusion Table Markers and Sidebar</title>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
google.load('visualization', '1', {'packages':['table']});
var map;
var markers = [];
var infoWindow = new google.maps.InfoWindow();
function initialize() {
var us = new google.maps.LatLng(38.24676420846342, -94.82073772499997);
map = new google.maps.Map(document.getElementById('map_canvas'), {
center: us,
zoom: 4,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
//sidebar to contain link to map marker - Sales Region - and Rep name
var sql = encodeURIComponent("SELECT 'State - Sales Region', 'Representative Contact', Lat, Lon FROM 5555555555 ORDER BY 'State - Sales Region'");
var query = new google.visualization.Query('http://www.google.com/fusiontables/gvizdata?tq=' + sql);
query.send(getData);
}
//simple sidebar and info window style
function getData(response) {
var dt = response.getDataTable();
var side_html = '<table style="border-collapse: collapse" border="1" \
cellpadding="5"> \
<thead> \
<tr style="background-color:#e0e0e0"> \
<th>Area</th> \
<th>Name</th> \
</tr> \
</thead> \
<tbody>';
for (var i = 0; i < dt.getNumberOfRows(); i++) {
var lat = dt.getValue(i,2);
var lng = dt.getValue(i,3);
var area = dt.getValue(i,0);
var pop = dt.getValue(i,1);
var pt = new google.maps.LatLng(lat, lng);
var html = "<strong>" + area + "</strong><br />" + pop;
side_html += '<tr> \
<td>' + area + '</td> \
<td>' + pop + '</td> \
</tr>';
createMarker(pt, html);
}
side_html += '</tbody> \
</table>';
document.getElementById("side_bar").innerHTML = side_html;
}
//use simple default marker
function createMarker(point,info) {
var marker = new google.maps.Marker({
position: point,
map: map
});
markers.push(marker);
google.maps.event.addListener(marker, 'click', function() {
infoWindow.close();
infoWindow.setContent(info);
infoWindow.open(map,marker);
});
}
function myclick(num) {
google.maps.event.trigger(markers[num], "click");
map.setCenter(markers[num].getPosition());
// map.setZoom(map.getZoom()+2);
}
</script>
</head>
<body onload="initialize()">
<div id="map_canvas" style="width: 900px; height: 600px; position: absolute; left: 10px"></div>
<div id="side_bar" style="width: 200px; height: 600px; position: absolute; left: 920px; overflow: auto;"></div>
</body>
</html>

The only way to open an InfoWindow on a FusionTablesLayer by default is to click on it. To open it from an external event, one option is to create your own InfoWindow. retrieving the content by querying the FusionTable and opening on whatever external stimulus you want.
Example/proof of concept with a sidebar
Example from the documentation

Related

How to clear the google map markers before refreshing with a new map? [duplicate]

This question already has answers here:
Google Maps API v3: How to remove all markers?
(32 answers)
Closed 4 years ago.
Could someone be kind enough to share how I can clear the markers in google map before refreshing it with a new set of markers?
In my map, I'm adding markers from an array that contains name, lat and long. The name can be picked from a drop down menu, and then all the markers for that name are added to the page.
Prtoject : Asp.Net Mvc
Link image: https://i.hizliresim.com/V927Py.jpg
When the user adds markers, the previous set of markers remain. I'd like to remove any existing markers before adding the new set.
After reading the documentation, I tried this:
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
#model List<Project_Map.Models.KONUM>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Complex Marker Icons</title>
<style>
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
height: 100%;
margin: 0;
padding: 0;
}
</style>
</head>
<body>
<style>
#map_wrapper {
height: 700px;
}
#map_canvas {
width: 100%;
height: 100%;
}
</style>
<div id="map_wrapper">
<div class="mapping" id="map_canvas">
</div>
</div>
<div id="map"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
jQuery(function ($) {
var script = document.createElement('script');
script.src = "https://maps.googleapis.com/maps/api/js?key=AIzaSyBT56XlfxnK2OB4K93vWdrZci_CKjZyQOM&callback=initMap";
document.body.appendChild(script);
});
</script>
<!-- Google Maps Kodu -->
<script type="text/javascript">
var contentString = '<div id="content">' +
'<div id="siteNotice">' +
'<img src="#IMG_SRC#" />' +
'</div>' +
//'<h2 id="firstHeading" class="firstHeading">#PERSONEL#</h2>' +
'<div id="bodyContent">' +
'<b>Mesafe: </b>#MESAFE# Km<br />' +
'<b>Tarih: </b> #TARIH#' +
'</p>' +
'</div>' +
'</div>';
$(document).ready(function () {
initMap();
});
function initMap() {
var mapCenter = { lat: 39.684536, lng: 35.337094 };
var map = new google.maps.Map(document.getElementById('map_wrapper'), {
zoom: 6,// haritanın yakınlık derecesi
center: mapCenter, // haritanın merkezi
mapTypeId: google.maps.MapTypeId.HYBRID
});
var infoWindow = new google.maps.InfoWindow();
setInterval(function () {
$.ajax({
url: '#Url.Action("GetMapLocations", "Konum")',
type: "POST",
success: function (data) {
var json = JSON.parse(data);
for (var i = 0; i < json.length; i++) {
var position = {
lat: parseFloat(json[i].lat.replace(',', '.')),
lng: parseFloat(json[i].lng.replace(',', '.'))
};
var marker = new google.maps.Marker({
position: position,
animation: google.maps.Animation.BOUNCE,
map: map,
});
// infoWindow içeriğini replace et
var cs = contentString;
cs = cs.replace("#PERSONEL#", json[i].name);
cs = cs.replace("#MESAFE#", json[i].mesafe);
cs = cs.replace("#TARIH#", json[i].tarih);
cs = cs.replace("#IMG_SRC#", json[i].img);
google.maps.event.addListener(marker, 'click', (function (marker, cs, infoWindow) {
return function () {
infoWindow.setContent(cs);
infoWindow.open(map, this);
passive: true;
};
})(marker, cs, infoWindow));
};
},
error: function (data) { alert("Malesef Sunucunuza Ulaşamıyoruz. Lütfen Tekrar Deneyiniz..."); },
});
}, 5000);
};
</script>
</body>
</html>
You have to set up an array, where you can store the added marker
var gmarkers = [];
If you add a marker you have to store the marker object in the array.
gmarkers.push(marker);
If you want to remove these markers you can use something like:
function removeMarker() {
if (gmarkers.length > 0) {
for (var i=0; i<gmarkers.length; i++) {
if (gmarkers[i] != null) {
gmarkers[i].setMap(null);
}
}
}
gmarkers = [];
}

How to display map using geocode

My Script is
<script type="text/javascript">
var lat = <%= #town.latitude %>,
lon = <%= #town.longitude %>,
map;
function initialize() {
var myOptions = {
center: new google.maps.LatLng(lat, lon)
};
map = new google.maps.Map(document.getElementById('map_canvas'),
myOptions);
}
google.maps.event.addDomListener(window, 'load', initialize);
<script type="text/javascript" src="//maps.google.com/maps?file=api& v=2.x&key="My api key"&libraries=places"></script>
I can fetch latitude and longitude but my map is not loading.Could anyone help me with this?
Here is working sample you can update it to your needs (remove what you dont need and add rails variables in place of static lat long):
<!DOCTYPE html>
<html>
<head>
<title>Simple Map</title>
<meta name="viewport" content="initial-scale=1.0">
<meta charset="utf-8">
<style>
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
height: 100%;
margin: 0;
padding: 0;
}
</style>
</head>
<body>
<div id="map"></div>
<script>
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: <%= #lat %>, lng: <%= #long %>},
zoom: 8
});
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=yourkey&callback=initMap"
async defer></script>
</body>
</html>
This is my sample Home controller index action code:
class HomeController < ApplicationController
def index
#lat = "43.8563"
#long = "18.4131"
end
end

OSM building and jQuery mobile

I have a problem with input "range" and OSM Buildings for leaflet maps. I used basic example from official example which works fine but if I add jquery mobile to <head> section it breaks the range input. It's strange... I was using jquery mobile input to change the leaflet map opacity and it's working. Here is my basic example:
var map = new L.Map('map');
map.setView([52.52111, 13.40988], 16, false);
new L.TileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: 'osm.org',
maxZoom: 18,
maxNativeZoom: 20
}).addTo(map);
var osmb = new OSMBuildings(map).load();
//************************************************************
var now,
date, time,
timeRange, dateRange,
timeRangeLabel, dateRangeLabel;
function changeDate() {
var Y = now.getFullYear(),
M = now.getMonth(),
D = now.getDate(),
h = now.getHours(),
m = 0;
timeRangeLabel.innerText = pad(h) + ':' + pad(m);
dateRangeLabel.innerText = Y + '-' + pad(M+1) + '-' + pad(D);
osmb.date(new Date(Y, M, D, h, m));
}
function onTimeChange() {
now.setHours(this.value);
now.setMinutes(0);
changeDate();
}
function onDateChange() {
now.setMonth(0);
now.setDate(this.value);
changeDate();
}
function pad(v) {
return (v < 10 ? '0' : '') + v;
}
timeRange = document.getElementById('time');
dateRange = document.getElementById('date');
timeRangeLabel = document.querySelector('*[for=time]');
dateRangeLabel = document.querySelector('*[for=date]');
now = new Date;
changeDate();
// init with day of year
var Jan1 = new Date(now.getFullYear(), 0, 1);
dateRange.value = Math.ceil((now-Jan1)/86400000);
timeRange.value = now.getHours();
timeRange.addEventListener('change', onTimeChange);
dateRange.addEventListener('change', onDateChange );
timeRange.addEventListener('input', onTimeChange);
dateRange.addEventListener('input', onDateChange);
body {
font-family: sans-serif;
padding: 5px;
margin: 0;
}
#map {
width: 300px;
height: 300px;
float: left;
margin: 0 15px 0 0;
}
label {
height: 20px;
}
<!DOCTYPE html>
<html >
<head>
<meta charset="UTF-8">
<title>Shadows</title>
<script src='http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.js'></script>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css">
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
<script src='http://cdn.osmbuildings.org/OSMBuildings-Leaflet.js'></script>
<link rel='stylesheet prefetch' href='http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.css'>
</head>
<body>
<div id="map"></div>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
<input id="date" type="range" min="1" max="365" step="1"><label for="date"></label><br>
<input id="time" type="range" min="0" max="23" step="1"><label for="time"></label>
</body>
</html>
For jQuery Mobile rangesliders you may use:
$(document).on("pagecreate", "#page-1", function() {
$("#date").on("change", onDateChange);
$("#time").on("change", onTimeChange);
});
Codepen: http://codepen.io/anon/pen/gLJRXb

Fusion infowindow output adding "\n" and geolocation

I've been working on this for a couple so getting to this point should make me very happy. However, I cannot figure out my infowindow output is adding "\n" to every new line. No idea how it's getting there. The geolocation is also being appended to the search result infowindow. I'd like to remove that as well.
Here is a link to the map: http://58design.com/gmaps/
Here is my code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Sheriff | Zone Leader Look Up</title>
<meta name="author" content="Santa Clarita Valley Sheriff" />
<meta name="copyright" content="Copyright 2013 SCV Sheriff" />
<meta name="keywords" content="Santa Clarita Valley Sheriff, SCV Sheriff, Canyon Country, Valencia, Saugus, Newhall, Castaic, Gorman, Stevenson Ranch, " />
<meta name="description" content="Santa Clarita Valley Sheriff Zone Leader Contact Inforamtion Look Up." />
<meta name="robots" content="index,follow" />
<meta name="Googlebot" content="follow" />
<meta name="googlebot" content="archive" />
<meta name="distribution" content="global" />
<!--Load the AJAX API-->
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
//<![CDATA[
google.load('visualization', '1', {'packages':['corechart', 'table', 'geomap']});
//var FusionTableID = 1931355;
var FusionTableID = '1uSGM1yPMJBlu74Znm4fPqdCsJjteB_kQ_nGz3tk';
var map = null;
var geocoder = null;
var infowindow = null;
var marker = null;
function initialize() {
geocoder = new google.maps.Geocoder();
infowindow = new google.maps.InfoWindow({size: new google.maps.Size(150,50) });
// create the map
var myOptions = {
zoom: 10,
center: new google.maps.LatLng(34.452789398370045, -118.51948001245114),
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);
//layer = new google.maps.FusionTablesLayer(FusionTableID,{suppressInfoWindows:true});
layer = new google.maps.FusionTablesLayer({
map: map,
suppressInfoWindows: true,
heatmap: { enabled: false },
query: {
select: "col2",
from: "1uSGM1yPMJBlu74Znm4fPqdCsJjteB_kQ_nGz3tk",
where: "",
},
options: {
styleId: 2,
templateId: 2
}
});
layer.setMap(map);
google.maps.event.addListener(layer, "click", function(e) {
var content = e.row['description'].value+"<br><br>";
infowindow.setContent(content);
infowindow.setPosition(e.latLng);
infowindow.open(map);
});
}
function showAddress(address) {
var contentString = address+"<br>Outside Area";
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var point = results[0].geometry.location;
contentString += "<br>"+point;
map.setCenter(point);
if (marker && marker.setMap) marker.setMap(null);
marker = new google.maps.Marker({
map: map,
position: point
});
// query FT for data
var queryText ="SELECT 'description', 'Zone Area' FROM "+FusionTableID+" WHERE ST_INTERSECTS(\'Zone Area\', CIRCLE(LATLNG(" + point.toUrlValue(6) + "),0.5));";
// document.getElementById('FTQuery').innerHTML = queryText;
queryText = encodeURIComponent(queryText);
var query = new google.visualization.Query('http://www.google.com/fusiontables/gvizdata?tq=' + queryText);
//set the callback function
query.send(openInfoWindowOnMarker);
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
function openInfoWindowOnMarker(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();
var content = "<b>Outside area</b><br><br>";
var unionBounds = null;
// alert(numRows);
for (var i=0; i < numRows; i++) {
var name = FTresponse.getDataTable().getValue(i,0);
var kml = FTresponse.getDataTable().getValue(i,1);
content = response.getDataTable().getValue(i,0)+"<br><br>";
}
infowindow.setContent(content+marker.getPosition().toUrlValue(6));
// zoom to the bounds
// map.fitBounds(unionBounds);
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map,marker);
});
google.maps.event.trigger(marker, 'click');
}
</script>
</head>
<body onload="initialize()">
<div id="content">
<h1>SCV Sheriff Reporting Zones</h1>
<p>Use the map below to determine your area's Zone Leader. Enter your street address, city and zip code in the search field below to view the Zone Leader's contact info.</p>
<form action="#" onsubmit="showAddress(this.address.value); return false" style="padding:10px 0px 30px 0px; background:none;">
<label>Address Search</label>
<input type="text" size="60" name="address" value="23920 Valencia Blvd. Santa Clarita, CA 91355" class="address" />
<input type="submit" value="Search" />
</p>
<div id="map_canvas" style="width: 516px; height: 387px; margin-bottom:30px; border:1px solid #999;"></div>
</form>
</div>
<div id="sidebar">
</div>
<div class="clear"><!--clear--></div>
</div>
</body>
</html>
The problem is in the data in your FusionTable (the line feeds are getting translated into "\n"). I fixed the entry for "Gorman" in my example (by removing the extraneous line feeds).
This line of my code is appending the geolocation to the search result infowindow:
infowindow.setContent(content+marker.getPosition().toUrlValue(6));

Adding Legend to Google Fusion Table

I'm trying to add a legend t a map i created from Google Fusion Table Layer Builder and nothing seem to be happening. The legend does not show. here's the sample code. Sample Code
<!DOCTYPE html>
<html>
<head>
<style>
#map-canvas { width:500px; height:400px; }
</style>
<script type="text/javascript"
src="http://maps.google.com/maps/api/js?sensor=false">
</script>
<script type="text/javascript">
var map;
var layerl0;
function initialize() {
map = new google.maps.Map(document.getElementById('map-canvas'), {
center: new google.maps.LatLng(0.428462803418747, 37.760009765625),
zoom: 6,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
layerl0 = new google.maps.FusionTablesLayer({
query: {
select: "'geometry'",
from: 3435376
},
map: map
});
// Create the legend and display on the map
var legend = document.createElement('div');
legend.id = 'legend';
var content = [];
content.push('<h3>Legend</h3>');
content.push('<p><div class="color red"></div>No</p>');
content.push('<p><div class="color green"></div>Yes</p>');
content.push('<p>*Data is fictional</p>');
legend.innerHTML = content.join('');
legend.index = 1;
map.controls[google.maps.ControlPosition.RIGHT_BOTTOM].push(legend);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas"></div>
</body>
</html>
Your legend does show, well at the least the text. You'll need to add some CSS styles, e..g to set the background white, etc. There is a good example at
http://gmaps-samples.googlecode.com/svn/trunk/fusiontables/legend_template.html
See the Legend() and updateLegend() functions.
UPDATE This is really a CSS question. My changes are marked by ADDED or CHANGED
var legend = document.createElement('div');
legend.id = 'legend';
// ADDED
legend.style.padding = '10px';
legend.style.backgroundColor = 'white';
legend.style.borderStyle = 'solid';
legend.style.borderWidth = '1px';
legend.style.textAlign = 'left';
var content = [];
content.push('<h3>Legend</h3>');
// CHANGED
//content.push('<p><div class="color red"></div>No</p>');
//content.push('<p><div class="color green"></div>Yes</p>');
content.push('<p style="background-color: #51D950;">No</p>');
content.push('<p style="background-color: #C84939;">Yes</p>');
content.push('<p>*Data is fictional</p>');
legend.innerHTML = content.join('');
legend.index = 1;
map.controls[google.maps.ControlPosition.RIGHT_BOTTOM].push(legend);
The legend tag is ONLY allowed within fieldset tags.
http://www.w3schools.com/html5/tag_legend.asp

Resources