How to get the city names in respond with selected country? - google-maps-api-3

I need not get the city names in accordance with selected country.
I have dropdown list of countries from database.
By default users can select cities from the field i.e no restriction. But when they select country the result in cities should only get the cities of that country.
google.maps.event.addDomListener(window, 'load', intiGoogleLocation);
function intiGoogleLocation() {
var options = {
types: ['(cities)']
};
if (typeof country !== 'undefined') {
options.componentRestrictions = {country: country};
}
function fillInAddress() {
//some custom logic
}
var input = document.getElementById('cities');
var autocomplete = new google.maps.places.Autocomplete(input, options);
autocomplete.addListener('place_changed', fillInAddress);
}
So question is how do i reset the option so that i can set the country to options.componentRestrictions

Observe the change-event of the dropdown and set the componentRestrictions of the autocomplete to the desired value(based on the selected dropdown-item)
function intiGoogleLocation() {
function fillInAddress() {
//some custom logic
console.log('place-name:'+this.getPlace().name);
}
var list = document.getElementById('countries'),
input = document.getElementById('cities'),
autocomplete = new google.maps.places.Autocomplete(input, {
types: ['(cities)']
});
google.maps.event.addListener(autocomplete,'place_changed', fillInAddress);
google.maps.event.addDomListener(list,'change', function(e){
var componentRestrictions={};
if(this.value!==''){
componentRestrictions.country=this.value
}
autocomplete.setComponentRestrictions(componentRestrictions);
input.value='';
if(e){
autocomplete.set('place',{name:''});
}
});
google.maps.event.trigger(list,'change',null);
}
<select id="countries">
<option value="">any country</option>
<option value="de">Germany</option>
<option value="it">Italy</option>
<option value="fr">France</option>
<option value="gb">Great Britain</option>
</select>
<input id="cities"/>
<script src="https://maps.googleapis.com/maps/api/js?v=3&callback=intiGoogleLocation&libraries=places" async defer></script>

Related

WordPress with select2 and Toastr get previous selected value destroys select2 behavior

