Adding Legend to Google Fusion Table - google-fusion-tables

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

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

Get Features in heatmap openlayers3

I want to get all features when I click on heat map in openlayers 3...It is possible or not? How to count the features in heat map and give heat map total count features label? thanks
Openlayers3 can do this easily,You can use getFeatures() to get all the features.
var features = heatlayer.getSource().getFeatures()
alert('count: '+features.length);
This method returns an array containing all the features,so you can use length to count.
<!DOCTYPE html>
<html>
<head>
<title>heatlayer count example</title>
<link rel="stylesheet" href="https://openlayers.org/en/v3.20.1/css/ol.css" type="text/css">
<!-- The line below is only needed for old environments like Internet Explorer and Android 4.x -->
<script src="https://cdn.polyfill.io/v2/polyfill.min.js?features=requestAnimationFrame,Element.prototype.classList,URL"></script>
<script src="https://openlayers.org/en/v3.20.1/build/ol.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.2.61/jspdf.min.js"></script>
<style>
.map {
max-width: 566px;
}
</style>
</head>
<body>
<div id="map" class="map"></div>
<script>
var raster = new ol.layer.Tile({
source: new ol.source.OSM()
});
var heatlayer = new ol.layer.Heatmap({
source: new ol.source.Vector(),
blur: parseInt(14),
radius: parseInt(8)
});
var adddata = [[104.807799,30.232233],[106.803599,31.233225]];
//addfeature
for(var i = 0;i < adddata.length ; i++){
var feature = new ol.Feature({
geometry:new ol.geom.Point([adddata[i][0],adddata[i][1]])
});
heatlayer.getSource().addFeature(feature);
}
var map = new ol.Map({
layers: [raster,heatlayer],
target: 'map',
controls: ol.control.defaults({
attributionOptions: /** #type {olx.control.AttributionOptions} */ ({
collapsible: false
})
}),
view: new ol.View({
projection: 'EPSG:4326',
center:[104.07, 30.7],
zoom: 2
})
});
map.on('click', function(event){
var features = heatlayer.getSource().getFeatures()
alert('count: '+features.length);
});
</script>
</body>
</html>

InfoWindow contents spilling out using dynamic template?

