I created a map using Fusion Tables today, and I'm about 90% of where I need to be, but I'm totally stuck on enabling the mouseover event on my map. Basically I want the county name to appear as one hovers over the map. I've taken the sample code from here:
http://gmaps-utility-gis.googlecode.com/svn/trunk/fusiontips/docs/examples.html
I think I've filled in the required info correctly. I generated the HTML/JS map automatically from Fusion Tables. Here's my live map: http://www.casalett.net/map/map.html
Any and all help would be appreciated!
Here's the code:
<script type="text/javascript" src="https://maps.google.com/maps/api/js?sensor=false&v=3"></script>
<script src="js/fusiontipsV1.js" type="text/javascript"></script>
<script type="text/javascript">
function initialize() {
google.maps.visualRefresh = true;
var isMobile = (navigator.userAgent.toLowerCase().indexOf('android') > -1) ||
(navigator.userAgent.match(/(iPod|iPhone|iPad|BlackBerry|Windows Phone|iemobile)/));
if (isMobile) {
var viewport = document.querySelector("meta[name=viewport]");
viewport.setAttribute('content', 'initial-scale=1.0, user-scalable=no');
}
var mapDiv = document.getElementById('googft-mapCanvas');
//mapDiv.style.width = isMobile ? '100%' : '1000px';
//mapDiv.style.height = isMobile ? '100%' : '400px';
var map = new google.maps.Map(mapDiv, {
center: new google.maps.LatLng(35.196111, -79.464167),
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
map.controls[google.maps.ControlPosition.RIGHT_BOTTOM].push(document.getElementById('googft-legend-open'));
map.controls[google.maps.ControlPosition.RIGHT_BOTTOM].push(document.getElementById('googft-legend'));
layer = new google.maps.FusionTablesLayer({
map: map,
heatmap: { enabled: false },
query: {
select: "col4\x3e\x3e0",
from: "1ohK_Kmh7JbNZH1nC7NM-1MjhVf8OBzCJrxmbC0tq",
where: ""
},
options: {
styleId: 2,
templateId: 2
}
});
// This is the only section I added myself from the example page
layer.enableMapTips({
select: "'County Name'", // list of columns to query, typially need only one column.
from: "1ohK_Kmh7JbNZH1nC7NM-1MjhVf8OBzCJrxmbC0tq", // fusion table name
geometryColumn: 'gemoetry', // geometry column name
suppressMapTips: false, // optional, whether to show map tips. default false
delay: 200, // milliseconds mouse pause before send a server query. default 300.
tolerance: 8 // tolerance in pixel around mouse. default is 6.
});
//listen to events if desired.
google.maps.event.addListener(layer, 'mouseover', function(fEvent) {
var row = fEvent.row;
myHtml = 'mouseover:<br/>';
for (var x in row) {
if (row.hasOwnProperty(x)) {
myHtml += '<b>' + x + "</b>:" + row[x].value + "<br/>";
}
}
document.getElementById('info').innerHTML = myHtml;
});
google.maps.event.addListener(layer, 'mouseout', function(fevt) {
document.getElementById('info').innerHTML = '';
});
// Section I added myself ends here
if (isMobile) {
var legend = document.getElementById('googft-legend');
var legendOpenButton = document.getElementById('googft-legend-open');
var legendCloseButton = document.getElementById('googft-legend-close');
legend.style.display = 'none';
legendOpenButton.style.display = 'block';
legendCloseButton.style.display = 'block';
legendOpenButton.onclick = function() {
legend.style.display = 'block';
legendOpenButton.style.display = 'none';
}
legendCloseButton.onclick = function() {
legend.style.display = 'none';
legendOpenButton.style.display = 'block';
}
}
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
You need to include your apiConsoleKey valid for the domain your page is on, like the example at:
http://gmaps-utility-gis.googlecode.com/svn/trunk/fusiontips/examples/fusiontips.html
// authentication required, either API key or OAuth 2.0 token
// replace with a key valid for your domain
var apiConsoleKey = "AIzaSyA47jXARydzK61yX18t4oPpy6xUZDBukiY"; // valid for this question on stackoverflow.com, http://stac
// var apiConsoleKey = "AIzaSyAfravxKsLG5RItI93Dyh3Nya8Dg7vfYsk"; // valid for gmaps-utility-gis.googlecode.com domain only.
// var apiConsoleKey = "AIzaSyCxitB5jQcw7weQdg9MqBRfxr6mj81wT7I"; // valid for geocodezip.com
var map, layer;
function loadPoint() {
if (layer != null) {
layer.setMap(null);
google.maps.event.clearInstanceListeners(layer);
}
// original numeric ID 297050; Fusion Tables API v1.0 requires encrypted IDs.
var tableid = '15UY2pgiz8sRkq37p2TaJd64U7M_2HDVqHT3Quw';
layer = new google.maps.FusionTablesLayer({
query: {
select: 'Address',
from: tableid
},
map: map
});
layer.enableMapTips({
// authentication required, either API key or OAuth 2.0 token
key: apiConsoleKey, // replace with a key valid for your domain.
select: "'Store Name','Address'", // list of columns to query, typially need only one column.
from: tableid, // fusion table name
geometryColumn: 'Address', // geometry column name
suppressMapTips: false, // optional, whether to show map tips. default false
delay: 200, // milliseconds mouse pause before send a server query. default 300.
tolerance: 8 // tolerance in pixel around mouse. default is 6.
});
map.setCenter(new google.maps.LatLng(37.4, -122.1));
map.setZoom(10);
addListeners();
google.maps.event.addListener(layer, 'click', function(me) {
me.infoWindowHtml = me.infoWindowHtml + "<a href='javascript:void'>Test</a>";
});
}
function loadLine() {
if (layer != null) {
layer.setMap(null);
google.maps.event.clearInstanceListeners(layer);
}
// original numeric ID 296374; Fusion Tables API v1.0 requires encrypted IDs.
var tableid = '1xo_sVz4108NNejzUCGp_2nJIoOltKi467LYbHg';
layer = new google.maps.FusionTablesLayer({
query: {
select: 'geometry',
from: tableid
},
map: map
});
layer.enableMapTips({
// authentication required, either API key or OAuth 2.0 token
key: apiConsoleKey, // replace with a key valid for your domain.
select: "description", // list of columns to query, typially need only one column.
from: tableid, // fusion table name
geometryColumn: 'geometry', // geometry column name
suppressMapTips: false, // optional, whether to show map tips. default false
delay: 200, // milliseconds mouse pause before send a server query. default 300.
tolerance: 4 // tolerance in pixel around mouse. default is 6.
});
map.setCenter(new google.maps.LatLng(50.46, -104.6));
map.setZoom(12);
addListeners();
}
function loadPoly() {
if (layer != null) {
layer.setMap(null);
google.maps.event.clearInstanceListeners(layer);
}
// original numeric ID 1670859; Fusion Tables API v1.0 requires encrypted IDs.
var tableid = '18Vjqv451aikVXxlnGKhVEIJ0y4l18ZQ86eReE68';
layer = new google.maps.FusionTablesLayer({
query: {
select: 'geometry_simplified',
from: tableid
},
map: map
});
layer.enableMapTips({
// authentication required, either API key or OAuth 2.0 token
key: apiConsoleKey, // replace with a key valid for your domain.
select: "'NAME'", // list of columns to query, typially need only one column.
from: tableid, // fusion table name
geometryColumn: 'geometry_simplified', // geometry column name
suppressMapTips: false, // optional, whether to show map tips. default false
delay: 100, // milliseconds mouse pause before send a server query. default 300.
tolerance: 1 // tolerance in pixel around mouse. default is 6.
});
map.setCenter(new google.maps.LatLng(38.3, -95.4));
map.setZoom(4);
addListeners();
}
function addListeners() {
google.maps.event.addListener(layer, 'mouseover', function(fEvent) {
var row = fEvent.row;
myHtml = 'mouseover:<br/>';
for (var x in row) {
if (row.hasOwnProperty(x)) {
myHtml += '<b>' + x + "</b>:" + row[x].value + "<br/>";
}
}
document.getElementById('info').innerHTML = myHtml;
});
google.maps.event.addListener(layer, 'mouseout', function(fevt) {
document.getElementById('info').innerHTML = '';
});
}
function initialize() {
map = new google.maps.Map(document.getElementById('map_canvas'), {
center: new google.maps.LatLng(37.4, -122.1),
zoom: 10,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
loadPoly();
}
google.maps.event.addDomListener(window, 'load', initialize);
body {
font-family: Arial, sans-serif;
}
body,
html {
width: 100%;
}
#map_canvas {
height: 500px;
width: 100%;
}
<script src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script src="http://gmaps-utility-gis.googlecode.com/svn/trunk/fusiontips/src/fusiontips.js"></script>
<div>
Move mouse over a fusion table feature and pause a while (configurable, default < 0.5 sec), a map tip will display. (documentation)
</div>
<div id='map_canvas'>
</div>
<div id='info'>
</div>
A code snippet using your table and my key:
function initialize() {
google.maps.visualRefresh = true;
var isMobile = (navigator.userAgent.toLowerCase().indexOf('android') > -1) ||
(navigator.userAgent.match(/(iPod|iPhone|iPad|BlackBerry|Windows Phone|iemobile)/));
if (isMobile) {
var viewport = document.querySelector("meta[name=viewport]");
viewport.setAttribute('content', 'initial-scale=1.0, user-scalable=no');
}
var mapDiv = document.getElementById('googft-mapCanvas');
//mapDiv.style.width = isMobile ? '100%' : '1000px';
//mapDiv.style.height = isMobile ? '100%' : '400px';
var map = new google.maps.Map(mapDiv, {
center: new google.maps.LatLng(35.196111, -79.464167),
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
map.controls[google.maps.ControlPosition.RIGHT_BOTTOM].push(document.getElementById('googft-legend-open'));
map.controls[google.maps.ControlPosition.RIGHT_BOTTOM].push(document.getElementById('googft-legend'));
layer = new google.maps.FusionTablesLayer({
map: map,
heatmap: {
enabled: false
},
query: {
select: "col4\x3e\x3e0",
from: "1ohK_Kmh7JbNZH1nC7NM-1MjhVf8OBzCJrxmbC0tq",
where: ""
},
options: {
styleId: 2,
templateId: 2
}
});
var apiConsoleKey = "AIzaSyA47jXARydzK61yX18t4oPpy6xUZDBukiY"; // valid for this question on stackoverflow.com, http://stacksnippets.net
layer.enableMapTips({
// authentication required, either API key or OAuth 2.0 token
key: apiConsoleKey, // replace with a key valid for your domain.
select: "'County Name'", // list of columns to query, typially need only one column.
from: "1ohK_Kmh7JbNZH1nC7NM-1MjhVf8OBzCJrxmbC0tq", // fusion table name
geometryColumn: 'gemoetry', // geometry column name
suppressMapTips: false, // optional, whether to show map tips. default false
delay: 200, // milliseconds mouse pause before send a server query. default 300.
tolerance: 8 // tolerance in pixel around mouse. default is 6.
});
//listen to events if desired.
google.maps.event.addListener(layer, 'mouseover', function(fEvent) {
var row = fEvent.row;
myHtml = 'mouseover:<br/>';
for (var x in row) {
if (row.hasOwnProperty(x)) {
myHtml += '<b>' + x + "</b>:" + row[x].value + "<br/>";
}
}
document.getElementById('info').innerHTML = myHtml;
});
google.maps.event.addListener(layer, 'mouseout', function(fevt) {
document.getElementById('info').innerHTML = '';
});
if (isMobile) {
var legend = document.getElementById('googft-legend');
var legendOpenButton = document.getElementById('googft-legend-open');
var legendCloseButton = document.getElementById('googft-legend-close');
legend.style.display = 'none';
legendOpenButton.style.display = 'block';
legendCloseButton.style.display = 'block';
legendOpenButton.onclick = function() {
legend.style.display = 'block';
legendOpenButton.style.display = 'none';
}
legendCloseButton.onclick = function() {
legend.style.display = 'none';
legendOpenButton.style.display = 'block';
}
}
}
google.maps.event.addDomListener(window, 'load', initialize);
html,
body {
margin: 0;
padding: 0;
font-family: Verdana, Geneva, sans-serif;
font-size: 18px;
}
#googft-mapCanvas {
min-height: 700px;
margin: 0 auto;
padding: 0;
width: 100%;
}
#media screen and (max-width: 780px) {
#googft-mapCanvas {
min-height: 400px;
}
}
#media screen and (max-width: 480px) {
#googft-mapCanvas {
min-height: 400px;
}
}
<script src="https://maps.google.com/maps/api/js?sensor=false&v=3"></script>
<script src="http://gmaps-utility-gis.googlecode.com/svn/trunk/fusiontips/src/fusiontips.js"></script>
<h1 style="text-align: center;">Counties in NC</h1>
<div id="googft-mapCanvas"></div>
<div style="width: 700px; margin: 100px auto;">
<section id="anchor-1">
<h3>Alamance County</h3>
<p><strong>Really good quote</strong>
</p>
<p>The default automatic template shows the data from the first 10 columns. Check or uncheck the box next to the column name to include it in the automatic info window.Any format applied to the data in the column will show here. For example, if a column
contains URLs to images and the format "Four line image" has been applied in the Edit > Change columns dialog, the image will be displayed in both the table and the info window.
</p>
</section>
<section id="anchor-2">
<h3>Alexander County</h3>
<p><strong>Really good quote</strong>
</p>
<p>The default automatic template shows the data from the first 10 columns. Check or uncheck the box next to the column name to include it in the automatic info window.Any format applied to the data in the column will show here. For example, if a column
contains URLs to images and the format "Four line image" has been applied in the Edit > Change columns dialog, the image will be displayed in both the table and the info window.
</p>
</section>
<section id="anchor-3">
<h3>Alleghany County</h3>
<p><strong>Really good quote</strong>
</p>
<p>The default automatic template shows the data from the first 10 columns. Check or uncheck the box next to the column name to include it in the automatic info window.Any format applied to the data in the column will show here. For example, if a column
contains URLs to images and the format "Four line image" has been applied in the Edit > Change columns dialog, the image will be displayed in both the table and the info window.
</p>
</section>
<section id="anchor-4">
<h3>Anson County</h3>
<p><strong>Really good quote</strong>
</p>
<p>The default automatic template shows the data from the first 10 columns. Check or uncheck the box next to the column name to include it in the automatic info window.Any format applied to the data in the column will show here. For example, if a column
contains URLs to images and the format "Four line image" has been applied in the Edit > Change columns dialog, the image will be displayed in both the table and the info window.
</p>
</section>
Related
I'm simply trying to replace the lat long coords to use the browsers geolocation yet I'm getting no result...
Code for the geolocation is;
<script> var coords = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
function initAutocomplete() {
var map = new google.maps.Map(document.getElementById('map'), {
center: coords,
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
The rest of the code points to the simple places api service;
// Create the search box and link it to the UI element.
var input = document.getElementById('pac-input');
var searchBox = new google.maps.places.SearchBox(input);
map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
// Bias the SearchBox results towards current map's viewport.
map.addListener('bounds_changed', function() {
searchBox.setBounds(map.getBounds());
});
var markers = [];
// Listen for the event fired when the user selects a prediction and retrieve
// more details for that place.
searchBox.addListener('places_changed', function() {
var places = searchBox.getPlaces();
if (places.length == 0) {
return;
}
// Clear out the old markers.
markers.forEach(function(marker) {
marker.setMap(null);
});
markers = [];
// Create a marker for each place.
markers.push(new google.maps.Marker({
map: map,
icon: icon,
title: place.name,
position: place.geometry.location
}));
if (place.geometry.viewport) {
// Only geocodes have viewport.
bounds.union(place.geometry.viewport);
} else {
bounds.extend(place.geometry.location);
}
});
map.fitBounds(bounds);
});
}
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(success);
} else {
error('Geo Location is not supported');
}
</script>
I cannot for the life of me find any reliable tutorials on-line...
I am unable to get region name from code of region. My region click event work fine and I also get code properly. My code is:
<div id="map" style="width: 600px; height: 400px"></div>
<script type="text/javascript">
$(function () {
new jvm.MultiMap({
container: $('#map'),
maxLevel: 1,
main: {
map: 'us_lcc_en'
},
mapUrlByCode: function (code, multiMap) {
return 'js/counties/jquery-jvectormap-data-' +
code.toLowerCase() + '-' +
multiMap.defaultProjection + '-en.js';
}
});
$('#map').bind('regionClick.jvectormap', function (event, code) {
var map = $('#map').vectorMap('get', 'mapObject');
alert(map.getRegionName(code));
});
});
</script>
HTML CODE
<div id="map2" style="width: 100%; height: 400px"></div>
Jquery Code
$('#map2').vectorMap({
map: 'world_mill_en',
series: {
regions: [{
scale: ['#C8EEFF', '#0071A4'],
normalizeFunction: 'polynomial',
values: gdpData
}]
},
onRegionClick: function (event, code) {
******* Code To Show Region Name *******
/* Here We are getting Map Object */
var map=$('#map2').vectorMap('get', 'mapObject');
/* Here Using Map Object we are using Inbuilt GetRegionName
function TO Get Regionname for a region Code */
var regionName = map.getRegionName(code);
console.log("Code: "+code+"<br/>");
console.log("Region Name: "+regionName+"<br/>");
******* Code To Show Region Name *******
}
});
I could not figure out how to get the region name from the onRegionClick for a multi map. This is my hack to get what is needed.
var drillDownUSMap;
var stateCode;
var countyName;
$(document).ready(function () {
drillDownUSMap = new jvm.MultiMap({
container: $('#map'),
maxLevel: 1,
main: {
map: 'us_lcc_en',
onRegionClick: function (e, code) {
var map = $('#map div').vectorMap('get', 'mapObject');
var regionName = map.getRegionName(code);
stateCode = code.toLowerCase();
console.log(regionName)
}
},
mapUrlByCode: function (code, multiMap) {
return 'js/counties/jquery-jvectormap-data-' +
code.toLowerCase() + '-' +
multiMap.defaultProjection + '-en.js';
},
mapNameByCode: function (code, multiMap) {
return code.toLowerCase() + '_' +
multiMap.defaultProjection + '_en';
}
});
$(document).on('click', '.jvectormap-region.jvectormap-element', function (evt) {
var regionElem = $(this);
var stateJSFileName = stateCode + "_" + drillDownUSMap.defaultProjection + "_en";
var regionCode = regionElem.attr('data-code');
if (drillDownUSMap.maps[stateJSFileName]) {
countyName = drillDownUSMap.maps[stateJSFileName].regions[regionCode].config.name;
if (regionElem.hasClass("selected-region")) {
regionElem.removeClass("selected-region");
} else {
regionElem.addClass("selected-region");
}
}
});
});
Add this code
onRegionClick:function(event, code) {
var name = (code);
alert(name);
}
All Script Like This
<div id="map" style="width: 600px; height: 400px"></div>
<script type="text/javascript">
$(function () {
new jvm.MultiMap({
container: $('#map'),
maxLevel: 1,
main: {
map: 'us_lcc_en'
},
mapUrlByCode: function (code, multiMap) {
return 'js/counties/jquery-jvectormap-data-' +
code.toLowerCase() + '-' +
multiMap.defaultProjection + '-en.js';
}
});
onRegionClick:function(event, code) {
var name = (code);
alert(name);
}
});
</script>
I want to access and view public Youtube videos (simple read only) from any Youtube channel without resorting to Oauth, just with plain API key. I haven't found a decent layman example on how to go about with API v3 ;-(
I have this to juggle with which I cannot get to work. Basically, a Select menu contains options whose values are existing channel IDs. When an option containing a channel ID is selected, it should trigger requestUserUploadsPlaylistId(). Then, when NEXTbutton or PREVIOUSbutton are activated, function requestVideoPlaylist() would kick in. Is there a better way to do this? I get the following error messages in Firebug:
TypeError: response.result is undefined (When I choose an option from SELECTmenu).
TypeError: response.result is undefined (After I click on buttons).
Here is what I am struggling with (am new to API v3 and kinda used to API v2 (sigh)):
<HTML is here>
script>
$('#NEXTbutton').prop('disabled', true).addClass('disabled');
</script>
<script type="text/javascript" src="https://apis.google.com
/js/client.js?onload=onJSClientLoad"></script>
<script>
var dd, playlistId, nextPageToken, prevPageToken;
function onJSClientLoad() {
gapi.client.setApiKey('YOUR-API-KEY');
gapi.client.load('youtube', 'v3', function(){
$('#NEXTbutton').prop('disabled', false).removeClass('disabled');
});
}
// Calling the following function via selected option value of select menu
// I am using "mine: false," since it's an unauthenticated request ??
function requestUserUploadsPlaylistId() {
var dd = $("#SELECTmenu option:selected").val();
var request = gapi.client.youtube.channels.list({
mine: false, // is this legit?
channelId: dd, // Variable is preset chosen value of SELECTmenu options
part: 'contentDetails,id'
});
request.execute(function(response) {
playlistId = response.result.items[0].contentDetails.relatedPlaylists.uploads;
channelId = response.result.items[0].id;
});
}
function requestVideoPlaylist(playlistId, pageToken) {
var requestOptions = {
playlistId: playlistId,
part: 'snippet,id',
maxResults: 5
};
if (pageToken) {
requestOptions.pageToken = pageToken;
}
var request = gapi.client.youtube.playlistItems.list(requestOptions);
request.execute(function(response) {
// Only show the page buttons if there's a next or previous page.
nextPageToken = response.result.nextPageToken;
var nextVis = nextPageToken ? 'visible' : 'hidden';
$('#NEXTbutton').css('visibility', nextVis);
prevPageToken = response.result.prevPageToken
var prevVis = prevPageToken ? 'visible' : 'hidden';
$('#PREVIOUSbutton').css('visibility', prevVis);
var playlistItems = response.result.items;
if (playlistItems) {
$.each(playlistItems, function(index, item) {
displayResult(item.snippet);
});
} else {
$('#CONTAINER').html('Sorry, no uploaded videos available');
}
});
}
function displayResult(videoSnippet) {
for(var i=0;i<response.items.length;i++) {
var channelTitle = response.items[i].snippet.channelTitle
var videoTitle = response.items[i].snippet.title;
var Thumbnail = response.items[i].snippet.thumbnails.medium.url;
var results = '<li><div class="video-result"><img src="'+Thumbnail+'" /></div>
<div class="chantitle">'+channelTitle+'</div>
<div class="vidtitle">'+videoTitle+'</div></li>';
$('#CONTAINER').append(results);
}
}
function nextPage() {
requestVideoPlaylist(playlistId, nextPageToken);
}
function previousPage() {
requestVideoPlaylist(playlistId, prevPageToken);
}
$('#NEXTbutton').on('click', function() { // Display next 5 results
nextPage();
});
$('#PREVIOUSbutton').on('click', function() { // Display previous 5 results
previousPage();
});
$("#SELECTmenu").on("change", function() {
$('#CONTAINER').empty();
if ($("#SELECTmenu option:selected").val().length === 24) { //Channel ID length
requestUserUploadsPlaylistId();
} else {
return false;
}
});
I'm surely missing something here, any pointers will be greatly appreciated.
FINAL UPDATE
A few updates later and I've finally answered my question after playing with the awesome Google APIs Explorer tool. Here is a sample working code allowing access to Youtube channel video-related data from a Select menu for read-only without using OAUTH, just an API key. The Select menu, based on a selected option's value (which contains a channel id), posts a video thumbnail, the thumbnail's channel origin; and the video's title. Should be easy to make the thumbnail clickable so as to load video in iframe embed or redirect to Youtube page. Enjoy!
// Change values and titles accordingly
<select id="SELECTmenu">
<option value="selchan">Select channel ...</option>
<option value="-YOUR-24digit-ChannelID-">Put-channel-title-here</option>
<option value="-YOUR-24digit-ChannelID-">Put-channel-title-here</option>
</select>
<button id="NEXTbutton">NEXT</button>
<button id="PREVIOUSbutton">PREV</button>
<ol id="CONTAINER"></ol> // Loads video data response
<script type="text/javascript"
src="https://apis.google.com/js/client.js?onload=onJSClientLoad">
</script>
var playlistId, nextPageToken, prevPageToken;
function onJSClientLoad() {
gapi.client.setApiKey('INSERT-YOUR-API-KEY'); // Insert your API key
gapi.client.load('youtube', 'v3', function(){
//Add function here if some action required immediately after the API loads
});
}
function requestUserUploadsPlaylistId(pageToken) {
// https://developers.google.com/youtube/v3/docs/channels/list
var selchan = $("#SELECTmenu option:selected").val();
var request = gapi.client.youtube.channels.list({
id: selchan,
part: 'snippet,contentDetails',
filter: 'uploads'
});
request.execute(function(response) {
playlistId = response.result.items[0].contentDetails.relatedPlaylists.uploads;
channelId = response.result.items[0].id;
requestVideoPlaylist(playlistId, pageToken);
});
}
function requestVideoPlaylist(playlistId, pageToken) {
$('#CONTAINER').empty();
var requestOptions = {
playlistId: playlistId,
part: 'snippet,id',
maxResults: 5 // can be changed
};
if (pageToken) {
requestOptions.pageToken = pageToken;
}
var request = gapi.client.youtube.playlistItems.list(requestOptions);
request.execute(function(response) {
// Only show the page buttons if there's a next or previous page.
nextPageToken = response.result.nextPageToken;
var nextVis = nextPageToken ? 'visible' : 'hidden';
$('#NEXTbutton').css('visibility', nextVis);
prevPageToken = response.result.prevPageToken
var prevVis = prevPageToken ? 'visible' : 'hidden';
$('#PREVIOUSbutton').css('visibility', prevVis);
var playlistItems = response.result.items;
if (playlistItems) {
displayResult(playlistItems);
} else {
$('#CONTAINER').html('Sorry, no uploaded videos.');
}
});
}
function displayResult(playlistItems) {
for(var i=0;i<playlistItems.length;i++) {
var channelTitle = playlistItems[i].snippet.channelTitle
var videoTitle = playlistItems[i].snippet.title;
var videoThumbnail = playlistItems[i].snippet.thumbnails.medium.url;
var results = '<li>
<div>'+channelTitle+'</div>
<div><img src="'+videoThumbnail+'" /></div>
<div>'+videoTitle+'</div>
</li>';
$('#CONTAINER').append(results);
}
}
function nextPage() {
$('#CONTAINER').empty(); // This needed here
requestVideoPlaylist(playlistId, nextPageToken);
}
function previousPage() {
$('#CONTAINER').empty(); // This needed here
requestVideoPlaylist(playlistId, prevPageToken);
}
$('#NEXTbutton').on('click', function() { // Display next maxResults
nextPage();
});
$('#PREVIOUSbutton').on('click', function() { // Display previous maxResults
previousPage();
});
// Using as filtering example Select option values which contain channel
// ID length of 24 alphanumerics/symbols to trigger functions just in case
// there are other option values in the menu that do not refer to channel IDs.
$("#SELECTmenu").on("change", function() {
$('#CONTAINER').empty();
if ($("#SELECTmenu option:selected").val().length === 24) {
requestUserUploadsPlaylistId();
return false;
} else {
return false;
}
});
NOTE:
Remember, code sample above is built based on what API v3 provided at the time of this posting.
TIP: It's better to make sure that the buttons be disabled during API call and re-enabled after API has posted the expected results. If you press those buttons while processing, you may get compounded and/or unexpected results. ~ Koolness
I would like to pass an array in my plugin defaults config settings. I am trying to give the user, the option to add as many title and src variable as they like for instance:
desktop_xl: {
"title":"beach",
"src":"http://images.smh.com.au/2013/02/25/4061249/art-Whitehaven-Beach-620x349.jpg"
},
{
"title":"sunset",
"src":"https://lh5.googleusercontent.com/-Oh0HlfM31BQ/TlXHejUNpeI/AAAAAAAABiI/tQbJJEGEOnU/s400/red_sunset_beach.jpg"
}
I have seen this question on stack overflow but could not find an answer that works for me.
I did some reading and figured out that I can create an array of objects, it works well only on my index.html page as per the below fiddle, http://jsfiddle.net/michelm/7gS6g/2/
The issue is that I would like to use this array as a config option in my plugin so users can add as many title and src variables as they need, but the array does not work inside the plugin.
When I did console.log(desktop_xl); on my index.html page, it shows as an object.
I read the documentation at http://api.jquery.com/jquery.extend/ and from what I understand I need to merge my objects to pass them as a config option, here is the link to my plugin from my drop box account (js fiddle did not take the https link for some reasons), please see below link to jquery.myplugin.js (random name for now, but will use unique naming convention once I work out the logic):
https://www.dropbox.com/s/boadofib6nggfzp/jquery.myplugin.js
Can anyone help me figure out how to pass this variable in my config option so users can add as many "title" and "src" from the option desktop_xl please?
UPDATE:
I have figured out how to pull array information and append it to my images, however, I still have no idea on how to "link" this to the plugin option settings as I need to give the user the option to add as many images with title as they would like in the option settings.
Here is how I have figured out how to pull data from array:
//create img desktop_xl loop
$.each(desktop_xl, function( index , value ){
$('#container').append(
$("<img />").attr({
id: value.title,
src: value.src,
title: value.title
})
);
});
UPDATE 2:
I have done some more work on the plugin, here is the code so far:
;(function($, window, document, undefined){
//define MyjQueryPlugin object with default config settings:
$.MyjQueryPlugin = {
defaults: {
imagecontainer: "#container",
version: "v01"
// add my Arrays to default options here?
// arrays should allow users to add as many images to #container div as they require
// arrays are desktop_xl[] , desktop_l[] , ipad_p[] , mobile_l[], mobile_p[]
}
};
//extend jquery with the plugin
$.fn.extend({
MyjQueryPlugin:function(config) {
//use defaults or properties supplied by user
var config = $.extend({}, $.MyjQueryPlugin.defaults, config );
//append slides
$(config.imagecontainer).append('<div class="imagecontainerfordesktop_xlarray" </div>').css('height', $(window).height() );
// append MyjQueryPlugin sidebar
this.append( '<div id="Mysidebar" class="open">' +
'<p class="review">Version ' + config.version + '- ready for review</p>'+
'<hr>' +
'</div>')
.children()
.css('height', $(window).height() );
//create array of objects
var desktop_xl = [
{
"title":"Homepage", // text for sidebar
"src":"slides/1200/Homepage.jpg"// path to image >= 1200px wide
},
{
"title":"Categories", // text for sidebar
"src":"slides/1200/Categories.jpg"// path to image >= 1200px wide
},
{
"title":"Product description", // text for sidebar
"src":"slides/1200/Product_description.jpg" // path to image >= 1200px wide
}
];
var desktop_l = [
// if array is empty, remove elements from the page
];
var ipad_p = [
{
"title":"Homepage", // text for sidebar
"src":"slides/480/Homepage.jpg" // path to image >= 480px wide
}
];
var mobile_l = [];
var mobile_p = [];
// set Global Variables
var width = $(window).width();
var currHeight = $(window).height();
var ctrl = $(".ctrl");
var ulscreenlia = $('ul.screen li a');
var sidebarlia = $('#MyjQueryPluginsidebar li a');
var sidebar = $("#MyjQueryPluginsidebar");
var ulscreenli = $('ul.screen li');
if (desktop_xl.length === 0) {
ulscreenli.eq(0).hide();
$('div.select_join option[value="xld"]').remove();
}
if (desktop_l.length === 0) {
ulscreenli.eq(1).hide();
$('div.select_join option[value="ld"]').remove();
}
if (ipad_p.length === 0) {
ulscreenli.eq(2).hide();
$('div.select_join option[value="ip"]').remove();
}
if (mobile_l.length === 0) {
ulscreenli.eq(3).hide();
$('div.select_join option[value="ml"]').remove();
}
if (mobile_p.length === 0) {
ulscreenli.eq(4).hide();
$('div.select_join option[value="mp"]').remove();
}
//create img desktop_xl loop
$.each(desktop_xl, function( index , value ){
$('#container .slides-xld').append(
//getting values from array but cannot understand how to pass array(s): desktop_xl, desktop_l, ipad_p, mobile_l, mobile_p inside config option
//And Each arrays should allow user to add multiple images to #container dive
$("<img />").attr({
id: value.title,
src: value.src,
title: value.title
})
);
});
//create img ipadp loop
$.each(ipad_p, function( index , value){
$('#container .slides-ipadp').append(
$("<img />").attr({
id: value.title,
src: value.src,
title: value.title
})
);
});
function rundateobject(){
var current_date = new Date ( );
var month_names = new Array ( );
month_names[month_names.length] = "January";
month_names[month_names.length] = "February";
month_names[month_names.length] = "March";
month_names[month_names.length] = "April";
month_names[month_names.length] = "May";
month_names[month_names.length] = "June";
month_names[month_names.length] = "July";
month_names[month_names.length] = "August";
month_names[month_names.length] = "September";
month_names[month_names.length] = "October";
month_names[month_names.length] = "November";
month_names[month_names.length] = "December";
var day_names = new Array ( );
day_names[day_names.length] = "Sunday";
day_names[day_names.length] = "Monday";
day_names[day_names.length] = "Tuesday";
day_names[day_names.length] = "Wednesday";
day_names[day_names.length] = "Thursday";
day_names[day_names.length] = "Friday";
day_names[day_names.length] = "Saturday";
$('#date').html( day_names[current_date.getDay()]
+ ', '
+ month_names[current_date.getMonth()]
+ ' '
+ current_date.getDate()
+ ' '
+ current_date.getFullYear() );
};
//create animation for anchor links with jQuery DOM ready function
$(function(){
$('a').hover(function(){
$(this).animate({
'margin-left':10,
'padding-left':20
},200);
$(this).dequeue();
},
function() {
$(this).animate({
'margin-left':0,
'padding-left':15
},200);
$(this).dequeue();
}
);
});
//on resize browser, adjust elements height
//initialise plugins
$(".nano").nanoScroller();
//initialise functions
rundateobject();
//return the jquery object for chaining
return this;
}// config options
}); // jQuery extend
})(jQuery, window, document);
The answer was given to me on jquery.com by user kbwood.au
defaults: {
imagecontainer: "#container",
version: "v01",
desktop_xl: [] //Array
}
Then in the .each function we need to pass the array as a config.desktop_xl:
//create img desktop_xl loop
$.each(config.desktop_xl, function( index , value ){
$('#container').append(
$("<img />").attr({
id: value.title,
src: value.src,
title: value.title
})
);
});
for a service providers website I am using the code below (stole it from here) to display a map and draw areas each provider covers. How can i return and store the arrays of latitudes/longitudes of each shape i draw? i need to save it into database so later i can use for search queries when searching for providers within a certain area.
<script type="text/javascript">
var drawingManager;
var selectedShape;
var colors = ['#1E90FF', '#FF1493', '#32CD32', '#FF8C00', '#4B0082'];
var selectedColor;
var colorButtons = {};
function clearSelection() {
if (selectedShape) {
selectedShape.setEditable(false);
selectedShape = null;
}
}
function setSelection(shape) {
clearSelection();
selectedShape = shape;
shape.setEditable(true);
selectColor(shape.get('fillColor') || shape.get('strokeColor'));
}
function deleteSelectedShape() {
if (selectedShape) {
selectedShape.setMap(null);
}
}
function selectColor(color) {
selectedColor = color;
for (var i = 0; i < colors.length; ++i) {
var currColor = colors[i];
colorButtons[currColor].style.border = currColor == color ? '2px solid #789' : '2px solid #fff';
}
// Retrieves the current options from the drawing manager and replaces the
// stroke or fill color as appropriate.
var polylineOptions = drawingManager.get('polylineOptions');
polylineOptions.strokeColor = color;
drawingManager.set('polylineOptions', polylineOptions);
var rectangleOptions = drawingManager.get('rectangleOptions');
rectangleOptions.fillColor = color;
drawingManager.set('rectangleOptions', rectangleOptions);
var circleOptions = drawingManager.get('circleOptions');
circleOptions.fillColor = color;
drawingManager.set('circleOptions', circleOptions);
var polygonOptions = drawingManager.get('polygonOptions');
polygonOptions.fillColor = color;
drawingManager.set('polygonOptions', polygonOptions);
}
function setSelectedShapeColor(color) {
if (selectedShape) {
if (selectedShape.type == google.maps.drawing.OverlayType.POLYLINE) {
selectedShape.set('strokeColor', color);
} else {
selectedShape.set('fillColor', color);
}
}
}
function makeColorButton(color) {
var button = document.createElement('span');
button.className = 'color-button';
button.style.backgroundColor = color;
google.maps.event.addDomListener(button, 'click', function() {
selectColor(color);
setSelectedShapeColor(color);
});
return button;
}
function buildColorPalette() {
var colorPalette = document.getElementById('color-palette');
for (var i = 0; i < colors.length; ++i) {
var currColor = colors[i];
var colorButton = makeColorButton(currColor);
colorPalette.appendChild(colorButton);
colorButtons[currColor] = colorButton;
}
selectColor(colors[0]);
}
function initialize() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
center: new google.maps.LatLng(22.344, 114.048),
mapTypeId: google.maps.MapTypeId.ROADMAP,
disableDefaultUI: true,
zoomControl: true
});
var polyOptions = {
strokeWeight: 0,
fillOpacity: 0.45,
editable: true
};
// Creates a drawing manager attached to the map that allows the user to draw
// markers, lines, and shapes.
drawingManager = new google.maps.drawing.DrawingManager({
drawingMode: google.maps.drawing.OverlayType.POLYGON,
markerOptions: {
draggable: true
},
polylineOptions: {
editable: true
},
rectangleOptions: polyOptions,
circleOptions: polyOptions,
polygonOptions: polyOptions,
map: map
});
google.maps.event.addListener(drawingManager, 'overlaycomplete', function(e) {
if (e.type != google.maps.drawing.OverlayType.MARKER) {
// Switch back to non-drawing mode after drawing a shape.
drawingManager.setDrawingMode(null);
// Add an event listener that selects the newly-drawn shape when the user
// mouses down on it.
var newShape = e.overlay;
newShape.type = e.type;
google.maps.event.addListener(newShape, 'click', function() {
setSelection(newShape);
});
setSelection(newShape);
}
});
// Clear the current selection when the drawing mode is changed, or when the
// map is clicked.
google.maps.event.addListener(drawingManager, 'drawingmode_changed', clearSelection);
google.maps.event.addListener(map, 'click', clearSelection);
google.maps.event.addDomListener(document.getElementById('delete-button'), 'click', deleteSelectedShape);
buildColorPalette();
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
any help would be appreciated.
Thank you
This is something you need.
I tested it and it works very well.
Just copy and then enjoy it.
<html>
<!--Here you will create a polygon by tools that Google maps "drawingManager" gives to you and then you have an array named "coordinates" as an output. This array saves all latLng of the polygon. When you edit the polygon it also edit this variable too.
!-->
<head>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true&libraries=drawing"></script>
<!--Global variables!-->
<script>
//This variable gets all coordinates of polygone and save them. Finally you should use this array because it contains all latitude and longitude coordinates of polygon.
var coordinates = [];
//This variable saves polygon.
var polygons = [];
</script>
<script>
//This function save latitude and longitude to the polygons[] variable after we call it.
function save_coordinates_to_array(polygon)
{
//Save polygon to 'polygons[]' array to get its coordinate.
polygons.push(polygon);
//This variable gets all bounds of polygon.
var polygonBounds = polygon.getPath();
for(var i = 0 ; i < polygonBounds.length ; i++)
{
coordinates.push(polygonBounds.getAt(i).lat(), polygonBounds.getAt(i).lng());
alert(i);
}
}
</script>
<script>
function initialize()
{
//Create a Google maps.
var map = new google.maps.Map(document.getElementById('map'), {zoom: 12, center: new google.maps.LatLng(32.344, 51.048)});
//Create a drawing manager panel that lets you select polygon, polyline, circle, rectangle or etc and then draw it.
var drawingManager = new google.maps.drawing.DrawingManager();
drawingManager.setMap(map);
//This event fires when creation of polygon is completed by user.
google.maps.event.addDomListener(drawingManager, 'polygoncomplete', function(polygon) {
//This line make it possible to edit polygon you have drawed.
polygon.setEditable(true);
//Call function to pass polygon as parameter to save its coordinated to an array.
save_coordinates_to_array(polygon);
//This event is inside 'polygoncomplete' and fires when you edit the polygon by moving one of its anchors.
google.maps.event.addListener(polygon.getPath(), 'set_at', function () {
alert('changed');
save_coordinates_to_array(polygon);
});
//This event is inside 'polygoncomplete' too and fires when you edit the polygon by moving on one of its anchors.
google.maps.event.addListener(polygon.getPath(), 'insert_at', function () {
alert('also changed');
save_coordinates_to_array(polygon);
});
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div style="width:1024px; height:768px;" id="map"></div>
</body>
</html>