I am using WordPress and I have used Select2 and Toastr libraries successfully.
Basically I have a dropdown and if I change, Toastr will ask whether I need to update or not.
If I click on "Yes" then it will update and if I click on "No" then my dropdown should set previous value and nothing will happen.
Currently its selecting previous value but then if I open the same dropdown try to click on it to search then its saying "The results could not be loaded".
Here is my JS code what I have done so far.
var prevSubVarClientId;
jQuery('.mySubscription').select2({
allowClear: true,
placeholder: "",
//minimumInputLength: 3,
ajax: {
type: "POST",
url: '/wp-admin/admin-ajax.php',
dataType: 'json',
delay: 250, // delay in ms while typing when to perform a AJAX search
data: function (params, page) {
return {
action: 'list_posts',
q: params.term,
};
},
processResults: function( data ) {
var options = [];
if ( data ) {
jQuery.each( data, function( index, text ) {
options.push( { id: text['id'], text: text['name'] } );
});
}
return {
results: options
};
},
cache: true
}
});
jQuery('.mySubscription').on('select2:selecting', function (evt) {
prevSubVarClientId = jQuery('select').val();
});
jQuery('.mySubscription').change(function() {
var $this = jQuery(this);
jQuery(this).blur();
alertify.confirm("Are you sure you want to transfer?",
function(e){
var subscriptionId = jQuery($this).data("subscription-id");
var url = jQuery($this).data("ajax-url");
var userId = jQuery($this).val();
jQuery.ajax({
type: "POST",
url: url,
data : {
action : 'update_var_client_user_id',
userId : userId,
subscriptionId : subscriptionId
},
success: function(data)
{
var data = JSON.parse(data);
toastr["success"]("Transferred Successfully." );
}
});
},
function(){
jQuery($this).val(prevSubVarClientId);
jQuery($this).select2().trigger('change');
}).set({title:"Alert!!!"}).set({ labels:{ok:'Yes', cancel: 'No'} });
});
As you can see I have prevSubVarClientId variable and mySubscription dropdown with this class.
jQuery('.mySubscription').change(function() { here you can see I am opening alertify confirm box and if I click on "No" then I am doing below code.
jQuery($this).val(prevSubVarClientId);
jQuery($this).select2().trigger('change');
But then whenever I am trying to open the dropdown again, I am getting the below error.
Can some one guide me, what I am doing wrong here ?
Thanks
"The results could not be loaded". only show when return data is null or not found.
I tested your code below snippet and working fine.
$(".js-data-example-ajax").select2();
jQuery('.js-data-example-ajax').on('select2:selecting', function (evt) {
prevSubVarClientId = jQuery('select').val();
});
jQuery('.js-data-example-ajax').change(function() {
var $this = jQuery(this);
jQuery(this).blur();
alertify.confirm("Are you sure you want to transfer?",
function(e){
console.log('change');
},function(){
console.log('no change');
jQuery($this).val(prevSubVarClientId);
jQuery($this).select2().trigger('change');
}).set({title:"Alert!!!"}).set({ labels:{ok:'Yes', cancel: 'No'} });
});
.select2-container, .select2-container--open .select2-dropdown--below {
width: 200px !important;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/css/select2.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/js/select2.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/AlertifyJS/1.13.1/css/alertify.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/AlertifyJS/1.13.1/alertify.min.js"></script>
<select class="js-data-example-ajax">
<option value="abc">ABC</option>
<option value="bca" selected>BCA</option>
<option value="mnp">MNP</option>
<option value="pqr">PQR</option>
</select>

AngularJS only works if repeatedly refresh page

Here I try to fetch names and id's of trailers in trailer table into the multi-select. When the page loaded for the first time the data in select not appearing, but if I repeatedly refresh the page then data in multi-select will appear
Code of View
<body ng-app="movApp">
<select ng-controller="movList" ng-init="GetMovie()" class="selectpicker"
multiple data-live-search="true" id="opts" name="opts">
<option ng-repeat="x in Trailer" value={{x.trailerid}}>{{x.mov_name}}
</option>
</select>
</body>
Code in javascript
var app = angular.module('movApp', []);
app.controller('movList', function ($scope, $http) {
$scope.GetMovie = function () {
$http({
method: "get",
url: "/Ajaxx/GetFilm"
}).then(function (response) {
$scope.Trailer = response.data;
}, function () {
alert("Error");
})
};
})
code in controller
public ActionResult GetFilm()
{
return Json(db.Trailers.ToList(), JsonRequestBehavior.AllowGet);
}

Add 'See on Map' Link in Fusion Tables Map List View

I am using the wonderful Fusion Tables Map Template by Derek Eder. I have activated the results list as instructed by him here.
I would like to have a 'See on Map' link on each listing so that when i click on the link the page scrolls up to the map and opens an infowindow for that particular listing. You can see an example on the geo places theme.
Below is my code
HTML
<!DOCTYPE html>
<html lang='en'>
<head>
<link rel="stylesheet" href="bootstrap.spacelab.min.css"/>
<link rel="stylesheet" href="bootstrap-responsive.min.css"/>
<link rel="stylesheet" href="custom.css"/>
<!-- HTML5 shim, for IE6-8 support of HTML5 elements -->
</head>
<body>
<div class='navbar'>
<div class='navbar-inner'>
<div class='container'>
<a class='brand' href='/'>Worldwide Stores</a>
</div>
</div>
</div>
<div class='container-fluid'>
<div class='row-fluid'>
<div class='span4'>
<div class='well'>
<h4>
Address <small>(<a id='find_me' href='#'>find me</a>)</small>
</h4>
<input class='input-block-level' id='search_address' placeholder='Enter an address or an intersection' type='text' />
<label>
show companies within
<select class='input-small' id='search_radius'>
<option value='400'>2 blocks</option>
<option value='805'>1/2 mile</option>
<option value='1610'>1 mile</option>
<option value='3220'>2 miles</option>
<option value='8050'>5 miles</option>
<option value='16100'>10 miles</option>
<option value='40250'>25 miles</option>
<option value='80500'>50 miles</option>
<option value='161000'>100 miles</option>
<option value='402500'>250 miles</option>
<option value='805000'>500 miles</option>
<option value='1610000'>1000 miles</option>
</select>
</label>
<h5> Refine Your Search By:</h5>
<label>
<select id='select_type'>
<option value=''>All Categories</option>
<option value='Hotels'>Hotels</option>
<option value='Restaurants'>Restaurants</option>
<option value='Shopping Malls'>Shopping Malls</option>
<option value='Travel Agents'>Travel Agents</option>
</select>
</label>
<label>
<select disabled id='select_type1'>
<option value=''>Select Two</option>
<option value='male'>Male</option>
<option value='female'>Female</option>
</select>
</label>
<label>
<select disabled id='select_type2'>
<option value=''>Select Three</option>
<option value='Advanced Materials/Prd'>Advanced Materials/Prd</option>
<option value='Advertising Agencies'>Advertising Agencies</option>
<option value='Advertising Sales'>Advertising Sales</option>
<option value='Advertising Services'>Advertising Services</option>
</select>
</label>
<input class='btn btn-primary' id='search' type='button' value='Search' />
<button class='btn' id='reset'>Reset</button>
</div>
<p class='alert alert-info lead' id='result_count'></p>
</p> </p>
</p> </p>
</p> </p>
</div>
<div class='span8'>
<div id='map_canvas'></div>
<div class='well'>
<div id='results_list'></div>
</div>
</div>
</div>
</div>
<script type="text/javascript" src="source/jquery.js"></script>
<script type="text/javascript" src="source/bootstrap.js"></script>
<script type="text/javascript" src="source/jquery.address.min.js"></script>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false&libraries=places"></script>
<script type="text/javascript" src="source/jquery.geocomplete.min.js"></script>
<script type="text/javascript" src="maps_lib.js"></script>
<script type='text/javascript'>
//<![CDATA[
$(window).resize(function () {
var h = $(window).height(),
offsetTop = 90; // Calculate the top offset
$('#map_canvas').css('height', (h - offsetTop));
}).resize();
$(function() {
MapsLib.initialize();
$("#search_address").geocomplete();
$(':checkbox').click(function(){
MapsLib.doSearch();
});
$(':radio').click(function(){
MapsLib.doSearch();
});
$('#search_radius').change(function(){
MapsLib.doSearch();
});
$('#select_type').change(function(){
MapsLib.doSearch();
});
$('#select_type1').change(function(){
MapsLib.doSearch();
});
$('#select_type2').change(function(){
MapsLib.doSearch();
});
$('#search').click(function(){
MapsLib.doSearch();
});
$('#find_me').click(function(){
MapsLib.findMe();
return false;
});
$('#reset').click(function(){
$.address.parameter('address','');
MapsLib.initialize();
return false;
});
$(":text").keydown(function(e){
var key = e.keyCode ? e.keyCode : e.which;
if(key == 13) {
$('#search').click();
return false;
}
});
});
//]]>
</script>
</body>
</html>
maps_lib.js
/*!
* Searchable Map Template with Google Fusion Tables
* http://derekeder.com/searchable_map_template/
*
* Copyright 2012, Derek Eder
* Licensed under the MIT license.
* https://github.com/derekeder/FusionTable-Map-Template/wiki/License
*
* Date: 12/10/2012
*
*/
var MapsLib = MapsLib || {};
var MapsLib = {
//Setup section - put your Fusion Table details here
//Using the v1 Fusion Tables API. See https://developers.google.com/fusiontables/docs/v1/migration_guide for more info
//the encrypted Table ID of your Fusion Table (found under File => About)
//NOTE: numeric IDs will be deprecated soon
fusionTableId: "1f8rnajgS2iSVwwBR1NwXwImUuFB7VCpOg1-IfCs",
//*New Fusion Tables Requirement* API key. found at https://code.google.com/apis/console/
//*Important* this key is for demonstration purposes. please register your own.
googleApiKey: "API KEY",
//name of the location column in your Fusion Table.
//NOTE: if your location column name has spaces in it, surround it with single quotes
//example: locationColumn: "'my location'",
locationColumn: "Address",
map_centroid: new google.maps.LatLng(17,15), //center that your map defaults to
locationScope: "", //geographical area appended to all address searches
recordName: "Store", //for showing number of results
recordNamePlural: "Stores",
searchRadius: 805, //in meters ~ 1/2 mile
defaultZoom: 2, //zoom level when map is loaded (bigger is more zoomed in)
addrMarkerImage: 'http://derekeder.com/images/icons/blue-pushpin.png',
currentPinpoint: null,
initialize: function() {
$( "#result_count" ).html("");
geocoder = new google.maps.Geocoder();
var myOptions = {
zoom: MapsLib.defaultZoom,
center: MapsLib.map_centroid,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map($("#map_canvas")[0],myOptions);
// maintains map centerpoint for responsive design
google.maps.event.addDomListener(map, 'idle', function() {
MapsLib.calculateCenter();
});
google.maps.event.addDomListener(window, 'resize', function() {
map.setCenter(MapsLib.map_centroid);
});
MapsLib.searchrecords = null;
//reset filters
$("#search_address").val(MapsLib.convertToPlainString($.address.parameter('address')));
var loadRadius = MapsLib.convertToPlainString($.address.parameter('radius'));
if (loadRadius != "") $("#search_radius").val(loadRadius);
else $("#search_radius").val(MapsLib.searchRadius);
$(":checkbox").attr("checked", "checked");
$("#result_count").hide();
//-----custom initializers-------
//run the default search
MapsLib.doSearch();
},
doSearch: function(location) {
MapsLib.clearSearch();
var address = $("#search_address").val();
MapsLib.searchRadius = $("#search_radius").val();
var whereClause = MapsLib.locationColumn + " not equal to ''";
//-----custom filters-------
if ( $("#select_type").val() != "") {
whereClause += " AND 'Category' = '" + $("#select_type").val() + "'";
}
if ( $("#select_type1").val() != "") {
whereClause += " AND 'sex' = '" + $("#select_type1").val() + "'";
}
if ( $("#select_type2").val() != "") {
whereClause += " AND 'Subindustry' = '" + $("#select_type2").val() + "'";
}
//-------end of custom filters--------
if (address != "") {
if (address.toLowerCase().indexOf(MapsLib.locationScope) == -1)
address = address + " " + MapsLib.locationScope;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
MapsLib.currentPinpoint = results[0].geometry.location;
$.address.parameter('address', encodeURIComponent(address));
$.address.parameter('radius', encodeURIComponent(MapsLib.searchRadius));
map.setCenter(MapsLib.currentPinpoint);
map.setZoom(14);
if (MapsLib.searchRadius == "400")
map.setZoom(16);
else if (MapsLib.searchRadius == "805")
map.setZoom(15);
else if (MapsLib.searchRadius == "1610")
map.setZoom(14);
else if (MapsLib.searchRadius == "3220")
map.setZoom(13);
else if (MapsLib.searchRadius == "8050")
map.setZoom(12);
else if (MapsLib.searchRadius == "16100")
map.setZoom(11);
else if (MapsLib.searchRadius == "40250")
map.setZoom(09);
else if (MapsLib.searchRadius == "80500")
map.setZoom(08);
else if (MapsLib.searchRadius == "161000")
map.setZoom(07);
else if (MapsLib.searchRadius == "402500")
map.setZoom(06);
else if (MapsLib.searchRadius == "805000")
map.setZoom(05);
else if (MapsLib.searchRadius == "1610000")
map.setZoom(04);
else
map.setZoom(14);
MapsLib.addrMarker = new google.maps.Marker({
position: MapsLib.currentPinpoint,
map: map,
icon: MapsLib.addrMarkerImage,
animation: google.maps.Animation.DROP,
title:address
});
whereClause += " AND ST_INTERSECTS(" + MapsLib.locationColumn + ", CIRCLE(LATLNG" + MapsLib.currentPinpoint.toString() + "," + MapsLib.searchRadius + "))";
MapsLib.drawSearchRadiusCircle(MapsLib.currentPinpoint);
MapsLib.submitSearch(whereClause, map, MapsLib.currentPinpoint);
}
else {
alert("We could not find your address: " + status);
}
});
}
else { //search without geocoding callback
MapsLib.submitSearch(whereClause, map);
}
},
submitSearch: function(whereClause, map, location) {
//get using all filters
//NOTE: styleId and templateId are recently added attributes to load custom marker styles and info windows
//you can find your Ids inside the link generated by the 'Publish' option in Fusion Tables
//for more details, see https://developers.google.com/fusiontables/docs/v1/using#WorkingStyles
MapsLib.searchrecords = new google.maps.FusionTablesLayer({
query: {
from: MapsLib.fusionTableId,
select: MapsLib.locationColumn,
where: whereClause
},
styleId: 2,
templateId: 2
});
MapsLib.searchrecords.setMap(map);
MapsLib.getCount(whereClause);
MapsLib.getList(whereClause);
},
clearSearch: function() {
if (MapsLib.searchrecords != null)
MapsLib.searchrecords.setMap(null);
if (MapsLib.addrMarker != null)
MapsLib.addrMarker.setMap(null);
if (MapsLib.searchRadiusCircle != null)
MapsLib.searchRadiusCircle.setMap(null);
},
findMe: function() {
// Try W3C Geolocation (Preferred)
var foundLocation;
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
foundLocation = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
MapsLib.addrFromLatLng(foundLocation);
}, null);
}
else {
alert("Sorry, we could not find your location.");
}
},
addrFromLatLng: function(latLngPoint) {
geocoder.geocode({'latLng': latLngPoint}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
$('#search_address').val(results[1].formatted_address);
$('.hint').focus();
MapsLib.doSearch();
}
} else {
alert("Geocoder failed due to: " + status);
}
});
},
drawSearchRadiusCircle: function(point) {
var circleOptions = {
strokeColor: "#4b58a6",
strokeOpacity: 0.3,
strokeWeight: 1,
fillColor: "#4b58a6",
fillOpacity: 0.05,
map: map,
center: point,
clickable: false,
zIndex: -1,
radius: parseInt(MapsLib.searchRadius)
};
MapsLib.searchRadiusCircle = new google.maps.Circle(circleOptions);
},
query: function(selectColumns, whereClause, callback) {
var queryStr = [];
queryStr.push("SELECT " + selectColumns);
queryStr.push(" FROM " + MapsLib.fusionTableId);
queryStr.push(" WHERE " + whereClause);
var sql = encodeURIComponent(queryStr.join(" "));
$.ajax({url: "https://www.googleapis.com/fusiontables/v1/query?sql="+sql+"&callback="+callback+"&key="+MapsLib.googleApiKey, dataType: "jsonp"});
},
handleError: function(json) {
if (json["error"] != undefined) {
var error = json["error"]["errors"]
console.log("Error in Fusion Table call!");
for (var row in error) {
console.log(" Domain: " + error[row]["domain"]);
console.log(" Reason: " + error[row]["reason"]);
console.log(" Message: " + error[row]["message"]);
}
}
},
getCount: function(whereClause) {
var selectColumns = "Count()";
MapsLib.query(selectColumns, whereClause,"MapsLib.displaySearchCount");
},
displaySearchCount: function(json) {
MapsLib.handleError(json);
var numRows = 0;
if (json["rows"] != null)
numRows = json["rows"][0];
var name = MapsLib.recordNamePlural;
if (numRows == 1)
name = MapsLib.recordName;
$( "#result_count" ).fadeOut(function() {
$( "#result_count" ).html(MapsLib.addCommas(numRows) + " " + name + " found");
});
$( "#result_count" ).fadeIn();
},
getList: function(whereClause) {
var selectColumns = "StoreName, Address, Contact, Website";
MapsLib.query(selectColumns, whereClause, "MapsLib.displayList");
},
displayList: function(json) {
MapsLib.handleError(json);
var data = json["rows"];
var template = "";
var results = $("#results_list");
results.hide().empty(); //hide the existing list and empty it out first
if (data == null) {
//clear results list
results.append("<li><span class='lead'>No results found</span></li>");
}
else {
for (var row in data) {
template = "\
<div class='row-fluid item-list'>\
<div class='span12'>\
<span class='lead'>" + data[row][0] + "\</span>\
<br />\
" + data[row][4] + "\
<br />\
" + data[row][5] + "\
<br />\
<a href='" + data[row][6] + "'>\
<span>" + data[row][7] + "\</span>\
</a>\
<br />\
<a onClick=''>\
<span style='color: red;'>See on Map</span>\
</a>\
</div>\
</div>"
results.append(template);
}
}
results.fadeIn();
},
addCommas: function(nStr) {
nStr += '';
x = nStr.split('.');
x1 = x[0];
x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
return x1 + x2;
},
// maintains map centerpoint for responsive design
calculateCenter: function() {
center = map.getCenter();
},
//converts a slug or query string in to readable text
convertToPlainString: function(text) {
if (text == undefined) return '';
return decodeURIComponent(text);
}
//-----custom functions-------
// NOTE: if you add custom functions, make sure to append each one with a comma, except for the last one.
// This also applies to the convertToPlainString function above
//-----end of custom functions-------
}
it's not as easy as it seems.
The location of a feature(e.g. marker) on a FusionTableLayer isn't available until you really click on it(this click can't be simulated).
You can't get the LatLng of the feature with the query, because you've stored addresses and not LatLng's inside the FusionTable.
Although the API knows the LatLng's of the addresses, there is no way to access them.
So the only thing you may do is:
Take the address of the row
use google.maps.Geocoder to geocode this address
open a custom InfoWindow(content populated by the properties of the row) at the LatLng returned by the geocoder.
I'd rather add a comment to Dr.Molle's answer, but thanks to Stack Overflow's point system, I have to add an answer even though I don't think this will be truly useful because I can't be very specific. I'm assuming that's because the goal is to get me to answer questions, not just talk about answers ;)
Dr.Molle was on the right track, but invoking the geocoder on every click is not only painfully slow, but every IP only gets so many geocoder requests per day. So:
Create a column that has a unique identifier. Add a listener to the marker so that when clicked, it will query your table for that ID. When the results come in, create an InfoWindow (sorry, no help here) with the returned data.
Here's a sample that does exactly what you're asking for:
https://developers.google.com/fusiontables/docs/samples/change_infowindow_content

