How to show maps side by side? - javascript

I have a flask application where i am using the leaflet map with the values offered by https://aqicn.org/faq/2015-09-18/map-web-service-real-time-air-quality-tile-api/ to display pm2.5, air quality index and other values in a side by side map. So far, I have managed to display all values on layers, and i don't know how to make the map display all values at the same time, like the one in the picture:
So far I have this:
<!DOCTYPE html>
<html>
{% extends "menu.html" %}
<head>
<title>{% block title %}Map{% endblock %}</title>
<meta charset="utf-8"/>
{% block dependencies %}
<style>
html {
height: 100%
}
body {
height: 100%;
margin: 0;
}
#map {
height: 800px;
}
</style>
{% endblock %}
</head>
<body>
{% block content %}
<link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.7.5/leaflet.css"/>
<script src="http://cdn.leafletjs.com/leaflet-0.7.5/leaflet.js"></script>
<div id='map' class="a"></div>
<script>
var mbUrl_aqi = 'https://tiles.aqicn.org/tiles/usepa-' + 'aqi' + '/{z}/{x}/{y}.png?token=?';
var mbUrl_pm25 = 'https://tiles.aqicn.org/tiles/usepa-' + 'pm25' + '/{z}/{x}/{y}.png?token=?';
var mbUrl_pm10 = 'https://tiles.aqicn.org/tiles/usepa-' + 'pm10' + '/{z}/{x}/{y}.png?token=?';
var mbUrl_o3 = 'https://tiles.aqicn.org/tiles/usepa-' + 'o3' + '/{z}/{x}/{y}.png?token=?';
var mbUrl_no2 = 'https://tiles.aqicn.org/tiles/usepa-' + 'no2' + '/{z}/{x}/{y}.png?token=?';
var mbUrl_so2 = 'https://tiles.aqicn.org/tiles/usepa-' + 'so2' + '/{z}/{x}/{y}.png?token=?';
var mbUrl_co = 'https://tiles.aqicn.org/tiles/usepa-' + 'co' + '/{z}/{x}/{y}.png?token=?';
var aqi = L.tileLayer(mbUrl_aqi);
var pm25 = L.tileLayer(mbUrl_pm25);
var pm10 = L.tileLayer(mbUrl_pm10);
var o3 = L.tileLayer(mbUrl_o3);
var no2 = L.tileLayer(mbUrl_no2);
var so2 = L.tileLayer(mbUrl_so2);
var co = L.tileLayer(mbUrl_co);
var map = L.map('map', {
center: [45.657974, 25.601198],
zoom: 11,
layers: [aqi]
});
var baseLayers = {
"aqi": aqi,
"pm25": pm25,
"pm10": pm10,
"no2": no2,
"so2": so2,
"co": co,
"o3": o3
};
{# resize #}
document.getElementById("map").style.resize = "both";
var WAQI_ATTR = '© waqi.info';
var credits_url = 'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png';
var credits_attrib = '© OpenStreetMap';
var osmLayer = L.tileLayer(credits_url, {attribution: [credits_attrib, WAQI_ATTR]});
map.addLayer(osmLayer);
L.control.layers(baseLayers).addTo(map);
</script>
{% endblock %}
</body>
</html>
The code displays the following:
How to show all maps side by side?

This works. You can play with CSS or the DOM to change the display of the maps, but there you have something working (also, you can improve the code because there is a repetition and a repetition is never good).
$( document ).ready(function() {
var layerTypes = ['aqi', 'pm25', 'pm10', 'o3', 'no2', 'so2', 'co']
var maps = []
layerTypes.forEach(function(layer){
var t = document.createElement('div');
t.setAttribute("id", "map_"+layer);
t.setAttribute("class", "map");
document.getElementById("maps").appendChild(t);
var m = L.tileLayer('https://tiles.aqicn.org/tiles/usepa-' + layer + '/{z}/{x}/{y}.png?token=?');
var map = L.map('map_'+layer, {
center: [45.657974, 25.601198],
zoom: 11,
layers: [m]
});
map.on("zoomend", function (e) {
var zoom = map.getZoom();
var center = map.getCenter();
maps.forEach(function(everyMap){
everyMap.setView(center, zoom);
})
});
map.on("moveend", function (e) {
var zoom = map.getZoom();
var center = map.getCenter();
maps.forEach(function(everyMap){
everyMap.setView(center, zoom);
})
});
var baseLayers = {};
baseLayers[layer] = m,
document.getElementById("map_"+layer).style.resize = "both";
var WAQI_ATTR = '© waqi.info';
var credits_url = 'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png';
var credits_attrib = '© OpenStreetMap';
var osmLayer = L.tileLayer(credits_url, {attribution: [credits_attrib, WAQI_ATTR]});
map.addLayer(osmLayer);
L.control.layers(baseLayers).addTo(map);
maps.push(map)
});
});
html {
height: 100%
}
body {
height: 100%;
margin: 0;
}
.map {
height: 200px;
width: 200px;
}
<link href="http://cdn.leafletjs.com/leaflet-0.7.5/leaflet.css" rel="stylesheet"/>
<script src="http://cdn.leafletjs.com/leaflet-0.7.5/leaflet.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="maps"></div>

Related

How to remove specific marker by type on leaflet?

I have a project that is making webgis to display data on a map and a check box to display data or hide that data.
I have finished making it with the google map version, but because it is paid, I look for the free version using leaflets.
But I have a problem with the check box on the leaflet, after unchecking, the marker does not disappear.
var date = new Date();
var year = date.getFullYear();
// Center of the map
var center = [-1.1329372, 120.0350916];
// Create the map
var map = L.map("map").setView(center, 5);
// Set up the Google Map Hybrib layer
L.tileLayer("http://mt0.google.com/vt/lyrs=m&hl=en&x={x}&y={y}&z={z}", {
attribution:
"Map data #" +
year +
" Google for Dinas Kebersihan Lingkungan Hidup dan Pertamanan",
maxZoom: 18
}).addTo(map);
// Call JSON
$(document).ready(function() {
getUsers();
});
// Format Icon Leaflet
var customIcons = L.Icon.extend({});
var merahIcon = new customIcons({ iconUrl: "merah.png" }),
biruIcon = new customIcons({ iconUrl: "biru.png" }),
kuningIcon = new customIcons({ iconUrl: "kuning.png" });
var icons = {
merah: merahIcon,
biru: biruIcon,
kuning: kuningIcon
};
// Marker Group
var markerGroups = {
merah: [],
biru: [],
kuning: []
};
// Get Data
function getUsers() {
$.getJSON("json.php", function(data) {
for (var i = 0; i < data.length; i++) {
var location = new L.LatLng(data[i].latitude, data[i].longitude);
var name = data[i].name;
var description = data[i].description;
var type = data[i].type;
var marker = createMarker(location, name, description, type);
}
});
}
// Create Marker
function createMarker(location, name, description, type) {
var content = "<b>" + name + "</b> <br/>" + description;
var marker = L.marker(location, { icon: icons[type] })
.bindPopup(content)
.addTo(map);
if (!markerGroups[type]) markerGroups[type] = [];
console.log(markerGroups[type]);
markerGroups[type].push(marker);
var html = "<b>" + name + "</b> <br/>" + address;
return marker;
}
// Create Checkbox Button
function toggleGroup(type) {
for (var i = 0; i < markerGroups[type].length; i++) {
var marker = markerGroups[type][i];
if (!marker.getVisible()) {
marker.setVisible(true);
} else {
marker.setVisible(false);
}
}
}
#map {
height: 600px;
}
<link
rel="stylesheet"
href="https://unpkg.com/leaflet#1.6.0/dist/leaflet.css"
/>
<script src="https://unpkg.com/leaflet#1.6.0/dist/leaflet.js"></script>
<script src="https://code.jquery.com/jquery-3.4.1.js"></script>
<div class="map_wrap">
<div class="siderbarmap">
<ul>
<input
id="merahCheckbox"
type="checkbox"
onclick="toggleGroup('merah')"
checked="checked"
autocomplete="off"
/>
<label>Merah</label
><br />
<input
id="biruCheckbox"
type="checkbox"
onclick="toggleGroup('biru')"
checked="checked"
autocomplete="off"
/>
<label>Biru</label
><br />
<input
id="kuningCheckbox"
type="checkbox"
onclick="toggleGroup('kuning')"
checked="checked"
autocomplete="off"
/>
<label>Kuning</label
><br />
</ul>
</div>
<div id="map"></div>
</div>
i found new method, thx for re
function toggleGroup(type) {
if ($('.leaflet-pane img[src="'+type+'.png"]').is(':hidden')){
$('.leaflet-pane img[src="'+type+'.png"]').show();
} else {
$('.leaflet-pane img[src="'+type+'.png"]').hide();
}
}

