Some misunderstanding how to use bootstrap and css - css

I am new to web programming and especially to css and bootstrap.
I found implemintation of multiselect-dropbox in angularjs:
'use strict';
var app = angular.module('myApp', ['app.directives']);
app.controller('AppCtrl', function($scope){
$scope.roles = [
{"id": 1, "name": "Manager", "assignable": true},
{"id": 2, "name": "Developer", "assignable": true},
{"id": 3, "name": "Reporter", "assignable": true}
];
$scope.member = {roles: []};
$scope.selected_items = [];
});
var app_directives = angular.module('app.directives', []);
app_directives.directive('dropdownMultiselect', function(){
return {
restrict: 'E',
scope:{
model: '=',
options: '=',
pre_selected: '=preSelected'
},
template: "<div class='btn-group' data-ng-class='{open: open}'>"+
"<button class='btn btn-small'>Select</button>"+
"<button class='btn btn-small dropdown-toggle' data-ng-click='open=!open;openDropdown()'><span class='caret'></span></button>"+
"<ul class='dropdown-menu' aria-labelledby='dropdownMenu'>" +
"<li><a data-ng-click='selectAll()'><i class='icon-ok-sign'></i> Check All</a></li>" +
"<li><a data-ng-click='deselectAll();'><i class='icon-remove-sign'></i> Uncheck All</a></li>" +
"<li class='divider'></li>" +
"<li data-ng-repeat='option in options'> <a data-ng-click='setSelectedItem()'>{{option.name}}<span data-ng-class='isChecked(option.id)'></span></a></li>" +
"</ul>" +
"</div>" ,
controller: function($scope){
$scope.openDropdown = function(){
$scope.selected_items = [];
for(var i=0; i<$scope.pre_selected.length; i++){ $scope.selected_items.push($scope.pre_selected[i].id);
}
};
$scope.selectAll = function () {
$scope.model = _.pluck($scope.options, 'id');
console.log($scope.model);
};
$scope.deselectAll = function() {
$scope.model=[];
console.log($scope.model);
};
$scope.setSelectedItem = function(){
var id = this.option.id;
if (_.contains($scope.model, id)) {
$scope.model = _.without($scope.model, id);
} else {
$scope.model.push(id);
}
console.log($scope.model);
return false;
};
$scope.isChecked = function (id) {
if (_.contains($scope.model, id)) {
return 'icon-ok pull-right';
}
return false;
};
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.4.4/underscore-min.js"></script>
<link href="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.0/css/bootstrap-combined.min.css" rel="stylesheet"/>
<div ng-app="myApp" ng-controller="AppCtrl">
<dropdown-multiselect pre-selected="member.roles" model="selected_items" options="roles"></dropdown-multiselect>
<pre>selected roles = {{selected_items | json}}</pre>
</div>
I want to use it in my project.
But I need to replace the appearance of the images.
Here how it looks now:
And I want the delete and checked signs will appear on another side:
Any idea how to implement it?
What changes I have to make changes on external resources files?

Not sure, is this right way or not, but its work for you
Change position of Text Check All and Uncheck All
"<li><a data-ng-click='selectAll()'>Check All <i class='icon-ok-sign'></i></a></li>" +
"<li><a data-ng-click='deselectAll();'> Uncheck All<i class='icon-remove-sign'></i></a></li>"
'use strict';
var app = angular.module('myApp', ['app.directives']);
app.controller('AppCtrl', function($scope){
$scope.roles = [
{"id": 1, "name": "Manager", "assignable": true},
{"id": 2, "name": "Developer", "assignable": true},
{"id": 3, "name": "Reporter", "assignable": true}
];
$scope.member = {roles: []};
$scope.selected_items = [];
});
var app_directives = angular.module('app.directives', []);
app_directives.directive('dropdownMultiselect', function(){
return {
restrict: 'E',
scope:{
model: '=',
options: '=',
pre_selected: '=preSelected'
},
template: "<div class='btn-group' data-ng-class='{open: open}'>"+
"<button class='btn btn-small'>Select</button>"+
"<button class='btn btn-small dropdown-toggle' data-ng-click='open=!open;openDropdown()'><span class='caret'></span></button>"+
"<ul class='dropdown-menu' aria-labelledby='dropdownMenu'>" +
"<li><a data-ng-click='selectAll()'>Check All <i class='icon-ok-sign'></i></a></li>" +
"<li><a data-ng-click='deselectAll();'>Uncheck All <i class='icon-remove-sign'></i></a></li>" +
"<li class='divider'></li>" +
"<li data-ng-repeat='option in options'> <a data-ng-click='setSelectedItem()'>{{option.name}}<span data-ng-class='isChecked(option.id)'></span></a></li>" +
"</ul>" +
"</div>" ,
controller: function($scope){
$scope.openDropdown = function(){
$scope.selected_items = [];
for(var i=0; i<$scope.pre_selected.length; i++){ $scope.selected_items.push($scope.pre_selected[i].id);
}
};
$scope.selectAll = function () {
$scope.model = _.pluck($scope.options, 'id');
console.log($scope.model);
};
$scope.deselectAll = function() {
$scope.model=[];
console.log($scope.model);
};
$scope.setSelectedItem = function(){
var id = this.option.id;
if (_.contains($scope.model, id)) {
$scope.model = _.without($scope.model, id);
} else {
$scope.model.push(id);
}
console.log($scope.model);
return false;
};
$scope.isChecked = function (id) {
if (_.contains($scope.model, id)) {
return 'icon-ok pull-right';
}
return false;
};
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.4.4/underscore-min.js"></script>
<link href="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.0/css/bootstrap-combined.min.css" rel="stylesheet"/>
<div ng-app="myApp" ng-controller="AppCtrl">
<dropdown-multiselect pre-selected="member.roles" model="selected_items" options="roles"></dropdown-multiselect>
<pre>selected roles = {{selected_items | json}}</pre>
</div>

For the first 2, you need to change the template to move the icons to after the text.
template: "<div class='btn-group' data-ng-class='{open: open}'>"+
"<button class='btn btn-small'>Select</button>"+
"<button class='btn btn-small dropdown-toggle' data-ng-click='open=!open;openDropdown()'><span class='caret'></span></button>"+
"<ul class='dropdown-menu' aria-labelledby='dropdownMenu'>" +
"<li><a data-ng-click='selectAll()'>Check All <i class='icon-ok-sign'></i></a></li>" +
"<li><a data-ng-click='deselectAll();'>Uncheck All <i class='icon-remove-sign'></i></a></li>" +
"<li class='divider'></li>" +
"<li data-ng-repeat='option in options'> <a data-ng-click='setSelectedItem()'> {{option.name}}<span data-ng-class='isChecked(option.id)'></span></a></li>" +
"</ul>" +
"</div>" ,
For the options list you need to change the isChecked method and replace pull-right by pull-left
$scope.isChecked = function (id) {
if (_.contains($scope.model, id)) {
return 'icon-ok pull-left';
}
return false;
};
Notice that I added a couple of to the template to give some gap between the icons and the text. You could do the same thing in CSS too.
'use strict';
var app = angular.module('myApp', ['app.directives']);
app.controller('AppCtrl', function($scope){
$scope.roles = [
{"id": 1, "name": "Manager", "assignable": true},
{"id": 2, "name": "Developer", "assignable": true},
{"id": 3, "name": "Reporter", "assignable": true}
];
$scope.member = {roles: []};
$scope.selected_items = [];
});
var app_directives = angular.module('app.directives', []);
app_directives.directive('dropdownMultiselect', function(){
return {
restrict: 'E',
scope:{
model: '=',
options: '=',
pre_selected: '=preSelected'
},
template: "<div class='btn-group' data-ng-class='{open: open}'>"+
"<button class='btn btn-small'>Select</button>"+
"<button class='btn btn-small dropdown-toggle' data-ng-click='open=!open;openDropdown()'><span class='caret'></span></button>"+
"<ul class='dropdown-menu' aria-labelledby='dropdownMenu'>" +
"<li><a data-ng-click='selectAll()'>Check All <i class='icon-ok-sign'></i></a></li>" +
"<li><a data-ng-click='deselectAll();'>Uncheck All <i class='icon-remove-sign'></i></a></li>" +
"<li class='divider'></li>" +
"<li data-ng-repeat='option in options'> <a data-ng-click='setSelectedItem()'> {{option.name}}<span data-ng-class='isChecked(option.id)'></span></a></li>" +
"</ul>" +
"</div>" ,
controller: function($scope){
$scope.openDropdown = function(){
$scope.selected_items = [];
for(var i=0; i<$scope.pre_selected.length; i++){ $scope.selected_items.push($scope.pre_selected[i].id);
}
};
$scope.selectAll = function () {
$scope.model = _.pluck($scope.options, 'id');
console.log($scope.model);
};
$scope.deselectAll = function() {
$scope.model=[];
console.log($scope.model);
};
$scope.setSelectedItem = function(){
var id = this.option.id;
if (_.contains($scope.model, id)) {
$scope.model = _.without($scope.model, id);
} else {
$scope.model.push(id);
}
console.log($scope.model);
return false;
};
$scope.isChecked = function (id) {
if (_.contains($scope.model, id)) {
return 'icon-ok pull-left';
}
return false;
};
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.4.4/underscore-min.js"></script>
<link href="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.0/css/bootstrap-combined.min.css" rel="stylesheet"/>
<div ng-app="myApp" ng-controller="AppCtrl">
<dropdown-multiselect pre-selected="member.roles" model="selected_items" options="roles"></dropdown-multiselect>
<pre>selected roles = {{selected_items | json}}</pre>
</div>

Related

DropdownList Doesn't Work on Mobile Devices

I have 2 dropdown list in my page. In web browser (PC side) It works fine. There is no problem. When i open the page with chrome toogle device toolbar and i resize as mobile view, it only gives this error
fastclick.js:1 [Intervention] Unable to preventDefault inside passive event listener due to target being treated as passive. See https://www.chromestatus.com/features/5093566007214080
csHTML Code
<div class="tab-pane active tabcontent" id="reservationPage" role="tabpanel">
<div class="col-sm-12 col-md-12">
<div class="form-group row rowR">
<label class="form-control-label col-md-2"><strong>Yemekhane</strong> </label>
<div class="col-md-12">
#Html.DropDownListFor(x => x.RefectoryId, new SelectList(Model.Refectories, "Id", "Name"), ("Seçiniz"), new { Id = "RefectoryId", #class = "form-control select2" })
</div>
</div>
<div class="form-group row rowR">
<label class="form-control-label col-md-2"><strong>Öğün</strong> </label>
<div class="col-md-12">
#Html.DropDownListFor(x => x.FoodMealId, new SelectList(Model.FoodMeals, "Id", "Name"), ("Seçiniz"), new { Id = "FoodMealId", #class = "form-control select2" })
</div>
</div>
</div>
</div>
JS Code
<script>
var reservationCount = 0;
var totalAmount = 0;
$(document).ready(function () {
$("#reservationCount")[0].textContent = "(" + reservationCount + ")";
//İlk açıldığında rezervasyon sayfasının acık gelmesi için
var tablinks = document.getElementById("reservationPageHead");
tablinks.className = tablinks.className + " active";
document.getElementById('reservationPage').style.display = "block";
//var foodMealId = $("#FoodMealId").val();
//var refectoryId = $("#RefectoryId").val();
//GetCalendarMenuPartial(foodMealId, refectoryId);
$("#RefectoryId").select2({
allowClear: true,
placeholder: 'Yemekhane Seçiniz',
// dropdownParent: $(".bootbox-body"),
});
var refectorySelect = $('#RefectoryId');
refectorySelect.on("select2:select", function (e) {
var foodMealId = $("#FoodMealId").val();
var refectoryId = $("#RefectoryId").val();
$.ajax({
url: "#Url.Action("GetRefectoryWithFoodMeal", "Reservation", new { area = "Common" })",
data: { refectoryId: refectoryId },
type: "POST",
async: false,
success: function (returnData) {
if (returnData.data == undefined) {
PageToastr(returnData.type, returnData.message, returnData.title);
}
else {
//FoodMeal List
$("#FoodMealId option[value]").remove();
$("#FoodMealId").select2({
allowClear: true,
placeholder: 'Seçiniz',
data : returnData.data,
});
}
},
beforeSend: function () {
$(".loaderDiv").show();
$(".loader").show();
},
complete: function () {
$(".loaderDiv").hide();
$(".loader").hide();
},
error: function (xhr, status, err) {
if (xhr.status === 999) {
noAuthorize(this.url);
}
}
});
var foodMealId = $("#FoodMealId").val();
var refectoryId = $("#RefectoryId").val();
GetCalendarMenuPartial(foodMealId, refectoryId);
});
$("#FoodMealId").select2({
allowClear: true,
placeholder: 'Öğün Seçiniz',
//dropdownParent: $(".bootbox-body"),
});
var foodMealSelect = $('#FoodMealId');
foodMealSelect.on("select2:select", function (e) {
var foodMealId = $("#FoodMealId").val();
var refectoryId = $("#RefectoryId").val();
GetCalendarMenuPartial(foodMealId, refectoryId);
});
// Rezervasyonu tamamla için tooltip
$('#completeReservation').tooltip('update');
});
</script>
<script>
function GetCalendarMenuPartial(foodMealId, refectoryId) {
$.ajax({
url: '#Url.Action("NewReservationCalendarMenuPartial", "Reservation", new { area = "Common" })',
data: { foodMealId: foodMealId, refectoryId: refectoryId, addCardMenu: $("#AddCardMenuString").val() },
type: "POST",
success: function (partialPage) {
if (partialPage.title != undefined) {
PageToastr(partialPage.type, partialPage.message, partialPage.title);
if (partialPage.result == '#Enums.ResultStatus.SessionTimeExpired.ToString()') {
setTimeout(function () { window.location.href = '/Login/Login'; }, 5000)
}
}
else {
$("#calendarMenuPartial").html(partialPage);
}
},
beforeSend: function () {
$(".loaderDiv").show();
$(".loader").show();
},
complete: function () {
$(".loaderDiv").hide();
$(".loader").hide();
},
error: function (xhr, status, err) {
if (xhr.status === 999) {
noAuthorize(this.url);
}
}
});
}
</script>
After that I've added touch-action: none; but it doesn't work too. It works properly in PC Devices. But never works on mobile devices.

Google Place Search using SearchBox - Restrict for UK only

I am using google place SearchBox ( not AutoComplete ) for place search. My objective is I want to restrict the search for a particular country (UK).
I know the same thing can be achieved easily by using AutoComplete. But I can't use this because my map will populate on enter key as well as against a search button.
I am using code to select the first option on search button click.
I have tried with google.maps.LatLngBounds but that only sets the priority of result, not restricting anything.
Html:
<ul class="list-unstyled search-branch">
<li>Search branches:</li>
<li><input type="text" placeholder="City, town or postcode" id="txtbranch" value="Eurochange" />
<input type="button" class="button gold" id="getbranch" value="Search" />
<div style="clear:both;"></div>
<div class="error-message-summary" id="locationnotfound" style="padding: 0;top:-30px; position:relative; font-size:16px;display:none">
No search results found.
</div>
</li>
</ul>
js:
var input = document.getElementById('txtbranch');
var defaultBounds = new google.maps.LatLngBounds(
new google.maps.LatLng(-33.8902, 151.1759),
new google.maps.LatLng(-33.8474, 1512631)
);
var options = {
bounds: defaultBounds
}
var searchBox = new google.maps.places.SearchBox(input, {
bounds: defaultBounds
});
$('#getbranch').click(function () {
var input = document.getElementById('txtbranch');
if (BranchAddressSelector.val() == "") {
return;
}
google.maps.event.trigger(input, 'focus');
google.maps.event.trigger(input, 'keydown', { keyCode: 13 });
return false;
})
searchBox.addListener('places_changed', function () {
var places = searchBox.getPlaces()[0];
if (typeof (places) === "undefined") {
locationNotFoundSelector.css("display", "block");
return false;
}
if (BranchAddressSelector.val() == "") {
return false;
}
var address = places.formatted_address;
if (typeof (address) === "undefined") {
locationNotFoundSelector.css("display", "block");
return false;
}
var latitude = places.geometry.location.lat();
var longitude = places.geometry.location.lng();
$.ajax({
type: "GET",
url: BranchLocatorUrl.GetBranches,
data: { Latitude: latitude, longitude: longitude },
success: function (data) {
if (data.length > 0) {
markers = data;
LoadMap(0, 0);
BranchListSelector.html(CreateSearchHtml(markers));
goToByScroll("dvMap");
BranchListSelector.css("display", "none");
paginationSelector.css("display", "none");
$('.map-distance').css("display", "block");
locationNotFoundSelector.css("display", "none");
var show_per_page = 6;
var number_of_items = BranchListSelector.children('.BranchItem').size();
var number_of_pages = Math.ceil(number_of_items / show_per_page);
totalPages = number_of_pages;
$('#current_page').val(0);
$('#show_per_page').val(show_per_page);
var navigation_html = '<a class="previous_link" style="color: #007ea0;" href="javascript:previous();">Prev</a> ';
var current_link = 0;
while (number_of_pages > current_link) {
navigation_html += '<a class="page_link" style="color: #007ea0;" href="javascript:go_to_page(' + current_link + ')" longdesc="' + current_link + '">' + (current_link + 1) + '</a> ';
current_link++;
}
navigation_html += '<a class="next_link" style="color: #007ea0;" href="javascript:next();"> Next</a>';
$('#page_navigation').html(navigation_html).css("float", "right").css("display", "none");
$('#page_navigation .page_link:first').addClass('active_page');
BranchListSelector.children('.BranchItem').css('display', 'none');
BranchListSelector.children('.BranchItem').slice(0, show_per_page).css('display', 'block');
BranchListSelector.css("display", "block");
// paginationSelector.css("display", "block");
$('.map-distance').css("display", "none");
$('#moreBranch').css("display", "block");
}
else {
alert("Data not found.");
}
},
error: function (e) {
alert("Some Problem occurs.Try after some time");
return;
}
});
});

Update function returns an error

This code returns an "Error: $scope.todoItems.update is not a function"
(in markDone function)
As I can see in console, $scope.todoItems has functions like save(), remove() but not an update() function, but as I can see here I writing it right.
Is something that I doing is wrong? More information would be helpful?
TodoItems = new Mongo.Collection('todoItems');
if(Meteor.isClient){
angular.module('todo_am', ['angular-meteor']);
angular.module('todo_am').controller('OutputListCtrl', ['$scope', '$meteor',
function($scope, $meteor){
$scope.todoItems = $meteor.collection(TodoItems);
$scope.remove = function(todoItem){
$scope.todoItems.remove(todoItem);
};
$scope.saveCustom = function(todoItem){
todoItem.isRead = false;
$scope.todoItems.save(todoItem);
};
$scope.markDone = function(todoItem){
console.log('>>> 4', todoItem);
console.log('>>> 5', $scope.todoItems);
$scope.todoItems.update(todoItem._id, { $set: { isRead: true }}); // <<<<<<<<< This line returns error
};
$scope.markUndone = function(todoItem){
todoItem.isRead = true;
$scope.todoItems.update(todoItem);
};
}]);
}
------------------------------ UPDATE --------------------------------
This is working:
if(Meteor.isClient){
angular.module('todo_am', ['angular-meteor']);
angular.module('todo_am').controller('OutputListCtrl', ['$scope', '$meteor',
function($scope, $meteor){
$scope.todoItems = $meteor.collection(TodoItems);
$scope.remove = function(todoItem){
$scope.todoItems.remove(todoItem);
};
$scope.saveCustom = function(todoItem){
todoItem.isRead = false;
$scope.todoItems.save(todoItem);
};
$scope.markDone = function(todoItem){
TodoItems.update({ _id: todoItem._id }, { $set: { isRead: true }});
};
$scope.markUndone = function(todoItem){
TodoItems.update({ _id: todoItem._id }, { $set: { isRead: false }});
};
}]);
}
------------------------------ UPDATE2 --------------------------------
This is whole code. I do not know if it's a right solution or not but it works.
Is there any example for update exists record in DB?
$ meteor --version
Meteor 1.1.0.2
As I can see in .meteor/versions file:
angular:angular#1.3.15_1
urigo:angular#0.8.6
index.html
<body ng-app="todo_am">
<div ng-controller="OutputListCtrl">
<div ng-include="'output-list.ng.html'"></div>
<div ng-include="'insert-new-form.ng.html'"></div>
</div>
</body>
index.ng.html
<p>Nothing</p>
insert-new-form.ng.html
<div>
<input type="text" ng-model="newTodoItem.text" />
<button ng-click="saveCustom(newTodoItem); newTodoItem='';" >Add New</button>
</div>
output-list.ng.html
<div>
<ul>
<li ng-repeat="todoItem in todoItems">
<p>
{{ todoItem.text }}
<span ng-switch on="todoItem.isRead">
<span ng-switch-when="true">
<button ng-click="markUndone(todoItem)">Mark Undone</button>
</span>
<span ng-switch-default>
<button ng-click="markDone(todoItem)">Mark Done</button>
</span>
</span>
<button ng-click="remove(todoItem)">X</button>
</p>
</li>
</ul>
</div>
app.js
TodoItems = new Mongo.Collection('todoItems');
if(Meteor.isClient){
angular.module('todo_am', ['angular-meteor']);
angular.module('todo_am').controller('OutputListCtrl', ['$scope', '$meteor',
function($scope, $meteor){
$scope.todoItems = $meteor.collection(TodoItems);
$scope.remove = function(todoItem){
$scope.todoItems.remove(todoItem);
};
$scope.saveCustom = function(todoItem){
todoItem.isRead = false;
$scope.todoItems.save(todoItem);
};
$scope.markDone = function(todoItem){
TodoItems.update({ _id: todoItem._id }, { $set: { isRead: true }});
};
$scope.markUndone = function(todoItem){
TodoItems.update({ _id: todoItem._id }, { $set: { isRead: false }});
};
}]);
}
if(Meteor.isServer){
Meteor.startup(function(){
/**
* If DB is empty, add some todoItems just for DEV purposes
*/
if (TodoItems.find().count() === 0) {
var todoItems = [
{
'text': 'First todo first todo first todo first todo first todo first todo first todo first todo first todo',
'isRead': true,
'userPosted': 'Vasia'
},
{
'text': 'Second todo item',
'isRead': false,
'userPosted': 'Fedia'
},
{
'text': 'Third todo item',
'isRead': true,
'userPosted': 'Vasia'
}
];
for (var i = 0; i < todoItems.length; i++)
TodoItems.insert({text: todoItems[i].text, isRead: todoItems[i].isRead});
}
});
}
That doesn't look like $scope.todoItems is a Meteor collection. If you look through the documentation you linked (http://docs.meteor.com/#/full/mongo_collection) - there's no reference to Meteor's Mongo Collections having a "save" method.
It looks like you're using an "Angular Meteor Collection" - http://angularjs.meteor.com/api/AngularMeteorCollection
In which case a simple call to ".save" should do it. Perhaps something like this:
$scope.markDone = function(todoItem){
todoItem.isRead = true;
$scope.todoItems.save(todoItem);
};

Google Places JS API Show Reviews

JS API, not web service:
I'm having trouble displaying the 0-5 reviews included with the Place Details Responses:
https://developers.google.com/maps/documentation/javascript/places#place_details_responses
So far I have been able to display these items:
details.name
details.rating
details.open_now
details.formatted_address
details.types
details.formatted_phone_number
But when I try to show details.reviews it just displays:
[object Object],[object Object],[object Object],[object Object],[object Object]
Has anyone had any success displaying the reviews?
function createMarker(place) {
var image = 'img/marker.png';
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
icon: image,
position: place.geometry.location
});
var request = { reference: place.reference };
service.getDetails(request, function(details, status) {
google.maps.event.addListener(marker, 'click', function() {
if (status == google.maps.places.PlacesServiceStatus.OK) {
// Replace empty spaces in navigation link with + symbols
var navLink = details.formatted_address;
navLink = navLink.replace(/\s/g, "+");
$('.navLink').html(navLink);
// Match Rating bar width to rating number
var ratingWidth = (details.rating*20)+"px";
$('.rating-bar > span').css('width', "'"+ratingWidth+"'");
var contentStr = '<h5 class="info-window-title">'+details.name+'</h5><ul class="info-window">';
if (!!details.rating) contentStr += '<li>Rating: <div class="rating-bar"><span style=width:'+ratingWidth+'></span></div><strong>'+details.rating+'</strong></li>';
if (!!details.open_now) contentStr += '<li class="open-now">'+details.open_now+'</li>';
contentStr += '<li>'+details.formatted_address+'</li>';
contentStr += '<li class=gray>'+details.types+'</li>';
// Check for platform to send appropriate app link
if ((navigator.platform.indexOf("iPhone") != -1)) {
contentStr += '<li class="link"><a class=navLink href=http://maps.apple.com/?daddr=Current+Location&saddr='+navLink+'><i class="fa fa-automobile"></i> Get Directions</a></li>';
} else {
contentStr += '<li class="link"><a class=navLink href=https://www.google.com/maps/dir/Current+Location/'+navLink+'><i class="fa fa-automobile"></i> Get Directions</a></li>';
}
if (!!details.formatted_phone_number) contentStr += '<li class="link"><i class="fa fa-phone"></i> '+details.formatted_phone_number+'</li>';
if (!!details.reviews) contentStr += '<li>'+details.reviews+'</li>';
contentStr += '</ul>';
infowindow.setContent(contentStr);
infowindow.open(map,marker);
} else {
var contentStr = "<h5>No Result, status="+status+"</h5>";
infowindow.setContent(contentStr);
infowindow.open(map,marker);
}
});
});
}
details.reviews doesn't return a string(what you get in the output is the string-representation of this array), it's an array which contains up to 5 review-objects. you must iterate over the items of this array and prepare the output on your own.
A sample-function which prepares the reviews:
(function (rs /*reviews-array*/ , fx /*review-parser*/ ) {
var list = document.createElement('ul');
rs.forEach(function (r) {
list.appendChild(fx(r));
});
return '<ul>' + list.innerHTML + '</ul>';
//remove the previous line when you want to return a DOMNode
return list;
}
(details.reviews,
function (r /*single review*/ ) {
console.log(r.aspects)
var item = document.createElement('li'),
review = item.appendChild(document.createElement('ul'))
props = {
author_name: 'author',
rating: 'rating',
text: 'text'
};
item.appendChild(document.createElement('h6'));
item.lastChild.appendChild(document.createElement('a'));
item.lastChild.lastChild
.appendChild(document.createTextNode(r.author_name));
if (r.author_url) {
item.lastChild.lastChild.setAttribute('href', r.author_url);
}
item.lastChild.appendChild(document.createTextNode('(' + r.rating +
')'));
if (r.aspects && r.aspects.length) {
item.appendChild(document.createElement('ul'));
r.aspects.forEach(function (a) {
item.lastChild.appendChild(document.createElement(
'li'));
item.lastChild.lastChild
.appendChild(document.createTextNode(a.type +
':' + a.rating))
});
}
item.appendChild(document.createElement('p'));
item.lastChild.appendChild(document.createTextNode(r.text));
return item;
}
))
Demo:
var map, infowindow, service;
function initialize() {
map = new google.maps.Map(document.getElementById('map-canvas'), {
center: new google.maps.LatLng(-33.8665433, 151.1956316),
zoom: 15
});
var request = {
placeId: 'ChIJN1t_tDeuEmsRUsoyG83frY4'
};
infowindow = new google.maps.InfoWindow();
service = new google.maps.places.PlacesService(map);
service.getDetails(request, function(place, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
createMarker(place)
}
});
}
function createMarker(place) {
var image = 'img/marker.png';
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
//icon: image,
position: place.geometry.location
});
var request = {
reference: place.reference
};
service.getDetails(request, function(details, status) {
google.maps.event.addListener(marker, 'click', function() {
if (status == google.maps.places.PlacesServiceStatus.OK) {
// Replace empty spaces in navigation link with + symbols
var navLink = details.formatted_address;
navLink = navLink.replace(/\s/g, "+");
$('.navLink').html(navLink);
// Match Rating bar width to rating number
var ratingWidth = (details.rating * 20) + "px";
$('.rating-bar > span').css('width', "'" + ratingWidth + "'");
var contentStr = '<h5 class="info-window-title">' + details.name + '</h5><ul class="info-window">';
if (!!details.rating) contentStr += '<li>Rating: <div class="rating-bar"><span style=width:' + ratingWidth + '></span></div><strong>' + details.rating + '</strong></li>';
if (!!details.open_now) contentStr += '<li class="open-now">' + details.open_now + '</li>';
contentStr += '<li>' + details.formatted_address + '</li>';
contentStr += '<li class=gray>' + details.types + '</li>';
// Check for platform to send appropriate app link
if ((navigator.platform.indexOf("iPhone") != -1)) {
contentStr += '<li class="link"><a class=navLink href=http://maps.apple.com/?daddr=Current+Location&saddr=' + navLink + '><i class="fa fa-automobile"></i> Get Directions</a></li>';
} else {
contentStr += '<li class="link"><a class=navLink href=https://www.google.com/maps/dir/Current+Location/' + navLink + '><i class="fa fa-automobile"></i> Get Directions</a></li>';
}
if (!!details.formatted_phone_number) contentStr += '<li class="link"><i class="fa fa-phone"></i> ' + details.formatted_phone_number + '</li>';
if (!!details.reviews && details.reviews.length) {
contentStr += '<li>Reviews' +
(function(rs /*reviews-array*/ , fx /*review-parser*/ ) {
var list = document.createElement('ul');
rs.forEach(function(r) {
list.appendChild(fx(r));
});
return '<ul>' + list.innerHTML + '</ul>';
//remove the previous line when you want to return a DOMNode
return list;
}
(details.reviews,
function(r /*single review*/ ) {
console.log(r.aspects)
var item = document.createElement('li'),
review = item.appendChild(document.createElement('ul'))
props = {
author_name: 'author',
rating: 'rating',
text: 'text'
};
item.appendChild(document.createElement('h6'));
item.lastChild.appendChild(document.createElement('a'));
item.lastChild.lastChild
.appendChild(document.createTextNode(r.author_name));
if (r.author_url) {
item.lastChild.lastChild.setAttribute('href', r.author_url);
}
item.lastChild.appendChild(document.createTextNode('(' + r.rating +
')'));
if (r.aspects && r.aspects.length) {
item.appendChild(document.createElement('ul'));
r.aspects.forEach(function(a) {
item.lastChild.appendChild(document.createElement(
'li'));
item.lastChild.lastChild
.appendChild(document.createTextNode(a.type +
':' + a.rating))
});
}
item.appendChild(document.createElement('p'));
item.lastChild.appendChild(document.createTextNode(r.text));
return item;
}
))
+ '</li>';
}
contentStr += '</ul>';
console.log(contentStr)
infowindow.setContent(contentStr);
infowindow.open(map, marker);
} else {
var contentStr = "<h5>No Result, status=" + status + "</h5>";
infowindow.setContent(contentStr);
infowindow.open(map, marker);
}
});
});
}
google.maps.event.addDomListener(window, 'load', initialize);
html,
body,
#map-canvas {
height: 100%;
margin: 0px;
padding: 0px
}
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?v=3&libraries=places"></script>
<div id="map-canvas"></div>

fusion table issues with onClick and custom icons

I am trying to get layers to click on and off by using a checkbox, but for some reason I am missing something and can not get it to click on and off again. I also would like to add custom markers for each layer but have not succeeded in doing that at all.
Here is the code I am working with. I would appreciate any help on this I am so new to working with this code.
var map;
var layerl0;
var layerl1;
function initialize() {
map = new google.maps.Map(document.getElementById('map-canvas'), {
center: new google.maps.LatLng(62.683556,-152.314453),
zoom: 4,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
layerl0 = new google.maps.FusionTablesLayer({
query: {
select: "'col0'",
from: '1suBUHqahw5W9f6A6kEVhh-NWmqSbukYqdtnJLWs'
},
map: map,
styleId: 2,
templateId: 3
});
layerl1 = new google.maps.FusionTablesLayer({
query: {
select: "'col0'",
from: '1ra3TP6cbWmdAOayLgzCugLrhdmDAO6UJIFuty9E'
},
map: map,
styleId: 2,
templateId: 3
});
}
function changeMapl0() {
var searchString = document.getElementById('search-string-l0').value.replace(/'/g, "\\'");
layerl0.setOptions({
query: {
select: "'col0'",
from: '1suBUHqahw5W9f6A6kEVhh-NWmqSbukYqdtnJLWs',
where: "'category' = '" + searchString + "'"
}
});
}
function changeMapl1() {
var searchString = document.getElementById('search-string-l1').value.replace(/'/g, "\\'");
layerl1.setOptions({
query: {
select: "'col0'",
from: '1ra3TP6cbWmdAOayLgzCugLrhdmDAO6UJIFuty9E',
where: "'category' = '" + searchString + "'"
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas"></div>
<div style="margin-top: 10px;">
<form>
<input type="checkbox" value="CRCD" checked="checked" id="search-string-l0" onClick="changeMapl0(this.value);">CRCD Learning Centers
<input type="checkbox" value="Research" checked="checked" id="search-string-l1" onClick="changeMapl1(this.value);">Off-site Research
</form>
</div>
Your problem is that your changeMap functions don't actually do anything based on the value of the checkbox:
function changeMapl0() {
var searchString = document.getElementById('search-string-l0').value.replace(/'/g, "\\'");
layerl0.setOptions({
query: {
select: "'col0'",
from: '1suBUHqahw5W9f6A6kEVhh-NWmqSbukYqdtnJLWs',
where: "'category' = '" + searchString + "'"
}
});
}
Try this instead:
function changeMapl0() {
if (document.getElementById('search-string-l0').checked )
{ layerl0.setMap(map); }
else
{ layerl0.setMap(null); }
}
Working example

Resources