I am currently working on a fairly basic phone gap applications. On one page I populate a listview from a JSON object. It populates fine and I am able to click on the list to go to the next page. The problem arises when I click the android back button (this takes you back to the previous page), the content that was loaded has no disappeared. As far as I can tell the DOM element disappears as soon as the new page is loaded (however i am new to this technology so I could be wrong).
Here is the html
<!DOCTYPE HTML>
<html>
<head>
<meta name="viewport" content="width=320; user-scalable=no" />
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<title>PhoneGap Demo With JQuery Mobile</title>
<link rel="stylesheet" href="jquery.mobile/jquery.mobile-1.0b2.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="pgandjqm-style-override.css" type="text/css" charset="utf-8" />
<script type="text/javascript" src="jquery.mobile/jquery-1.6.2.min"></script>
<script type="text/javascript" charset="utf-8" src="phonegap-1.0.0.js"></script>
<script src="jquery.mobile/jquery.mobile-1.0b2.js"></script>
<script type="text/javascript" charset="utf-8" src="main.js"></script>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
</head>
<body onload="init();" data-theme="a">
<div data-role="page" data-theme="a">
<div data-role="header">
<img src="images/joycard.png" alt="JoyCard" class="banner">
</div>
<div data-role="navbar">
<ul>
<li><a onclick="categoriesList();" class="ui-btn-active">KATEGORIEN</a></li>
<li><a onclick="mapDetails();">IN DER NÄHE</a></li>
<li><a onclick="allPartners();">ALLE PARTNER</a></li>
</ul>
</div><!-- /navbar -->
<div id="list" data-role="content" data-theme="a">
<ul data-role="listview" data-inset="true" data-theme="a">
</ul>
</div><!-- end jqm content -->
<div id="allPartners" data-role="content">
<ul data-role="listview" data-inset="true" data-theme="a">
</ul>
</div><!--/all partners list -->
<div id="loctext" ></div>
<div id="map_canvas" class="mapView"></div>
<div id="menu" data-role="content" class="menu" onClick="hideMenu();">
<img src="images/news.png" alt="News">
<img src="images/contact.png" alt="Contact">
<img src="images/info.png" alt="Info">
</div>
</div>
</body>
</html>
and the js/query
var menuUp = false;
var gotLoc = false;
var waitingForLoc = false;
var allWaitingForLoc = false;
var currentId;
var venueId;
var onDetails = false;
var onDetail = false;
var neighborhoods = [];
var markersIds = [];
var mapLoaded = false;
var latlng;
var myLat;
var myLong
document.addEventListener("menubutton", onMenuKeyDown, false);
function init() {
$("#map_canvas").hide();
$("#allPartners").hide();
$("#menu").hide();
var suc = function(position) {
gotLoc = true;
latlng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
myLat = position.coords.latitude;
myLong = position.coords.longitude;
if (waitingForLoc == true) {
mapDetails();
} else if (allWaitingForLoc == true) {
allPartners();
}
}
var err = function(error) {
alert("Problem with GPS" + error.message);
}
var geoOptions = {
enableHighAccuracy: true,
}
getCategories();
navigator.geolocation.getCurrentPosition(suc, err, geoOptions);
}
function categoriesList() {
$("#allPartners").hide();
$("#map_canvas").hide();
$("#list").show();
}
function allPartners() {
if (gotLoc == true) {
$('#allPartners ul').empty();
$.getJSON("http://www.aURLiamusing.com" +
"&lat=" + myLat + "&lon=" + myLong,
function(data){
$.each(data, function(key, value){
$('<li id="'+ value.id +'" class="list-item-li" onclick="changeToDiscountDetails(this);" data-theme="a">' + value.venue + '</li>').appendTo("#allPartners ul");
});
});
$("#map_canvas").hide();
$("#list").hide();
$("#allPartners").show();
} else if (gotLoc == false) {
$("#list").hide();
jQuery("#loctext").append("Getting geolocation . . .");
waitingForLoc = false;
mapWaitingForLoc = true;
}
}
//change for Iphone
function onMenuKeyDown() {
if (menuUp == true){
$("#menu").hide();
menuUp = false;
} else {
$("#menu").show();
menuUp = true;
}
}
function mapDetails() {
if (mapLoaded == false) {
if (gotLoc == true) {
var mapListURL = "http://www.aURLiamusing.com" +
"&lat=" + myLat + "&lon=" + myLong;
console.log("this is just before the getJson");
$.getJSON(mapListURL,
function(data){
$.each(data, function(key, value){
var pos = new google.maps.LatLng(value.lat, value.lon);
neighborhoods[key] = pos;
markersIds[key] = value.id;
});
setMap();
});
}
if (gotLoc == false) {
$("#list").hide();
jQuery("#loctext").append("Getting geolocation . . .");
allWaitingForLoc = false;
waitingForLoc = true;
}
} else if (mapLoaded == true) {
$("#allPartners").hide();
$("#list").hide();
$("#map_canvas").show();
}
}
function setMap() {
var iterator = 0;
var myOptions = {
zoomControl: true,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.SMALL
},
scaleControl: true,
streetViewControl: false,
mapTypeControl: true,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
},
zoom: 12,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
};
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var myMarker = new google.maps.Marker({
position: latlng,
map: map,
title:"Hello World!",
});
myMarker.setMap(map);
for (var i = 0; i < neighborhoods.length; i++) {
var marker = new google.maps.Marker({
position: neighborhoods[i],
map: map,
title:"Hello World!",
});
marker.set("id", markersIds[i]);
marker.setMap(map);
marker.metadata = {type: "point", id: i};
google.maps.event.addListener(marker, 'click', function() {
var val = this.get("id");
venueId = val;
console.log(val);
onDetails = false;
onDetail = true;
$.mobile.changePage("discountDetails.html", { transition: "slide"});
});
}
mapLoaded = true;
$("#allPartners").hide();
$("#list").hide();
$("#map_canvas").show();
}
function hideMenu(){
$("#menu").hide();
}
$('div').live('pageshow',function(event, ui){
if (onDetails == true) {
getVenues();
} else if(onDetail == true) {
populateDetail();
}
});
function populateDetail() {
var url = "http://www.aURLiamusing.com";
$.getJSON(url,
function(data){
$.each(data, function(key, value){
$("#details").append('<h2 data-theme="a">' + value.venue + '</h2>');
var picUrl = value.image;
picUrl.replace(/\/$/, '');
$("#details").append('<img data-theme="a" src="' + picUrl + '"></p>');
$("#details").append('<p data-theme="a">' + value.description + '</p>');
$("#details").append('<p data-theme="a">' + value.offer1 + '</p>');
$("#details").append('<p data-theme="a">' + value.offer2 + '</p>');
});
});
}
function getCategories() {
$('#list ul').empty();
$.getJSON("http://www.aURLiamusing.com",
function(data){
$.each(data, function(key, value){
$('<li id="'+ value.id +'" class="list-item-li" onclick="changeToDetails(this);" data-theme="a">' + value.title + '</li>').appendTo("#list ul");
});
});
}
function getVenues() {
var url = "http://www.aURLiamusing.com;
$.getJSON(url,
function(data){
$.each(data, function(key, value){
$('<li id="'+ value.id +'" class="list-item-li" onclick="changeToDiscountDetails(this);" data-theme="a">' + value.venue + '</li>').appendTo("#venueList ul");
});
});
}
function changeToDetails(object) {
currentId = $(object).attr('id');
onDetails = true;
$.mobile.changePage("details.html", { transition: "slide"});
}
function changeToDiscountDetails(object) {
venueId = $(object).attr('id');
onDetails = false;
onDetail = true;
$.mobile.changePage("discountDetails.html", { transition: "slide"});
}
Thanks for any help
try using
data-dom-cache="true" in the < div data-role="page" > tag
Related
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();
}
}
I'm working with Flickr's API. I am asynchronously loading some images and related metadata. I have a script where I do all this, using three AJAX calls:
$(document).ready(function() {
var latLon = {
lat: 38.736946,
lng: -9.142685
};
var numero = 10;
var clicked = 1;
$("#sq").click(function() {
clicked = 1;
});
$("#lg-sq").click(function() {
clicked = 2;
});
$("#thumb").click(function() {
clicked = 3;
});
$("#small").click(function() {
clicked = 4;
});
$("#mid").click(function() {
clicked = 5;
});
$("#apagar").click(function() {
$("#results").html('');
});
$('#pesquisar').click(function() {
$("#results").html('');
$.ajax({
url: 'https://api.flickr.com/services/rest/?method=flickr.photos.search',
dataType: 'xml',
data: {
api_key: '2fd41b49fedfd589dc265350521ab539',
tags: $("#tag").val(),
format: 'rest'
},
success: sucessHandler,
error: errorHandler
});
function sucessHandler(data) {
$("#results").html('');
var fotos = Array.prototype.slice.call($(data).find("photo"));
if ($("#numero").val() != "") {
numero = parseInt($("#numero").val());
console.log("entrou");
}
fotos.forEach(function(foto, key) {
if (key < numero) {
$.ajax({
url: 'https://api.flickr.com/services/rest/?method=flickr.photos.getSizes',
dataType: 'xml',
data: {
api_key: '2fd41b49fedfd589dc265350521ab539',
photo_id: $(foto).attr('id'),
format: 'rest'
},
success: function(dataSize) {
var farmId = $(foto).attr('farm');
var serverId = $(foto).attr('server');
var Id = $(foto).attr('id');
var secret = $(foto).attr('secret');
var src = "https://farm" + farmId + ".staticflickr.com/" + serverId + "/" + Id + "_" + secret + ".jpg";
$.ajax({
url: 'https://api.flickr.com/services/rest/?method=flickr.photos.getInfo',
dataType: 'xml',
data: {
api_key: '2fd41b49fedfd589dc265350521ab539',
photo_id: $(foto).attr('id'),
format: 'rest',
secret: secret
},
success: function(dataInfo) {
for (var i = 1; i < 6; i++) {
if (clicked == i) {
var size = dataSize.getElementsByTagName('size')[i - 1];
var title = dataInfo.getElementsByTagName('title')[0].textContent;
var owner = $(dataInfo.getElementsByTagName('owner')[0]).attr('username');
var date = $(dataInfo.getElementsByTagName('dates')[0]).attr('taken');
var local = $(dataInfo.getElementsByTagName('owner')[0]).attr('location');
if (local == "") {
local = "desconhecido";
}
var tags = $(dataInfo.getElementsByTagName('tag'));
var allTags = "";
var width = $(size).attr("width");
var height = $(size).attr("height");
var htmlText = "<div class='col-md-12 jumbotron style='display:inline-block;vertical-align:text-top'><p hidden>" + Id + "</p><img src =" + src + " width=" + width + " height=" + height + "><img class='pull-right' src='icon.png' width=50 height=50/>" +
"<p><b>título: </b>:" + title + "</p>" + "<p><b>autor: </b>" + owner + "</p>" + "<p><b>data: </b>" + date + "</p>" + "<p><b>local: </b>" + local + "</br></br>"
for (var i = 0; i < tags.length; i++) {
htmlText += "<label style='border:1px solid grey;margin-left:10px'>" + $(tags[i]).attr('raw') + "</label>";
}
htmlText += "</div>";
$('#results').append(htmlText);
/*$('#results').append("<div class='col-md-4'><img src ="+src+" width="+width+" height="+height+">");
$('#results').append("<p><b>título: </b>:" + title + "</p>" + "<p><b>autor: </b>" + owner + "</p>" + "<p><b>data: </b>" + date + "</p>" + "<p><b>local: </b>" + local);
$('#results').append("</br>");*/
}
}
},
error: function(req, status, err) {
}
});
},
error: errorSize
});
}
});
function errorSize(req, status, err) {
console.log("error size");
}
}
function errorHandler(req, status, err) {
console.log("fail");
}
});
var map;
function initMap() {
map = new google.maps.Map(
document.getElementById('map'), {
center: latLon,
zoom: 8
}
);
}
});
html
<html lang="en">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript" src="FlickrPhotosSearch.js"></script>
<link rel="stylesheet" type="text/css" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<style type="text/css">
#sq,
#lg-sq,
#thumb,
#small,
#mid,
#ori {
width: 100%
}
input {
width: 50px;
}
#map{
width:1240;
height:300;
}
</style>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-12">
<h2>Escolha o tamanho das imagens (em píxeis) que quer visualizar</h2>
</div>
</div>
<div class="row">
<div class="col-md-2">
<button type="button" class="btn btn-primary" id="sq">Square [75X75]</button>
</div>
<div class="col-md-2">
<button type="button" class="btn btn-primary" id="lg-sq">Large Square</button>
</div>
<div class="col-md-2">
<button type="button" class="btn btn-primary" id="thumb">Thumbnail</button>
</div>
<div class="col-md-2">
<button type="button" class="btn btn-primary" id="small">Small</button>
</div>
<div class="col-md-2">
<button type="button" class="btn btn-primary" id="mid">Medium</button>
</div>
</div>
<div class="row">
<div class="col-md-12">
<h2>Pesquisa de fotos</h2>
</div>
</div>
<div class="row">
<div class="col-lg-2">
<input type="text" class="form-control" id="tag">
</div>
<div class="col-lg-1">
<button type="button" class="btn btn-success" id="pesquisar">Pesquisar</button>
</div>
<div class="col-lg-1">
<button type="button" class="btn btn-alert" id="apagar">Apagar</button>
</div>
<div class="col-lg-2">
<input type="text" id="numero" class="form-control" placeholder="numero de fotos">
</div>
</div>
<hr>
<div id="map"></div>
<div class="row" id="results" style="margin-top:100px;margin-left:50px">
</div>
</div>
<script src="googleapi.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAKKKmlp2uHM78D9NMhhzY-lVQmzI81Z_E&callback=initMap" async defer></script>
</body>
</html>
second script
$(document.ready(function(){
var map;
var latLon = {lat:38.736946,lng:-9.142685};
function initMap() {
map = new google.maps.Map(
document.getElementById('map'),
{
center: latLon,
zoom: 8
}
);
}
});
I coded a call to an initMap function on the bottom, but when I try to invoke it, I get the error:
initMap is not a function
I need to make this function available so I can make another AJAX call with the previously-described data. How can I do that?
You need to move initMap() function outside the $(document).ready() function. This method of initializing google maps requires that initMap is accessible globally.
initMap() has to be outside any other function, right inside <script> tag.
$(document).ready(function() {
// all your other stuff
});
var map;
var latLon = {lat:38.736946,lng:-9.142685};
function initMap() {
map = new google.maps.Map(
document.getElementById('map'),
{
center: latLon,
zoom: 8
}
);
}
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 :)
This is kind of an update to a question I asked earlier but never got an answer here previous question. I've got a google map that creates and loads different categories of markers from an xml file when the corresponding checkbox is clicked and then updates the list on a sidebar. I'd like to load each category into its own separate sidebar so I can split them up or stack them side-by-side, etc. When I click the check-boxes the first list (the list of huts) gets loaded into both sidebars but the second list (list of yurts) gets loaded correctly into its corresponding sidebar. I don't understand why one list gets loaded into both sidebars but the other list gets loaded correctly into just one. Thanks in advance for any help. The code is all below:
Javascript
var side_bar_html = "";
//var for kml route layers
var routes = {
y: {
name: "Winter Routes",
url: "http://www.huts.org/Tests/Maps/GPSTracks/Margys_MacV2.kml"
},
z: {
name: "Summer Routes",
url: "http://www.huts.org/Tests/Maps/GPSTracks/Telluride_to_Last_Dollar.kml"
},
};
var gmarkers = [];
var gicons = [];
var map = null;
var infowindow = new google.maps.InfoWindow(
{
size: new google.maps.Size(100,150)
});
gicons["ltblue"] = new google.maps.MarkerImage("images/marker2_ltblue.png");
var iconImage = new google.maps.MarkerImage('images/marker2_ltblue.png');
function getMarkerImage(iconColor) {
if ((typeof(iconColor)=="undefined") || (iconColor==null)) {
iconColor = "ltblue";
}
if (!gicons[iconColor]) {
gicons[iconColor] = new google.maps.MarkerImage("images/marker2_"+ iconColor +".png");
}
return gicons[iconColor];
}
function category2color(category) {
var color = "ltblue";
switch(category) {
case "huts": color = "ltblue";
break;
case "yurts": color = "orange";
break;
case "demohuts": color = "red";
break;
default: color = "ltblue";
break;
}
return color;
}
gicons["huts"] = getMarkerImage(category2color("huts"));
gicons["yurts"] = getMarkerImage(category2color("yurts"));
gicons["demohuts"] = getMarkerImage(category2color("demohuts"));
// A function to create the marker and set up the event window
function createMarker(latlng,name,html,category) {
var contentString = html;
var marker = new google.maps.Marker({
position: latlng,
icon: gicons[category],
map: map,
title: name,
zIndex: Math.round(latlng.lat()*-100000)<<5
});
// === Store the category and name info as a marker properties ===
marker.mycategory = category;
marker.myname = name;
gmarkers.push(marker);
//google.maps.event.addListener(marker, 'click', function() {
// infowindow.setContent(contentString);
// infowindow.open(map,marker);
// });
google.maps.event.addListener(marker, 'click', function() {
var testimonial = document.getElementById('hutMapinfo');
testimonial.innerHTML = contentString;
});
}
// == shows all markers of a particular category, and ensures the checkbox is checked ==
function show(category) {
for (var i=0; i<gmarkers.length; i++) {
if (gmarkers[i].mycategory == category) {
gmarkers[i].setVisible(true);
}
}
// == check the checkbox ==
document.getElementById(category+"box").checked = true;
}
// == hides all markers of a particular category, and ensures the checkbox is cleared ==
function hide(category) {
for (var i=0; i<gmarkers.length; i++) {
if (gmarkers[i].mycategory == category) {
gmarkers[i].setVisible(false);
}
}
// == clear the checkbox ==
document.getElementById(category+"box").checked = false;
// == close the info window, in case its open on a marker that we just hid
infowindow.close();
}
// == a checkbox has been clicked ==
function boxclick(box,category) {
if (box.checked) {
show(category);
} else {
hide(category);
}
// == rebuild the side bar
makeSidebar();
}
function myclick(i) {
google.maps.event.trigger(gmarkers[i],"click");
}
// == rebuilds the sidebar to match the markers currently displayed ==
function makeSidebar() {
var html = "";
for (var i=0; i<gmarkers.length; i++) {
if (gmarkers[i].getVisible()) {
html += '<a href="javascript:myclick(' + i + ')" onmouseover="gmarkers['+ i +'].setAnimation(google.maps.Animation.BOUNCE)" onmouseout="gmarkers['+ i +'].setAnimation(null)">' + gmarkers[i].myname + '<\/a><br>';
}
document.getElementById(gmarkers[i].mycategory+"side_bar").innerHTML = html;
}
}
function initialize() {
var myOptions = {
zoom: 7,
center: new google.maps.LatLng(39.192948, -105.089823),
mapTypeId: google.maps.MapTypeId.TERRAIN
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
//google.maps.event.addListener(map, 'click', function() {
// infowindow.close();
// });
// Read the data
downloadUrl("coloradoYurtsToggleTest.xml", function(doc) {
var xml = xmlParse(doc);
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
// obtain the attribues of each marker
var lat = parseFloat(markers[i].getAttribute("lat"));
var lng = parseFloat(markers[i].getAttribute("lng"));
var point = new google.maps.LatLng(lat,lng);
var name = markers[i].getAttribute("label");
var html = GXml.value(markers[i].getElementsByTagName("infowindow")[0]);
var category = markers[i].getAttribute("category");
var season = markers[i].getAttribute("season");
// create the marker
var marker = createMarker(point,name,html,category);
}
// == show or hide the categories initially ==
show("huts");
hide("yurts");
// == create the initial sidebar ==
makeSidebar();
});
createRouteTogglers();
}
// the important function... routes[id].xxxxx refers back to the top
function toggleRoute(checked, id) {
if (checked) {
var layer = new google.maps.KmlLayer(routes[id].url, {
preserveViewport: true,
suppressInfoWindows: false
});
// store kml as obj
routes[id].obj = layer;
routes[id].obj.setMap(map);
}
else {
routes[id].obj.setMap(null);
delete routes[id].obj;
}
};
// create the Routes controls
function createRouteTogglers() {
var html = "<form><ul>";
for (var prop in routes) {
html += "<li id=\"selector-" + prop + "\"><input type='checkbox' id='" + prop + "'" +
" onclick='highlight(this,\"selector-" + prop + "\"); toggleRoute(this.checked, this.id)' \/>" +
routes[prop].name + "<\/li>";
}
html += "<\/ul><\/form>";
document.getElementById("routeLayers").innerHTML = html;
};
// Append Class on Select
function highlight(box, listitem) {
var selected = 'selected';
var normal = 'normal';
document.getElementById(listitem).className = (box.checked ? selected: normal);
};
html
<!DOCTYPE html>
<html>
<head>
<title>10th Mountain Division Hut Association</title>
<meta charset="UTF-8">
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<title>Google Maps Javascript API v3 Example: Marker Categories</title>
<link rel="stylesheet" href="css/foundation.css" />
<link rel="stylesheet" href="css/10thMtn2.css" />
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript" src="GXml.js"></script>
<script type="text/javascript" src="downloadxml.js"></script>
<script type="text/javascript" src="xmlToggle2.js"></script>
<title>Google Maps</title>
</head>
<body onload="initialize()">
<?php include('includes/header3.php'); ?>
<div id="map_canvas" style="width:65%; height:625px;"></div>
<div id="toggle_box">
<div id="routeLayers"></div>
<form action="#">
<img src="images/marker2_ltblue.png"> Huts: <input type="checkbox" id="hutsbox" onclick="boxclick(this,'huts')" />
<img src="images/marker2_orange.png"> Yurts: <input type="checkbox" id="yurtsbox" onclick="boxclick(this,'yurts')" />
</form>
<div id="hutsside_bar">
</div>
<div id="yurtsside_bar">
</div>
</div>
<div id="hutMapinfo"></div>
<?php include('includes/footer.php'); ?>
<noscript><b>JavaScript must be enabled in order for you to use Google Maps.</b>
However, it seems JavaScript is either disabled or not supported by your browser.
To view Google Maps, enable JavaScript by changing your browser options, and then
try again.
</noscript>
</body>
</html>
xml snippet
<?xml version="1.0" encoding="UTF-8"?>
<markers>
<marker lat="39.369804" lng="-106.388725" label="10th Mountain Division Hut" category="huts" season="winter">
<infowindow>
<![CDATA[
<div class="info">
<button class="tiny radius" id="closer">X</button>
<h5>10th Mountain Division Hut</h5>
<div class="hutMapTitle">
<img src="http://www.huts.org/images/10thMtn/10thMountainsmall.jpg"/>
<h6>10th Mountain Hut System</h6>
<h6>(970)925-5775</h6>
</div>
<div class="hutMapList">
<ul>
<li>10th Mtn Division Huts Website</li>
<li>Book This Hut</li>
<li><span class="subheading">Seasons:</span> Winter & Summer</li>
<li><span class="subheading">Price:</span> $33 per person</li>
<li><span class="subheading">Capacity:</span> 16 people</li>
<li><span class="subheading">Distance:</span> 4.4 miles</li>
<li><span class="subheading">Elevation Gain:</span> 1200ft
</ul>
</div>
<p>Nestled at timberline below the majestic peaks of the Colorado Continental Divide, 10th Mountain Division Hut forms a perfect destination for a single hut trip or ski-through using other nearby huts. In summer, dozens of hiking and cycling routes start or end just outside the door.</p></div>]]></infowindow>
</marker>
<marker lat="37.059971" lng="-106.480865" label="Trujillo Meadows Yurt" category="yurts">
<infowindow>
<![CDATA[
<div class="info">
<button class="tiny radius" id="closer">X</button>
<h5>Trujillo Meadows Yurt</h5>
<div class="hutMapTitle">
<img src="http://www.huts.org/images/GMaps/trujilloMeadowsYurt.jpg"/>
<h6>Southwest Nordic Center</h6>
<h6>(575)758-4761</h6>
</div>
<div class="hutMapList">
<ul>
<li>Southwest Nordic Website</li>
<li>Book This Hut</li>
<li><span class="subheading">Seasons:</span> Winter & Summer</li>
<li><span class="subheading">Price:</span> $125 per night</li>
<li><span class="subheading">Capacity:</span> 10 people</li>
<li><span class="subheading">Distance:</span> 4.1 miles</li>
<li><span class="subheading">Elevation Gain:</span> 380ft</li>
</ul>
</div>
<p>Located north Cumbres Pass in south central Colorado, the Trujillo Meadows Yurt is gentle open slopes out the front door of the yurt perfect for beginning and intermediate telemarkers. Advanced skiers will have fun looking for shots on the extensive north facing tree slopes. A full day loop is possible up to the Flat Mtn. ridge and back via the Los Pinos Creek.</p></div>]]></infowindow>
</marker>
</markers>
Your makeSidebar function has an issue (it is doing what you coded it to do, which is the behavior you are seeing):
function makeSidebar() {
var html = "";
for (var i=0; i<gmarkers.length; i++) {
if (gmarkers[i].getVisible()) {
html += '<a href="javascript:myclick(' + i + ')" onmouseover="gmarkers['+ i +'].setAnimation(google.maps.Animation.BOUNCE)" onmouseout="gmarkers['+ i +'].setAnimation(null)">' + gmarkers[i].myname + '<\/a><br>';
}
document.getElementById(gmarkers[i].mycategory+"side_bar").innerHTML = html;
}
}
If you want unique text for each "sidebar", you should make a unique version of "html" for each sidebar. Something like this:
var html = null;
function makeSidebar() {
// empty any pre-existing sidebar entries
for (i in html) {
document.getElementById(i+"side_bar").innerHTML = "";
}
html = []; // make html an array
for (var i=0; i<gmarkers.length; i++) {
if (gmarkers[i].getVisible()) {
// make entry for category if it doesn't already exist
if (!html[gmarkers[i].mycategory])
html[gmarkers[i].mycategory] = "";
// add the entry to the sidebar specific to the category
html[gmarkers[i].mycategory] += '<a href="javascript:myclick(' + i + ')" onmouseover="gmarkers['+ i +'].setAnimation(google.maps.Animation.BOUNCE)" onmouseout="gmarkers['+ i +'].setAnimation(null)">' + gmarkers[i].myname + '<\/a><br>';
}
}
for (i in html) {
document.getElementById(i+"side_bar").innerHTML = html[i];
}
}
working fiddle
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.