Make mapfish print request to geoserver

I am trying to print a custom map using openlayers and geoserver.
However i am unable to find the implementation for it.
Any code snippet would be appreciated!
Here is my code for displaying so far:
<!DOCTYPE html>
<html>
<head>
<title>Export PDF example</title>
<link rel="stylesheet" href="https://openlayers.org/en/v4.1.1/css/ol.css" type="text/css">
<script src="https://openlayers.org/en/v4.1.1/build/ol.js"></script>
</head>
<body>
<form class="form">
<i><label>Choose the layers</label><br></i>
<b><input type="checkbox" id="layer1" name="a">Boundaries<br>
<input type="checkbox" id="layer2" name="a">Roads<br>
<input type="checkbox" id="layer3" name="a">Water bodies<br>
<input type="button" onclick="showMap()" value="Display"></b>
<input type="button" onclick="printMap()" value="Print map">
<script>
function printMap(){
//needs to be completed!
}
function showMap(){
layer1_checked = document.getElementById('layer1').checked;
layer2_checked = document.getElementById('layer2').checked;
layer3_checked = document.getElementById('layer3').checked;
var layers_array = [];
if(layer1_checked){
layers_array.push('topp:tasmania_state_boundaries');
}
if(layer2_checked){
layers_array.push('topp:tasmania_roads');
}
if(layer3_checked){
layers_array.push('topp:tasmania_water_bodies');
}
layers_param = "";
for(var i=0;i<layers_array.length;i++){
layers_param = layers_param+layers_array[i]+",";
}
layers_param = layers_param.substring(0,layers_param.length-1);
document.getElementById('map').innerHTML="";
var format = 'image/png';
var bounds = [145.19754, -43.423512,148.27298000000002, -40.852802];
var mousePositionControl = new ol.control.MousePosition({
className: 'custom-mouse-position',
target: document.getElementById('location'),
coordinateFormat: ol.coordinate.createStringXY(5),
undefinedHTML: ' '
});
var tiled = new ol.layer.Tile({
visible: true,
source: new ol.source.TileWMS({
url: 'http://localhost:8080/geoserver/topp/wms',
params: {'FORMAT': format,
'VERSION': '1.1.1',
tiled: true,
STYLES: '',
LAYERS: layers_param,
tilesOrigin: 145.19754 + "," + -43.423512
}
})
});
var projection = new ol.proj.Projection({
code: 'EPSG:4326',
units: 'degrees',
axisOrientation: 'neu',
global: true
});
var map = new ol.Map({
controls: ol.control.defaults({
attribution: false
}).extend([mousePositionControl]),
target: 'map',
layers: [
tiled
],
view: new ol.View({
projection: projection
})
});
map.getView().on('change:resolution', function(evt) {
var resolution = evt.target.get('resolution');
var units = map.getView().getProjection().getUnits();
var dpi = 25.4 / 0.28;
var mpu = ol.proj.METERS_PER_UNIT[units];
var scale = resolution * mpu * 39.37 * dpi;
if (scale >= 9500 && scale <= 950000) {
scale = Math.round(scale / 1000) + "K";
} else if (scale >= 950000) {
scale = Math.round(scale / 1000000) + "M";
} else {
scale = Math.round(scale);
}
});
map.getView().fit(bounds, map.getSize());
map.on('singleclick', function(evt) {
var view = map.getView();
var viewResolution = view.getResolution();
var source = tiled.getSource();
var url = source.getGetFeatureInfoUrl(
evt.coordinate, viewResolution, view.getProjection(),
{'INFO_FORMAT': 'text/html', 'FEATURE_COUNT': 50});
});
}
</script>
</body>
</html>
So far displaying the layers seems to be working fine.
I need implementation help for printMap function. Besides it is suppose to use Mapfish plugin for printing!