Multiple custom Streetview generation

I want to show another streetview pane on the screen.
I bound the "redraw()" function to the button onclick event.
The calling of redraw() function from the onclick event failed to draw another streetview.
When redraw() function is called in the initialize() function it works well.
Q1. Why does this redraw() fucnction behaves differently ?
Q2. How can I make it work as I wanted ?
<!DOCTYPE html>
<html>
<head>
<title>Google Maps JavaScript API v3 Example: Simple Custom StreetView</title>
<meta charset="utf-8">
<link href="/default.css" rel="stylesheet">
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script>
var tileSize, worldSize;
var panorama = null;
var panorama1 = null;
var panoOptions = null;
var panoOptions1 = null;
function initialize() {
// Set up Street View and initially set it visible. Register the
// custom panorama provider function. Set the StreetView to display
// the custom panorama 'reception' which we check for below.
panoOptions = {
pano: 'reception',
visible: true,
panoProvider: getCustomPanorama
};
tileSize = 1024;
worldSize = 1024;
panorama = new google.maps.StreetViewPanorama(
document.getElementById('pano_canvas'), panoOptions);
//redraw();
}
function redraw() {
// Set up Street View and initially set it visible. Register the
// custom panorama provider function. Set the StreetView to display
// the custom panorama 'reception' which we check for below.
tileSize = 1024;
worldSize = 1024;
panoOptions1 = {
pano: 'reception1',
visible: true,
panoProvider: getCustomPanorama1
};
panorama1 = new google.maps.StreetViewPanorama(
document.getElementById('pano_canvas1'), panoOptions1);
}
// Return a pano image given the panoID.
function getCustomPanoramaTileUrl(pano, zoom, tileX, tileY) {
// Note: robust custom panorama methods would require tiled pano data.
// Here we're just using a single tile, set to the tile size and equal
// to the pano "world" size.
return 'panoReception1024-0.jpg';
}
// Return a pano image given the panoID.
function getCustomPanoramaTileUrl1(pano, zoom, tileX, tileY) {
// Note: robust custom panorama methods would require tiled pano data.
// Here we're just using a single tile, set to the tile size and equal
// to the pano "world" size.
return 'panoReception1024-0.jpg';
}
// Construct the appropriate StreetViewPanoramaData given
// the passed pano IDs.
function getCustomPanorama(pano, zoom, tileX, tileY) {
if (pano == 'reception') {
return {
location: {
pano: 'reception',
description: 'Google Sydney - Reception'
},
links: [],
// The text for the copyright control.
copyright: 'Imagery (c) 2010 Google',
visible: true,
// The definition of the tiles for this panorama.
tiles: {
tileSize: new google.maps.Size(tileSize, 512),
worldSize: new google.maps.Size(worldSize, 512),
// The heading in degrees at the origin of the panorama
// tile set.
centerHeading: 105,
getTileUrl: getCustomPanoramaTileUrl
}
};
}
}
// Construct the appropriate StreetViewPanoramaData given
// the passed pano IDs.
function getCustomPanorama1(pano, zoom, tileX, tileY) {
if (pano == 'reception1') {
return {
location: {
pano: 'reception1',
description: 'Google Sydney - Reception'
},
links: [],
visible: true,
// The text for the copyright control.
copyright: 'Imagery (c) 2010 Google',
// The definition of the tiles for this panorama.
tiles: {
tileSize: new google.maps.Size(tileSize, 512),
worldSize: new google.maps.Size(worldSize, 512),
// The heading in degrees at the origin of the panorama
// tile set.
centerHeading: 105,
getTileUrl: getCustomPanoramaTileUrl1
}
};
}
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div>
<b>Tile Size: </b>
<select id="tileSize" >
<option value="256">256</option>
<option value="512">512</option>
<option value="768">768</option>
<option value="1024" selected>1024</option>
<option value="2048">2048</option>
</select>
<b>World Size: </b>
<select id="worldSize" >
<option value="256">256</option>
<option value="512">512</option>
<option value="768">768</option>
<option value="1024" selected>1024</option>
<option value="2048">2048</option>
</select>
<input type="button" value="Redraw" id="redraw" onclick="redraw()" />
</div>
<div id="pano_canvas" style="width: 500px; height: 380px"></div>
<div id="pano_canvas1" style="width: 500px; height: 380px"></div>
</body>
</html>
I found how to make it work but still am not sure why.
In the redraw() function, I added setPano() as below.
panorama1 = new google.maps.StreetViewPanorama(document.getElementById('pano_canvas1'), panoOptions1);
panorama1.setPano('reception1');
Then the redraw() function worked as expected.
Without that, the custom panoProvider function was not called.
I suppose setPano calls the custom panoProvider function internally.

Trying to deal XML with Ajax

I Wrote a code that takes a generates XML file from Harvard Uni, and put it in a dropdown, next you can choose a course from the list and it will generates a table with the course details.
<script type="text/javascript" src="Script/jquery-1.7.2.js"></script>
<script type="text/javascript">
$('#button').click(function () {
document.getElementById("span").style.visibility = "visible";
document.getElementById("button").style.visibility = "hidden";
$.ajax({
type: "GET",
url: "Harvard.aspx?field=COMPSCI",
success: function (data) {
var courses = data.documentElement.getElementsByTagName("Course");
var options = document.createElement("select");
$(options).change(function () {
ShowCourseDetails(this);
});
for (var i = 0; i < courses.length; i++) {
var option = document.createElement("option");
option.value = $(courses[i]).find("cat_num").text();
option.text = $(courses[i]).find("title").text();
options.add(option, null);
}
document.getElementById("selectDiv").appendChild(options);
document.getElementById("span").style.visibility = "hidden";
}
});
});
function ShowCourseDetails(event) {
// get the index of the selected option
var idx = event.selectedIndex;
// get the value of the selected option
var cat_num = event.options[idx].value;
$.ajax({
type: "GET",
url: "http://courses.cs50.net/api/1.0/courses?output=xml&&cat_num=" + cat_num,
success: function (data) {
$("#TableDiv").html(ConvertToTable(data.documentElement));
}
});
}
function ConvertToTable(targetNode) {
targetNode = targetNode.childNodes[0];
// first we need to create headers
var columnCount = 2;
var rowCount = targetNode.childNodes.length
// name for the table
var myTable = document.createElement("table");
for (var i = 0; i < rowCount; i++) {
var newRow = myTable.insertRow();
var firstCell = newRow.insertCell();
firstCell.innerHTML = targetNode.childNodes[i].nodeName;
var secondCell = newRow.insertCell();
secondCell.innerHTML = targetNode.childNodes[i].text;
}
// i prefer to send it as string instead of a table object
return myTable.outerHTML;
}
</script>
and the body:
<div id="main">
<div class="left">
<input id="button" type="button" value="Get all science courses from HARVARD"/>
<br />
<span id="span" style="visibility: hidden">Downloading courses from harvard....</span>
<div id="selectDiv"></div>
<div id="TableDiv"></div>
</div>
</div>
and What I get in the dropdown is only "undefined" on all the rows in the dropdown, can someone can see the problem with the code I wrote?
10x alot in advance :)
Working jsFiddle: http://jsfiddle.net/3kXZh/44/
Well, I found a couple of issues..
First, I'd stay away from setting "onclick" in the HTML. You want to separate your action layer from your content layer.
Since you're using jQuery anyway, try this:
$('#button').click(function() {
/* function loadXMLDoc contents should go here */
});
And change:
<input id="button" type="button" onclick="loadXMLDoc()" value="Get all sci..."/>
To:
<input id="button" type="button" value="Get all sci..." />
To solve your immediate problem in the JavaScript, change the loadXMLDoc function from this:
option.value = courses[i].getElementsByTagName("cat_num")[0].text;
option.text = courses[i].getElementsByTagName("title")[0].text;
to this:
option.value = $(courses[i]).find("cat_num").text();
option.text = $(courses[i]).find("title").text();
That should be enough to get you on to creating your tables from there.

Resources