Google Fusion Table with checkbox filter not working correctly - google-fusion-tables

I've been attempting to put together a fusion map that is filterable by a checkbox.
I've used Google's sample code but have clearly gone wrong somewhere.
I'm new to this so I know it's probably a simple mistake but I can't find it.
The checkbox is only working for 1 filter. The others don't work nor does the data linked to them load.
I'd appreciate any help to identify where I've gone wrong.
my data table is at https://www.google.com/fusiontables/DataSource?docid=1VnR1phtvbSUZXPiiVbxiwzOF06sdW_GiZoqd8Ks
and my code is below
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="UTF-8">
<title>Fusion Tables Layer Example: IN query</title>
<link href="https://developers.google.com/fusiontables/docs/samples/style/default.css"
rel="stylesheet" type="text/css">
<script type="text/javascript"
src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
function initialize() {
var tableId = '1VnR1phtvbSUZXPiiVbxiwzOF06sdW_GiZoqd8Ks';
var map = new google.maps.Map(document.getElementById('map-canvas'), {
center: new google.maps.LatLng(53.30647442766776, -2.0839745570312917),
zoom: 6,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var layer = new google.maps.FusionTablesLayer();
filterMap(layer, tableId, map);
google.maps.event.addDomListener(document.getElementById('anna-mathers'),
'click', function() {
filterMap(layer, tableId, map);
});
google.maps.event.addDomListener(document.getElementById('sonia-osborne'),
'click', function() {
filterMap(layer, tableId, map);
});
google.maps.event.addDomListener(document.getElementById('neil-larner'),
'click', function() {
filterMap(layer, tableId, map);
});
google.maps.event.addDomListener(document.getElementById('bridget-tully'),
'click', function() {
filterMap(layer, tableId, map);
});
}
// Filter the map based on checkbox selection.
function filterMap(layer, tableId, map) {
var where = generateWhere();
if (where) {
if (!layer.getMap()) {
layer.setMap(map);
}
layer.setOptions({
query: {
select: 'Location',
from: tableId,
where: where
}
});
} else {
layer.setMap(null);
}
}
// Generate a where clause from the checkboxes. If no boxes
// are checked, return an empty string.
function generateWhere() {
var filter = [];
var ops = document.getElementsByName('ops');
for (var i = 0, ops; ops = ops[i]; i++) {
if (ops.checked) {
var opsName = ops.value.replace(/'/g, '\\\'');
filter.push("'" + opsName + "'");
}
}
var where = '';
if (filter.length) {
where = "'Ops' IN (" + filter.join(',') + ')';
}
return where;
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas"></div>
<div>
<input type="checkbox" checked="checked" name="ops"
id="sonia-osborne" value="Sonia Osborne">
<label>Sonia Osborne</label>
<input type="checkbox" checked="checked" name="ops"
id="anna-mathers" value="Anna Mathers">
<label>Anna Mathers</label>
<input type="checkbox" checked="checked" name="ops"
id="neil-larner" value="Neil Larner">
<label>Neil Larner</label>
<input type="checkbox" checked="checked" name="ops"
id="bridget-tully" value="Bridget Tully">
<label>Bridget Tully</label>
</div>
</body>
</html>

You are overwriting ops in the for-condition:
ops = ops[i]
after the first loop the condition will fail, because ops[i] is undefined
Fixed version:
for (var i = 0; i<ops.length,op=ops[i]; ++i) {
if (op.checked) {
var opName = op.value.replace(/'/g, '\\\'');
filter.push("'" + opName + "'");
}
}

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 = [];
}

zip two arrays in javascript not working to draw high chart

Im going to take x,y values in text area.create another array for with xy cordinates to draw high chart.but it does not display graph.i couldnt find the error.please help.
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
<script src="http://code.highcharts.com/highcharts.js"></script>
<script type="text/javascript">
$(function () {
$('#container').highcharts({
chart: {},
plotOptions: {
series: {
allowPointSelect: true
}
},
series: [{
data: []
}]
});
$('#button').click(function () {
xval = $('#hi').val().split('\n');
var lines=[];
for (var i = 0; i < xval.length; i++)
    if (xval[i]) lines.push(xval[i]);
lines.toString();
document.getElementById("demo").innerHTML=lines;
yval = $('#hii').val().split('\n');
var lines1 = [];
for (var i = 0; i < yval.length; i++)
    if (yval[i]) lines1.push(yval[i]);// to remove white space
lines1.toString();
var mySeries = [];
for (var i = 0; i < lines.length; i++) {
mySeries.push([lines[i], lines1[i]]);
}
var chart = $('#container').highcharts();
chart.series[0].setData(mySeries);
});
});
</script>
</head>
<body>
<div id="container" style="height: 400px"></div>
<textarea id="hi" name="Text1" cols="40" rows="5" placeholder="enter one wdg in one line"></textarea>
<textarea id="hii" name="Text2" cols="40" rows="5" placeholder="enter one wdg in one line"></textarea>
<p id="demo"></p>
<button id="button">Add My Data</button>
</body>
</html>
check this fiddle.
http://jsfiddle.net/Cm3Ps/443/
The issue is caused by the error #14, which means that you use strings instead of values. Morever you should split all x/y values (i.e by comma) and push each of them to array. You cannot push the string like '10,20,30'.
for (var i = 0; i < lines.length; i++) {
var itemsX = lines[i].split(','),
itemsY = lines1[i].split(',');
for(var j = 0; j < itemsX.length; j++) {
mySeries.push([parseFloat(itemsX[j]), parseFloat(itemsY[j])]);
}
}
var chart = $('#container').highcharts();
Fixed demo:
http://jsfiddle.net/Lfq0x5j5/

Fusion Table Layer Wizard shows search but not map

I found several other people on here had the same issue with the Fusion Table Wizard generating HTML that works in the preview but when you try to embed the code on your own webpage pieces are missing. Mine for example, will show the search bar but not the map. Someone else had the same problem and it turned out that quotes were missing around the id number. But mine does have the appropriate quotes. So I'm wondering what is wrong with my code. I've compared my code to theirs several times looking for what is missing but can't figure it out.
Our webpage is hosted by jimdo, and I have to use the html/widget. I copy and paste the code into that. But it does say that some code requires you to edit the head section. That wouldn't be the problem would it? And if it is, what would I put in the head section and what would I put in the body section?
Here is my code:
<!DOCTYPE html>
<html>
<head>
<style>
#map-canvas { width:500px; height:400px; }
.layer-wizard-search-label { font-family: sans-serif };
</style>
<script type="text/javascript"
src="http://maps.google.com/maps/api/js?sensor=false">
</script>
<script type="text/javascript">
var map;
var layer_0;
var layer_1;
function initialize() {
map = new google.maps.Map(document.getElementById('map-canvas'), {
center: new google.maps.LatLng(45.0817001045586, -89.74025),
zoom: 6
});
var style = [
{
featureType: 'all',
elementType: 'all',
stylers: [
{ saturation: 11 }
]
}
];
var styledMapType = new google.maps.StyledMapType(style, {
map: map,
name: 'Styled Map'
});
map.mapTypes.set('map-style', styledMapType);
map.setMapTypeId('map-style');
layer_0 = new google.maps.FusionTablesLayer({
query: {
select: "col18",
from: "1_rIjSmE6MLjWMF4JH-OIzHFcYCjKr-8eytn9v6Y"
},
map: map,
styleId: 2,
templateId: 3
});
layer_1 = new google.maps.FusionTablesLayer({
query: {
select: "col4",
from: "1ZLOwVcCWsIA-1WNg_yICWjaRdWOTeVy9xpudaQ"
},
map: map
});
}
function changeMap_0() {
var whereClause;
var searchString = document.getElementById('search-string_0').value.replace(/'/g, "\\'");
if (searchString != '--Select--') {
whereClause = "'Counties' CONTAINS IGNORING CASE '" + searchString + "'";
}
layer_0.setOptions({
query: {
select: "col18",
from: "1_rIjSmE6MLjWMF4JH-OIzHFcYCjKr-8eytn9v6Y",
where: whereClause
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas"></div>
<div style="margin-top: 10px;">
<label class="layer-wizard-search-label">
Counties
<input type="text" id="search-string_0">
<input type="button" onclick="changeMap_0()" value="Search">
</label>
</div>
</body>
</html>
Can somebody help me, because I have been doing this for days now. And have finally decided to actually ask for help. Any input you have would be greatly appreciated!
Thanks, Angie
Paste this:
<div id="map-canvas" style="width:500px; height:400px;"></div>
<div style="margin-top: 10px;">
<label class="layer-wizard-search-label">
Counties
<input type="text" id="search-string_0">
<input type="button" onclick="changeMap_0()" value="Search">
</label>
</div>
<script type="text/javascript"
src="http://maps.google.com/maps/api/js?sensor=false">
</script>
<script type="text/javascript">
var map;
var layer_0;
var layer_1;
function initialize() {
map = new google.maps.Map(document.getElementById('map-canvas'), {
center: new google.maps.LatLng(45.0817001045586, -89.74025),
zoom: 6
});
var style = [
{
featureType: 'all',
elementType: 'all',
stylers: [
{ saturation: 11 }
]
}
];
var styledMapType = new google.maps.StyledMapType(style, {
map: map,
name: 'Styled Map'
});
map.mapTypes.set('map-style', styledMapType);
map.setMapTypeId('map-style');
layer_0 = new google.maps.FusionTablesLayer({
query: {
select: "col18",
from: "1_rIjSmE6MLjWMF4JH-OIzHFcYCjKr-8eytn9v6Y"
},
map: map,
styleId: 2,
templateId: 3
});
layer_1 = new google.maps.FusionTablesLayer({
query: {
select: "col4",
from: "1ZLOwVcCWsIA-1WNg_yICWjaRdWOTeVy9xpudaQ"
},
map: map
});
}
function changeMap_0() {
var whereClause;
var searchString = document.getElementById('search-string_0').value.replace(/'/g, "\\'");
if (searchString != '--Select--') {
whereClause = "'Counties' CONTAINS IGNORING CASE '" + searchString + "'";
}
layer_0.setOptions({
query: {
select: "col18",
from: "1_rIjSmE6MLjWMF4JH-OIzHFcYCjKr-8eytn9v6Y",
where: whereClause
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
As it seems everything except the contents of <body> will be removed when you paste a complete HTML-source.

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));

Trying to get 2 maps API: FusionTablesLayer Functions to work on the same map and fusion table

I have created a fusion table and layer that allows me to use check boxes to hide or display certain markers on the map. I would like to add a search feature that works like the pan and zoom feature. In addition, once the map zooms to the location I would like to have a radius option that identifies other locations within a certain area.
I have modified the sample code found on the IN Query (https://developers.google.com/fusiontables/docs/samples/in) and can get the checkboxes to work, but when I try to include the pan and zoom code (https://developers.google.com/fusiontables/docs/samples/search_and_zoom), I can't seem to get the search feature to work.
I have one fusion table with approximately 4000 records. I am a novice at coding so I am sure it is something in my syntax. I would also assume what I want to do is possible?
Any help would be appreciated.
Here is the code. As indicated I want to insert a search that utilizes pan and zoom feature. I ended up removing it from the code below because I was unsure how to insert or format it.
<head>
<style>
#map-canvas { width:800px; height:600px; }
</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() {
var tableId = '4422804';
var map = new google.maps.Map(document.getElementById('map-canvas'), {
center: new google.maps.LatLng(50.792047064406866, -99.052734375),
zoom: 2,
mapTypeId: google.maps.MapTypeId.HYBRID
});
var layer = new google.maps.FusionTablesLayer();
filterMap(layer, tableId, map);
google.maps.event.addDomListener(document.getElementById('< 5'),
'click', function() {
filterMap(layer, tableId, map);
});
google.maps.event.addDomListener(document.getElementById('> 5'),
'click', function() {
filterMap(layer, tableId, map);
});
google.maps.event.addDomListener(document.getElementById('Not Signed'),
'click', function() {
filterMap(layer, tableId, map);
});
google.maps.event.addDomListener(document.getElementById('Signed Not Selling'),
'click', function() {
filterMap(layer, tableId, map);
});
}
// Filter the map based on checkbox selection.
function filterMap(layer, tableId, map) {
var where = generateWhere();
if (where) {
if (!layer.getMap()) {
layer.setMap(map);
}
layer.setOptions({
query: {
select: 'Full Address',
from: tableId,
where: where
}
});
} else {
layer.setMap(null);
}
}
// Generate a where clause from the checkboxes. If no boxes
// are checked, return an empty string.
function generateWhere() {
var filter = [];
var stores = document.getElementsByName('store');
for (var i = 0, store; store = stores[i]; i++) {
if (store.checked) {
var storeName = store.value.replace(/'/g, '\\\'');
filter.push("'" + storeName + "'");
}
}
var where = '';
if (filter.length) {
where = "'Map' IN (" + filter.join(',') + ')';
}
return where;
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas"></div>
You did not include your checkboxes, etc. But here's an example which works, using buttons, not checkboxes. Should not be too hard to adapt it your needs. No zoom to, which is really a different questions.
http://jsfiddle.net/ebridger/wmnDU/

Resources