retrieve value from mysql database to be used as value in javascript

I am making a map and I want to use the value from the database to be used as the coordinates in the javascript. Please see below:
I want to change the default values of the longitude and latitude by fetching data fro the database but I don't know how.
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<title>Google Maps</title>
<script src="http://maps.google.com/maps/api/js?sensor=false" t type="text/javascript"></script>
<script type="text/javascript">
function LatiPoint(options)
{
this.UserName = "";
this.JobType = "";
this.UserMood = "";
this.Latitude = "";
this.Longitude = "";
this.Pic = "";
this.Color = "red";
this.OpenInfoWindowInitial = false;
if (options != null)
{
this.UserName = options.UserName;
this.JobType = options.JobType;
this.UserMood = options.UserMood;
this.Latitude = options.Latitude;
this.Longitude = options.Longitude;
this.Pic = options.Pic;
this.Color = ( options.Color == null ? "red" : options.Color );
this.OpenInfoWindowInitial = ( options.OpenInfoWindowInitial == null ? false : options.OpenInfoWindowInitial );
}
}
</script>
<script type="text/javascript">
var LatiPts = new Array();
LatiPts[0] = new LatiPoint({UserName:'Dukot',JobType:'Balulang Cagayan De Oro',UserMood:'drinking beer',Latitude:8.4542363,Longitude:124.63189769999997,Color:'yellow',OpenInfoWindowInitial:true,Pic:''});
LatiPts[1] = new LatiPoint({UserName:'Alot',JobType:'Cagayan De Oro',UserMood:'with classmates',Latitude:8.458353831903118,Longitude:124.63627706511227,Color:'yellow',OpenInfoWindowInitial:true,});
LatiPts[2] = new LatiPoint({UserName:'Lindongan',JobType:'SM Cagayan De Oro',UserMood:'feeling bored',Latitude:8.456188949479728,Longitude:124.62177167875973,Color:'yellow',OpenInfoWindowInitial:true,});
LatiPts[3] = new LatiPoint({UserName:'Galal',JobType:'Carmen Cagayan De Oro',UserMood:'beer',Latitude:8.467607505884205,Longitude:124.62271581633297,Color:'yellow',OpenInfoWindowInitial:true,});
LatiPts[4] = new LatiPoint({UserName:'Belen',JobType:'Cagayan De Oro',UserMood:'beer',Latitude:8.46332028090713,Longitude:124.63537584288326,Color:'yellow',OpenInfoWindowInitial:true,});
</script>
<script type="text/javascript">
//<![CDATA[
var infoWindows = [];
var markers = [];
// A function to create the marker and set up the event window
function createMarker(map, point, title, icon) {
var marker = new google.maps.Marker();
marker.setMap(map);
marker.setPosition(point);
marker.setTitle(title);
marker.setIcon(icon)
google.maps.event.addListener(marker, 'click', function() {
for (var i = 0; i < infoWindows.length; i++)
infoWindows[i].setZIndex(0);
infoWindows[marker.counter].setZIndex(1);
infoWindows[marker.counter].open(marker.getMap(), marker);
});
return marker;
}
function createInfoWindow(html)
{
var infoWindow = new google.maps.InfoWindow();
infoWindow.setContent(html);
infoWindow.setZIndex(0);
return infoWindow;
}
function initialize() {
// Create the Google Map
var map = new google.maps.Map(document.getElementById("map"));
map.setMapTypeId(google.maps.MapTypeId.ROADMAP);
map.setCenter(new google.maps.LatLng(0,0));
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < LatiPts.length; i++) {
var lpt = LatiPts[i];
var point = new google.maps.LatLng(lpt.Latitude, lpt.Longitude);
var html = "<span style='font-family:Arial;font-size:9pt'>";
html += "<span style='font-size:12pt;font-weight:bold'>" + lpt.UserName + "</span><br />";
html += lpt.UserMood.substring(0, 30) + "<br/>";
html += lpt.JobType.substring(0, 30) + "<br/>";
html += "</span>";
var imgPath
if(lpt.Pic != "") {
imgPath = lpt.Pic
} else {
imgPath = "http://maps.gstatic.com/intl/en_ALL/mapfiles/marker.png"
}
//alert("imgPath = " + imgPath + " Pic: " + lpt.Pic)
var icon = new google.maps.MarkerImage(imgPath);
//icon.shadowSize = GSize.ZERO;
var infoWindow = createInfoWindow(html);
infoWindow.open();
var marker = createMarker(map, point, lpt.UserName, icon);
marker.setZIndex(0);
marker.counter = i;
if (LatiPts[i].OpenInfoWindowInitial)
{
infoWindow.open(marker.getMap(), marker);
}
infoWindows.push(infoWindow);
markers.push(marker);
bounds.extend(point);
}
map.setCenter(bounds.getCenter());
map.fitBounds(bounds);
}
function handleNoFlash(code)
{
if ( code == GStreetviewPanorama.ErrorValues.FLASH_UNAVAILABLE )
alert( 'You need flash player to view the panorama.' );
}
function convertLatLngToString(latlng)
{
var hour = parseInt(latlng)
var min = parseInt((latlng - hour) * 60)
var second = (((latlng - hour) * 60) - min) * 60
return (hour + "° " + min + "' " + second.toFixed(2) + "" ");
}
//]]>
</script>
<style type="text/css">
/*give the body height:100% so that its child
elements can have percentage heights*/
body{ margin:0;padding:0;height:100% }
div.fullscreen{
display:block;
position:absolute;
top:0;
left:0;
width:100%;
height:100%;
z-index: 9999;
margin: 0;
padding: 0;
background: inherit;
}
</style>
</head>
<body onload="initialize()">
<div id="map" class="fullscreen" style="width:100%; height:100%"></div>
<div id="streetview" style="width: 650px; height: 400px; display: none;"></div>
<noscript>
<b>JavaScript must be enabled in order for you to use Google Maps.</b>
</noscript>
</body>
</html>
You can do something like this:
<?php /* read from database into variable $results*/ ?>
this.UserName = "<?php echo $results; ?>";
Hope it helps :)