Can anyone tell my why the contents of my InfoWindows are spilling out? When I view the InfoWindows in the Fusion Table UI, they all pop up and resize themselves correctly:
https://www.google.com/fusiontables/embedviz?q=select+col7+from+15wosKAeHC0gcpU_N6UPbxPL09RrEBKlQNEaCmnU&viz=MAP&h=false&lat=34.199813229302734&lng=-111.2955847411987&t=1&z=8&l=col7&y=2&tmplt=2
But when I try to use the html code to create a webpage, some (not all) of the InfoWindow contents spill out:
<!DOCTYPE html>
<html>
<head>
<title>CaveCreek - Google Fusion Tables</title>
<style type="text/css">
html, body, #googft-mapCanvas {
height: 300px;
margin: 0;
padding: 0;
width: 500px;
}
</style>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
function initialize() {
google.maps.visualRefresh = true;
var map = new google.maps.Map(document.getElementById('googft-mapCanvas'), {
center: new google.maps.LatLng(34.199813229302734, -111.2955847411987),
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
map.controls[google.maps.ControlPosition.RIGHT_BOTTOM].push(document.getElementById('googft-legend'));
layer = new google.maps.FusionTablesLayer({
map: map,
heatmap: { enabled: false },
query: {
select: "col7",
from: "15wosKAeHC0gcpU_N6UPbxPL09RrEBKlQNEaCmnU",
where: ""
},
options: {
styleId: 2,
templateId: 2
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="googft-mapCanvas"></div>
</body>
</html>
My dynamic template InfoWindow code looks like:
{template .contents}
<div>
<div style="align: center">
<b>{$data.value.Stream}</b>
</div>
{if $data.value.y2012}
2012-{/if}
{if $data.value.y2012a}
2012a-{/if}
...
</div>
{/template}
I have tried to add height and width to the div tag for the InfoWindow in the template but that still doesn't seem to work.
Remove the visualRefresh, that is causing the infoWindow size to be calculated incorrectly.
google.maps.visualRefresh = true;
Note that the Google Maps visual refresh is going to be the default soon, so removing it is not a long-term solution.
If you set the height of the div and add overflow-y: scroll you should get a scrollbar on your content; does that not happen? One of the examples in the dynamic template help is setting the height differently based on fields being there or not, so that might help.

Google Fusion Map Info Window Not Formatted

I have created a Google Fusion Map with 2 layers. All appears to be working correctly with 1 exception.
I have formatted the Info Window of both layers using the Google Fusion Table tool. However, the Info Window on layer 1 is not appearing as specified with the code below. It works fine in the Google Fusion Table tool itself.
Can anyone spot what I've done wrong? Thanks.
<meta charset="UTF-8">
<title>Smithfield Foods UK</title>
<link rel="stylesheet" type="text/css" media="all" href="FusionMapTemplate.css" />
<script type="text/javascript"
src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
function initialize() {
var defaultZoom = 10;
var defaultCenter = new google.maps.LatLng(52.6500, 1.2800)
var locationColumn = 'geometry'
var map = new google.maps.Map(document.getElementById('map-canvas'), {
center: defaultCenter,
zoom: defaultZoom,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infoWindow = new google.maps.InfoWindow();
// Initialize the first layer
var FirstLayer = new google.maps.FusionTablesLayer({
query: {
select: 'geometry',
from: '1hpGzmMBg8bDgPOGrAXvc0_QVLSBqQ0O5vpLbfUE'
},
map: map,
styleId: 3,
templateID: 5,
suppressInfoWindows: true
});
google.maps.event.addListener(FirstLayer, 'click', function(e) {windowControl(e, infoWindow, map);
});
// Initialize the second layer
var SecondLayer = new google.maps.FusionTablesLayer({
query: {
select: 'PostCode',
from: '1RrCcRC-1vU0bfHQJTQWqToR-vllSsz9iKnI5WEk'
},
map: map,
styleId: 2,
templateId: 2,
suppressInfoWindows: true
});
google.maps.event.addListener(SecondLayer, 'click', function(e) {windowControl(e, infoWindow, map);
});
}
// Open the info window at the clicked location
function windowControl(e, infoWindow, map) {
infoWindow.setOptions({
content: e.infoWindowHtml,
position: e.latLng,
pixelOffset: e.pixelOffset
});
infoWindow.open(map);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas"></div>
</body>
the issue:
templateID: 5,
//-------^
the D has to be lowercase

Getting around the 500 row limit

I have written a Google Fusion Tables script I'm happy with (below), but it's loading only 500 rows of points in my table, which has over 20,000 rows. This is my first time in this neighborhood and I was really surprised to find the limit. Is there some way to load all the rows?
<!doctype html>
<html class="no-js" lang="en">
<head>
<meta charset="utf-8">
<meta content="IE=edge,chrome=1" http-equiv="X-UA-Compatible">
<title>Points in box</title>
<link href="./stylesheets/example.css" media="screen" rel="stylesheet" type="text/css" />
<link rel="shortcut icon" href="/images/favicon.ico" />
<noscript><meta http-equiv="refresh" content="0;url=/no_javascript.html"></noscript>
<!-- Find box coordinates javascript -->
<script type ="text/javascript" src="http://www.movable-type.co.uk/scripts/latlon.js"></script>
<!-- Type label text javascript -->
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript" src="./js/label.js"></script>
<!-- Visulization javascript -->
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<!-- Initialize visualization -->
<script type="text/javascript">
google.load('visualization', '1', {});
</script>
</head>
<body class="developers examples examples_downloads examples_downloads_points-in-box examples_downloads_points-in-box_index">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
var store_table = 4121905;
//send a call to GViz to retrieve lat/long coordinates of the stores
function getStoreData() {
//set the query using the input from the user
var queryText = encodeURIComponent("SELECT Latitude,Longitude,Impressions FROM " + store_table);
var query = new google.visualization.Query('http://www.google.com/fusiontables/gvizdata?tq=' + queryText);
//set the callback function
query.send(doLoop);
}
function drawBox(topleftx, toplefty, bottomrightx, bottomrighty) {
var bounds = new google.maps.LatLngBounds(
new google.maps.LatLng( topleftx, toplefty ),
new google.maps.LatLng( bottomrightx, bottomrighty )
);
var overlay = new google.maps.Rectangle({
map: carto_map,
bounds: bounds,
strokeColor: "#0000ff",
strokeOpacity: 0.20,
strokeWeight: 2,
fillColor: "#0000ff",
fillOpacity: 0.050,
});
}
function doLoop(response) {
numRows = response.getDataTable().getNumberOfRows();
//Basic
var cartodbMapOptions = {
zoom: 7,
center: new google.maps.LatLng( 37.926868, -121.68457 ),
// center: new google.maps.LatLng( 40.7248057566452, -74.003 ),
// disableDefaultUI: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
// Init the map
carto_map = new google.maps.Map(document.getElementById("map"),cartodbMapOptions);
for(i = 0; i < numRows; i++) {
var centerX = response.getDataTable().getValue(i,0);
var centerY = response.getDataTable().getValue(i,1);
var imps = response.getDataTable().getValue(i,2);
var centerPoint = new LatLon(centerX,centerY);
var latLng = new google.maps.LatLng(centerX,centerY);
var toplefty = centerPoint.destinationPoint(-45, 6)._lon;
var topleftx = centerPoint.destinationPoint(-45, 7.7)._lat;
var bottomrighty = centerPoint.destinationPoint(135, 6)._lon;
var bottomrightx = centerPoint.destinationPoint(135, 7.7)._lat;
drawBox(topleftx, toplefty, bottomrightx, bottomrighty);
var marker = new google.maps.Marker({
position: latLng,
draggable: false,
markertext: imps,
flat: true,
map: carto_map
});
var label = new Label({
map: carto_map,
position: latLng,
draggable: true
});
label.bindTo('text', marker, 'markertext');
marker.setMap(null);
}
}
$(function() {
getStoreData();
});
</script>
<div id="map"></div>
</body>
</html>
I solved the problem by using the json call method. Code below.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>David's Build Up</title>
<link href="./stylesheets/example.css" media="screen" rel="stylesheet" type="text/css" />
<link rel="shortcut icon" href="/images/favicon.ico" />
<noscript><meta http-equiv="refresh" content="0;url=/no_javascript.html"></noscript>
<!-- Find box coordinates javascript -->
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js">
</script>
<script type ="text/javascript" src="http://www.movable-type.co.uk/scripts/latlon.js"></script>
<!-- Type label text javascript -->
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript" src="./js/label.js"></script>
<!-- Visulization javascript -->
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<!-- Initialize visualization -->
<script type="text/javascript">
google.load('visualization', '1', {});
</script>
<script type="text/javascript">
function drawBox(topleftx, toplefty, bottomrightx, bottomrighty) {
var bounds = new google.maps.LatLngBounds(
new google.maps.LatLng( topleftx, toplefty ),
new google.maps.LatLng( bottomrightx, bottomrighty )
);
var overlay = new google.maps.Rectangle({
map: carto_map,
bounds: bounds,
strokeColor: "#0000ff",
strokeOpacity: 0.20,
strokeWeight: 2,
fillColor: "#0000ff",
fillOpacity: 0.050,
});
}
function initialize() {
// Set the map parameters
var cartodbMapOptions = {
zoom: 5 ,
center: new google.maps.LatLng( 40.313043, -97.822266 ),
mapTypeId: google.maps.MapTypeId.ROADMAP
}
// Initialize the map
carto_map = new google.maps.Map(document.getElementById("map"),cartodbMapOptions);
// Query to grab the data
var query = "SELECT Latitude, Longitude, Impressions FROM " +
'[encrypted table ID here]';
var encodedQuery = encodeURIComponent(query);
// Construct the URL to grab the data
var url = ['https://www.googleapis.com/fusiontables/v1/query'];
url.push('?sql=' + encodedQuery);
url.push('&key=AIzaSyAm9yWCV7JPCTHCJut8whOjARd7pwROFDQ');
url.push('&callback=?');
// Set the number of rows
var numRows = 3500;
// Get the variables from the table, in a loop
$.ajax({
url: url.join(''),
dataType: 'jsonp',
success: function (data) {
var rows = data['rows'];
var ftData = document.getElementById('ft-data');
for (var i in rows) {
var centerX = rows[i][0];
var centerY = rows[i][1];
var imps = rows[i][2];
// Set the center points
var centerPoint = new LatLon(centerX,centerY);
var latLng = new google.maps.LatLng(centerX,centerY);
// Set top left points
var toplefty = centerPoint.destinationPoint(-45, 6)._lon;
var topleftx = centerPoint.destinationPoint(-45, 7.7)._lat;
// Set bottom right points
var bottomrighty = centerPoint.destinationPoint(135, 6)._lon;
var bottomrightx = centerPoint.destinationPoint(135, 7.7)._lat;
// Draw the box
drawBox(topleftx, toplefty, bottomrightx, bottomrighty);
// Drop markers
var marker = new google.maps.Marker({
position: latLng,
draggable: false,
markertext: imps,
flat: true,
map: carto_map
});
var label = new Label({
map: carto_map,
position: latLng,
draggable: true
});
label.bindTo('text', marker, 'markertext');
marker.setMap(null);
};
}
});
}
</script>
</head>
<body onload="initialize()">
<div id="map"></div>
<div id="ft-data"></div>
</body>
</html>
The Gviz API does have a 500 row limit for a given query.
Any table is limited to 100,000 mappable rows, but that's well outside your reported 20,000 rows.
The new Javascript API, currently accepting Trusted Testers, offers JSON format support for any number of rows returned for a query. You can apply for the TT program by requesting membership in this group:
https://groups.google.com/group/fusion-tables-api-trusted-testers
-Rebecca
The fusiontables/gvizdata URL is intended for Gviz charts and so is limited to 500 points. There are other ways to query that don't have that limitation. See https://developers.google.com/fusiontables/docs/sample_code for examples.
I routinely refresh a 2500 row table by deleting all rows and inserting new ones. The loop in my code that constructs the INSERT sql has a nested loop that just counts to 400, sends that sql, and then starts building another one with the next 400 records.

Resources