Map Marker refresh/Update without refreshing whole map

I cannot figure out how to edit this to make it so the map does not refresh but it continues to refresh the marker to get the updated positions.
the positions are coming from
this line
<?php
$json_pos = file_get_contents("C:\Users\KLAUS\Desktop\New\This SAMP\scriptfiles\positions.json");
?>
right there
<?php
$json_pos = file_get_contents("C:\Users\KLAUS\Desktop\New\This SAMP\scriptfiles\positions.json");
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="refresh" content="1" />
<title>SA:MP live map</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script src="http://maps.google.com/maps/api/js?sensor=false"></script>
<style type="text/css">
#map-canvas { display: inline-block; height: 800px; width: 800px; }
#map-legend { padding: 10px; background-color: rgba(141, 142, 127, 0.46);}
</style>
</head>
<body>
<div id="map-canvas"></div>
<script src="js/SanMap.min.js"></script>
<script type="text/javascript">
var p_pos = <?php echo (empty($json_pos)) ? "" : $json_pos ?>;
var mapType = new SanMapType(0, 1, function (zoom, x, y) {
return x == -1 && y == -1
? "images/tiles/map.outer.png"
: "images/tiles/map." + zoom + "." + x + "." + y + ".png";//Where the tiles are located
});
var satType = new SanMapType(0, 3, function (zoom, x, y) {
return x == -1 && y == -1
? null
: "images/tiles/sat." + zoom + "." + x + "." + y + ".png";//Where the tiles are located
});
var map = SanMap.createMap(document.getElementById('map-canvas'),
{'Map': mapType, 'Satellite': satType}, 2, SanMap.getLatLngFromPos(0,0), false, 'Satellite');
map.controls[google.maps.ControlPosition.TOP_RIGHT].push(document.getElementById('map-legend'));
if(p_pos !== "")
{
for (var i = 0; i < Object.keys(p_pos).length; i++)
{
if(p_pos[i].online == 1) createMarker(i);
}
}
google.maps.event.addListener(map, 'click', function(event) {
var pos = SanMap.getPosFromLatLng(event.latLng);
console.log(pos.x + "," + pos.y);
});
function createMarker(id)
{
var p_windows = new google.maps.InfoWindow({
content: "<p>"+p_pos[id].name+" <b>(ID: "+id+")</b><br>Ping: "+p_pos[id].ping+"</p>"
});
var p_marker = new google.maps.Marker({
position: SanMap.getLatLngFromPos(p_pos[id].x, p_pos[id].y),
map: map,
icon: "images/marker.png"
});
google.maps.event.addListener(p_marker, 'click', function() {
p_windows.open(map,p_marker);
});
}
</script>
</body>
Remove the top header line: <meta http-equiv="refresh" content="1" /> to disable refresh the page. And then add a setInterval function to get the new data from your php service, in the call back --
first use marker.setMap(null) to clear the previous marker and then call your CreateMarker(id).
Or
you can write an updateMarker(id) function, and use marker.setPosition() to update the location.
These are generally idea for you to implement your own code.

Google Maps and Fusion tables - Loading error

I trying to do the map base on geocodezip example http://www.geocodezip.com/geoxml3_test/v3_FusionTables_CountryBrowser.html , but I have always have message on my map "Data may still be loading".
I reduce my map to only 10 polygons but I have same message over and over.
Inside left sidebar; name of the polygons are properly displayed, and when I click "show" map guide me to the exact place of the polygon, but the polygons are not displayed on the map. Does anyone have any suggestions?
My code is below.
<!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>Google Maps JavaScript API v3 Example: Fusion Tables Natural Earth Data Country Browser</title>
<style type="text/css">
html, body, #map_canvas {
width: 750px;
height: 600px;
margin: 0;
padding: 0;
}
.infowindow * {font-size: 90%; margin: 0}
</style>
<!--Load the AJAX API-->
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript" src="geoxml3_kmlStr.js"></script>
<!-- Initialize -->
<script type="text/javascript">
// 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 = [];
var geocoder = null;
// Fusion Table data ID
var FT_TableID = '1-bZhRr6OMbj4NWZcY8XnVjpijvV97yNgSXSf_mE';
var CountryName = "USA"; // "United States of America";
google.load('visualization', '1', {'packages':['corechart', 'table', 'geomap']});
function createSidebar() {
// set the query using the parameters
document.getElementById('sidebar').innerHTML = "querying for data";
var FT_Query2 = "SELECT 'name_0', 'name', 'geometry' FROM "+FT_TableID+" WHERE 'name_0' = '"+CountryName+"' ORDER by 'name'";
document.getElementById("FTquery2").innerHTML = FT_Query2;
var queryText = encodeURIComponent(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);
function getCountryNames() {
// set the query using the parameters
var FT_Query_CountryName = "SELECT 'name_0', count() FROM "+FT_TableID+" GROUP by 'name_0' ORDER by 'name_0'";
document.getElementById("FTquery4").innerHTML = FT_Query_CountryName;
var queryText = encodeURIComponent(FT_Query_CountryName);
var query = new google.visualization.Query('http://www.google.com/fusiontables/gvizdata?tq=' + queryText);
//set the callback function
query.send(createCountryDropdown);
}
function createCountryDropdown(response) {
if (!response) {
alert('no response');
return;
}
if (response.isError()) {
alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}
//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 countryNames = {};
for (var i = 0; i < numRows; i++) {
var countryName = response.getDataTable().getValue(i,0);
// countryName = countryName.substring(0,countryName.indexOf('('));
countryNames[countryName] = countryName;
}
var countryNameDropdown = "<select name='country_select' onchange='handleSelected(this)'>"
countryNameDropdown += '<option selected> - Select a country - <\/option>';
for (countryName in countryNames) {
countryNameDropdown += "<option value='"+countryName+"'>"+countryName+"</option>"
// document.getElementById('country_list').innerHTML += countryName+"<br>";
}
countryNameDropdown += "</select>"
document.getElementById('dropdown_menu').innerHTML = countryNameDropdown;
}
// ======= This function handles selections from the select box ====
function handleSelected(opt) {
if (opt.selectedIndex > 0) {
CountryName = geoXML3.nodeValue(opt[opt.selectedIndex]);
DisplayCountry();
} else {
alert("Please pick a country");
}
}
function DisplayCountry() {
// geocode the country
var addressStr = CountryName;
if (addressStr != "Baikonur Cosmodrome") addressStr += " Country";
geocoder.geocode( { 'address': addressStr}, 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);
}
});
FT_Query = "SELECT 'geometry' FROM "+FT_TableID+" WHERE 'name_0' = '"+CountryName+"';";
gpolygons = [];
layer.setQuery(FT_Query);
document.getElementById("FTquery").innerHTML = FT_Query;
createSidebar();
}
</script>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
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 there are any parameters at eh end of the URL, they will be in location.search
// looking something like "?marker=3"
// skip the first character, we are not interested in the "?"
var query = location.search.substring(1);
// split the rest at each "&" character to give a list of "argname=value" pairs
var pairs = query.split("&");
for (var i=0; i<pairs.length; i++) {
// break each pair at the first "=" to obtain the argname and value
var pos = pairs[i].indexOf("=");
var argname = pairs[i].substring(0,pos).toLowerCase();
var value = pairs[i].substring(pos+1);
if (argname == "country") {CountryName = unescape(value);}
value = pairs[i].substring(pos+1).toLowerCase();
// process each possible argname - use unescape() if theres any chance of spaces
if (argname == "geocode") {geocodeTheCountry = (value != "false");}
if (argname == "id") {id = unescape(value);}
if (argname == "filename") {filename = unescape(value);}
if (argname == "marker") {index = parseFloat(value);}
if (argname == "lat") {lat = parseFloat(value);}
if (argname == "lng") {lng = parseFloat(value);}
if (argname == "zoom") {
zoom = parseInt(value);
myGeoXml3Zoom = false;
}
if (argname == "type") {
// from the v3 documentation 8/24/2010
// HYBRID This map type displays a transparent layer of major streets on satellite images.
// ROADMAP This map type displays a normal street map.
// SATELLITE This map type displays satellite images.
// TERRAIN This map type displays maps with physical features such as terrain and vegetation.
if (value == "m") {maptype = google.maps.MapTypeId.ROADMAP;}
if (value == "k") {maptype = google.maps.MapTypeId.SATELLITE;}
if (value == "h") {maptype = google.maps.MapTypeId.HYBRID;}
if (value == "t") {maptype = google.maps.MapTypeId.TERRAIN;}
}
}
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();
if (numRows <= 1) {
document.getElementById('sidebar').innerHTML = "no data";
return;
}
//concatenate the results into a string, you can build a table here
fusiontabledata = "<table><tr>";
// for(i = 0; i < numCols; i++) {
fusiontabledata += "<th colspan='2'>" + response.getDataTable().getValue(1,0) + "</th>";
// }
fusiontabledata += "</tr><tr>";
fusiontabledata += "<tr><td colspan='2' align='left'><a href='javascript:showAll();'>show all</a></td></tr>";
for(i = 0; i < numRows; i++) {
// for(j = 0; j < numCols; j++) {
/*
var kml = response.getDataTable().getValue(i,2);
geoXml.parseKmlString("<Placemark>"+kml+"</Placemark>");
*/
fusiontabledata += "<td><a href='javascript:myFTclick("+i+")'>"+response.getDataTable().getValue(i, 1) + "</a></td><td><a href='javascript:zoomTo("+i+")'>show</a></td>";
// }
fusiontabledata += "</tr><tr>";
}
fusiontabledata += "</table>"
//display the results on the page
document.getElementById('sidebar').innerHTML = fusiontabledata;
}
function infoWindowContent(name, description, id) {
content = '<div class="FT_infowindow"><h3>' + name +
'</h3><div>' + description + '</div>';
if (typeof id != "undefined") {
content += 'zoom to';
}
content += '</div>';
return content;
}
function zoomTo(id) {
loadRow(id);
if (gpolygons[id] && gpolygons[id].bounds) {
map.fitBounds(gpolygons[id].bounds);
var queryStr = "SELECT 'geometry' FROM "+FT_TableID+" WHERE 'name_0' = '"+CountryName+"' AND 'name' = '"+gpolygons[id].name+"';"
layer.setQuery(queryStr);
document.getElementById("FTquery3").innerHTML = queryStr;
}
}
function showAll() {
layer.setQuery("SELECT 'geometry' FROM "+FT_TableID+" WHERE 'name_0' = '"+CountryName+"';");
}
function loadRow(row) {
if (!gpolygons[row]) {
var name = FTresponse.getDataTable().getValue(row,1);
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] = new Object();
gpolygons[row].position = geoXml.docs[0].gpolygons[0].bounds.getCenter();
gpolygons[row].bounds = geoXml.docs[0].gpolygons[0].bounds;
gpolygons[row].name = name;
}
}
function myFTclick(row) {
var description = FTresponse.getDataTable().getValue(row,0);
var name = FTresponse.getDataTable().getValue(row,1);
loadRow(row);
var position = gpolygons[row].position;
/*
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: infoWindowContent(name, description, row),
pixelOffset: new google.maps.Size(0, 2),
position: position
});
// Infowindow-opening event handler
infoWindow.open(map);
}
function initialize() {
myOptions = {
zoom: zoom,
center: myLatLng,
// zoom: 5,
// center: myLatlng,
mapTypeId: maptype
};
map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
google.maps.event.addListener(map, "click", function(event) {
infoWindow.close();
var FT_click_query="SELECT 'name_0' FROM "+FT_TableID+" WHERE ST_INTERSECTS('geometry',CIRCLE(LATLNG"+event.latLng+", 1));";
// alert(event.latLng+"query="+FT_click_query);
// set the query using the parameters
var queryText = encodeURIComponent(FT_click_query);
var query = new google.visualization.Query('http://www.google.com/fusiontables/gvizdata?tq=' + queryText);
document.getElementById("FTquery5").innerHTML = FT_click_query;
//set the callback function
query.send(getCountryFromClick);
});
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 'geometry' FROM "+FT_TableID+" WHERE 'name_0' = '"+CountryName+"';";
var FT_Options = { suppressInfoWindows: true, query:FT_Query };
document.getElementById("FTquery").innerHTML = FT_Query;
layer = new google.maps.FusionTablesLayer(FT_TableID, FT_Options);
layer.setMap(map);
google.maps.event.addListener(layer, "click", function(event) {
infoWindow.close();
infoWindow.setContent(infoWindowContent(event.row.name.value,event.row.name_0.value));
infoWindow.setPosition(event.latLng);
infoWindow.open(map);
});
getCountryNames();
}
function getCountryFromClick(response) {
if (!response) {
alert('no response');
return;
}
if (response.isError()) {
alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}
//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();
if (numRows <= 1) {
return;
}
CountryName = response.getDataTable().getValue(1, 0);
// alert("CountryName="+CountryName);
DisplayCountry();
}
</script>
</head>
<body onload="initialize()">
<table style="width:100%;">
<tr><td colspan="2"><h3>Google Maps JavaScript API v3 Example: Fusion Tables Natural Earth Data Country Browser</h3></td></tr>
<tr><td colspan="2"><div id="dropdown_menu">
</div></td></tr>
<tr>
<td><div id="map_canvas"></div></td>
<td><div id="sidebar" style="width:300px;height:600px; overflow:auto"></div></td>
</tr>
<tr><td colspan="2"><div id="FTquery"></div></td></tr>
<tr><td colspan="2"><div id="FTquery2"></div></td></tr>
<tr><td colspan="2"><div id="FTquery3"></div></td></tr>
<tr><td colspan="2"><div id="FTquery4"></div></td></tr>
<tr><td colspan="2"><div id="FTquery5"></div></td></tr>
</table>
<div id="country_list"></div>
<script src="http://www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-162157-1";
urchinTracker();
</script>
</body>
</html>
With the new encrypted ids, you need to use the new query syntax:
layer.setQuery({select:'geometry',from:FT_TableID,where:"'name_0' = '"+CountryName+"'"});
layer.setQuery({select:'geometry',from:FT_TableID,where:"'name_0' = '"+CountryName+"' AND 'name' = '"+gpolygons[id].name+"'"});
and most important (if you only want the selected polygons to show):
layer = new google.maps.FusionTablesLayer(FT_Options);
The old "string" queries only seem to work with the numeric IDs.
working example
updated original example with new syntax
See answer above, it works for me. Thanks to geocodezip
Non numric fields should be enclosed in single quotes under double quotes, ex: " SELECT 'DATE' <= '2013-11-11' "
For complete example, you can have a look here.

Categories

Resources