I would like to create pdfs in OpenLayers with specifis scales.
I know the example how to print pdfs in DinA4 or DinA3.
var dims = {
a3: [420, 297],
a4: [297, 210],
a5: [210, 148]
};
But so far I didn`t get it to create maps in a specific sacle (e.g. 1:1000 in meters).
Could anybody give me a hint please?
Thank you for the hint.
In OL5 it works great with that (just a little bit changed) code from the above mentioned example:
import Map from 'ol/Map.js';
import View from 'ol/View.js';
import {getCenter} from 'ol/extent.js';
import {transform} from 'ol/proj.js';
import TileLayer from 'ol/layer/Tile.js';
import OSM from 'ol/source/OSM.js';
import WKT from 'ol/format/WKT.js';
import {defaults as defaultControls} from 'ol/control.js';
import {ScaleLine} from 'ol/control.js';
import ImageLayer from 'ol/layer/Image.js';
import ImageWMS from 'ol/source/ImageWMS.js';
import TileWMS from 'ol/source/TileWMS.js';
import Static from 'ol/source/ImageStatic.js';
import * as proj4 from 'ol/proj';
import proj4 from 'proj4';
import {register} from 'ol/proj/proj4.js';
import {get as getProjection} from 'ol/proj';
import BingMaps from 'ol/source/BingMaps.js';
import * as olProj from 'ol/proj';
import GeoJSON from 'ol/format/GeoJSON.js';
import VectorLayer from 'ol/layer/Vector.js';
import VectorSource from 'ol/source/Vector.js';
import {Circle as CircleStyle,Fill, Stroke, Style, Text} from 'ol/style.js';
proj4.defs('EPSG:25832', '+proj=utm +zone=32 +x_0=-32000000 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs');
register(proj4);
const utm32n = transform([7.7,52.2], 'EPSG:4326', 'EPSG:25832');
function getURLParameter(name) {
return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search) || [null, ''])[1].replace(/\+/g, '%20')) || null;
}
var mzoom=12;
var rechtswert = Number(getURLParameter('rechtswert'));
var hochwert = Number(getURLParameter('hochwert'));
var mzoom = Number(getURLParameter('zoom'));
if (rechtswert == 0 || hochwert == 0) {
rechtswert = 412989; hochwert = 5791597; mzoom=18;
}
if (mzoom == 0 ) { mzoom=18
}
var osm = new TileLayer({
source: new OSM()
});
var bingMapsAerial = new TileLayer({
preload: Infinity,
source: new BingMaps({
key: 'AqpsHuO0V-IoueH******************wj0w38QDNe5cVMeZtF-4VMlu4CM8oN',
imagerySet: 'Aerial',
})
});
var view = new View({
center: [rechtswert,hochwert],
zoom: mzoom,
projection: 'EPSG:25832'
});
var map = new Map({
layers: [osm,bingMapsAerial],
target: 'map',
view: view
});
map.addControl(new ScaleLine({units: 'metric'}));
var zoom = view.getZoom();
function openInNewTab(url) {
var win = window.open(url, '_blank');
win.focus();
}
var dims = {
a0: [1189, 841],
a1: [841, 594],
a2: [594, 420],
a3: [420, 297],
a4: [297, 210],
a5: [210, 148]
};
var exportButton = document.getElementById('export-pdf');
exportButton.addEventListener('click', function() {
exportButton.disabled = true;
document.body.style.cursor = 'progress';
var format = document.getElementById('format').value;
var resolution = document.getElementById('resolution').value;
var scale = document.getElementById('scale').value;
var dim = dims[format];
var width = Math.round(dim[0] * resolution / 25.4);
var height = Math.round(dim[1] * resolution / 25.4);
var size = map.getSize();
var viewResolution = map.getView().getResolution();
var scaleResolution = scale / olProj.getPointResolution(map.getView().getProjection(), resolution / 25.4, map.getView().getCenter());
map.once('rendercomplete', function(event) {
var canvas = event.context.canvas;
var data = canvas.toDataURL('image/jpeg');
var pdf = new jsPDF('landscape', undefined, format);
pdf.addImage(data, 'JPEG', 0, 0, dim[0], dim[1]);
pdf.save('map.pdf');
// Reset original map size
map.setSize(size);
map.getView().setResolution(viewResolution);
exportButton.disabled = false;
document.body.style.cursor = 'auto';
});
// Set print size
var printSize = [width, height];
map.setSize(printSize);
map.getView().setResolution(scaleResolution);
}, false);
And the html-code like:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://openlayers.org/en/v5.3.0/css/ol.css" type="text/css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.2.61/jspdf.min.js"></script>
<meta charset="utf-8">
<title>k,ais test</title>
<style>
#map {
width: 750px;
height: 750px;
}
</style>
</head>
<body>
<div id="map" class="map"></div>
<form class="form">
<label>Page size </label>
<select id="format">
<option value="a0">A0</option>
<option value="a1">A1</option>
<option value="a2">A2</option>
<option value="a3">A3</option>
<option value="a4" selected>A4</option>
<option value="a5">A5</option>
</select>
<label>Resolution </label>
<select id="resolution">
<option value="72">72 dpi</option>
<option value="150">150 dpi</option>
<option value="200" selected>200 dpi</option>
<option value="300">300 dpi</option>
</select>
<label>Scale </label>
<select id="scale">
<option value="500">1:500000</option>
<option value="250" selected>1:250000</option>
<option value="100">1:100000</option>
<option value="50">1:50000</option>
<option value="25">1:25000</option>
<option value="10">1:10000</option>
</select>
</form>
<button id="export-pdf">Export PDF</button>
...
....
Related
I have a google maps piece of code that gets my current location to a fixed destination but the width and height of the view wont stay the same after i click on the button to get the directions and it looks very unprofessional
The width and height changes once i click on the button. I want the size of the maps to stay the same as before i click the button and once i click the button the size of the maps should remain the same as before and not change
This is the code i have:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<h2>Our Location</h2>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=AIzaSyC6v5-2uaq_wusHDktM9ILcqIrlPtnZgEk&sensor=false">
</script>
<script type="text/javascript">
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(success);
} else {
alert("There is Some Problem on your current browser to get Geo Location!");
}
function success(position) {
var lat = position.coords.latitude;
var long = position.coords.longitude;
var city = position.coords.locality;
var LatLng = new google.maps.LatLng(lat, long);
var mapOptions = {
center: LatLng,
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("MyMapLOC"), mapOptions);
var marker = new google.maps.Marker({
position: LatLng,
title: "<div style = 'height:60px;width:200px'><b>You Are Here:</b><br />Latitude: "
+ lat + +"<br />Longitude: " + long
});
marker.setMap(map);
var getInfoWindow = new google.maps.InfoWindow({ content: "<b>Your Current Location</b><br/> Latitude:" +
lat + "<br /> Longitude:" + long + ""
});
getInfoWindow.open(map, marker);
}
</script>
<script type="text/javascript">
function SearchRoute() {
document.getElementById("MyMapLOC").style.display = 'none';
var markers = new Array();
var myLatLng;
//Find the current location of the user.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(p) {
var myLatLng = new google.maps.LatLng(p.coords.latitude, p.coords.longitude);
var m = {};
m.title = "Your Current Location";
m.lat = p.coords.latitude;
m.lng = p.coords.longitude;
markers.push(m);
//Find Destination address location.
var address = document.getElementById("txtDestination").value;
var geocoder = new google.maps.Geocoder();
geocoder.geocode({ 'address': address }, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
m = {};
m.title = address;
m.lat = results[0].geometry.location.lat();
m.lng = results[0].geometry.location.lng();
markers.push(m);
var mapOptions = {
center: myLatLng,
zoom: 4,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("MapRoute"), mapOptions);
var infoWindow = new google.maps.InfoWindow();
var lat_lng = new Array();
var latlngbounds = new google.maps.LatLngBounds();
for (i = 0; i < markers.length; i++) {
var data = markers[i];
var myLatlng = new google.maps.LatLng(data.lat, data.lng);
lat_lng.push(myLatlng);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: data.title
});
latlngbounds.extend(marker.position);
(function(marker, data) {
google.maps.event.addListener(marker, "click", function(e) {
infoWindow.setContent(data.title);
infoWindow.open(map, marker);
});
})(marker, data);
}
map.setCenter(latlngbounds.getCenter());
map.fitBounds(latlngbounds);
//***********ROUTING****************//
//Initialize the Path Array.
var path = new google.maps.MVCArray();
//Getting the Direction Service.
var service = new google.maps.DirectionsService();
//Set the Path Stroke Color.
var poly = new google.maps.Polyline({ map: map, strokeColor: '#4986E7' });
//Loop and Draw Path Route between the Points on MAP.
for (var i = 0; i < lat_lng.length; i++) {
if ((i + 1) < lat_lng.length) {
var src = lat_lng[i];
var des = lat_lng[i + 1];
path.push(src);
poly.setPath(path);
service.route({
origin: src,
destination: des,
travelMode: google.maps.DirectionsTravelMode.DRIVING
}, function(result, status) {
if (status == google.maps.DirectionsStatus.OK) {
for (var i = 0, len = result.routes[0].overview_path.length; i < len; i++) {
path.push(result.routes[0].overview_path[i]);
}
} else {
alert("Invalid location.");
window.location.href = window.location.href;
}
});
}
}
} else {
alert("Request failed.")
}
});
});
}
else {
alert('Some Problem in getting Geo Location.');
return;
}
}
</script>
</head>
<body>
<form id="SetDirections">
<p>Directions To Elena's Delicacies</p>
<p>
<b>Elena's Delicacies Address:</b>
<input type="text" id="txtDestination" value="499 Paradise Valey Pinetown" style="width: 300px"disabled readonly />
<input type="button" value="Directions" onclick="SearchRoute()" />
</p>
<div id="MyMapLOC" style="width: 100%; height: 600px">
</div>
<div id="MapRoute" style="width: 500px; height: 500px">
</div>
</form>
</body>
</html>
I have a form with more than one dropdown list, like this below. I can see how to get the ID's of each dropdown but I can't figure out how to get the one that was actually used. Would someone explain how to do that, please.
<div>
<select name="id[11]" class="pullDown" id="attrdrop0">
<option class="pink" value="31`">No</option>
<option class="pink" value="32">Yes (+$40.00)</option>
</select>
</div>
<div>
<select name="id[10]" class="pullDown" id="attrdrop1">
<option class="pink" value="31">No</option>
<option class="pink" value="32">Yes (+$150.00)</option>
</select>
</div>
<script>
$(function () {
$("#prices").change(function () {
console.log('A change was made');
CalculatePrice();
});
});
function CalculatePrice() {
var ttl_price = 0;
var id = '';
$(":input.select, :input").each(function() {
var cur_price = $('option:selected', $(this)).text();
ttl_price += cur_price;
id = $(this).attr('id');
/*** What now ***/
});
SetPrice(id, ttl_price);
}
</script>
You can pass the control as a parameter to CalculatePrice.
$(function () {
$("#prices").change(function () {
console.log('A change was made');
CalculatePrice(this);
});
});
function CalculatePrice(triggerObject) {
var ttl_price = 0;
var id = '';
$(":input.select, :input").each(function() {
var cur_price = $('option:selected', $(this)).text();
ttl_price += cur_price;
id = $(this).attr('id');
/*** What now ***/
if (triggerObject.id) {...}
});
SetPrice(id, ttl_price);
}
</script>
I have Fusion Table data that I would like to map on a web page and give users the ability to filter the geopoints using selection menus based on data in columns. I can do this using one column from the Fusion Table but I can't figure out how to do this using two or more columns. i.e./e.g. They can select/filter a column called 'Program' for entries labelled with 'GypsyMoth' and then further filter all these entries for 'TrapRteList' entries labelled 'NE'.
I have tried many, many ways of accomplishing this but so far no luck. Below is my best attempt but it will only select data from TrapRteList. How can get two column selections to update the map? I'm not a programmer (obviously) and have been banging my head against a wall for awhile now. None of the solutions I've found seem to work quite the way I want them to. Any help would be appreciated. Thank you.
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="UTF-8">
<title>Tree Traps Map</title>
<style>
#map-canvas { width:1080px; height:768px; }
.layer-wizard-search-label { font-family: sans-serif };
</style>
<script type="text/javascript"
src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
function initialize() {
var pointTableID = '1EADJbmeOJj60i_jIMDPNwVt0SMYEwYsw8kuU3nwI';
var pointColumn = 'GPSpoint';
var map = new google.maps.Map(document.getElementById('map-canvas'), {
center: new google.maps.LatLng(53.637692, -113.422068),
zoom: 10,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
// Initialize the points layer
var pointsLayer = new google.maps.FusionTablesLayer({
query: {
select: pointColumn,
from: pointTableID
},
map: map,
styleId: 2,
templateId: 2
});
// -----------------------------------
google.maps.event.addDomListener(document.getElementById('Program'),
'change', function() {
updateMap(pointsLayer, pointTableID, pointColumn);
});
google.maps.event.addDomListener(document.getElementById('TrapRteList'),
'change', function() {
updateMap(pointsLayer, pointTableID, pointColumn);
});
}
// Update the query sent to the Fusion Table Layer based on
// the user selection in the select menu
function updateMap(pointsLayer, pointTableID, pointColumn) {
var Program = document.getElementById('Program').value;
if (Program) {
pointsLayer.setOptions({
query: {
select: pointColumn,
from: pointTableID,
where: "Program = '" + Program + "'"
}
});
} else {
pointsLayer.setOptions({
query: {
select: pointColumn,
from: pointTableID
}
});
}
var TrapRteList = document.getElementById('TrapRteList').value;
if (TrapRteList) {
pointsLayer.setOptions({
query: {
select: pointColumn,
from: pointTableID,
where: "TrapRteList = '" + TrapRteList + "'"
}
});
} else {
pointsLayer.setOptions({
query: {
select: pointColumn,
from: pointTableID
}
});
}
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<p style="margin-left:auto; margin-right:auto; margin-top:0.25em; margin-bottom:0.25em; width:20%; font-size:14pt; font-weight:bold;">Trapping Program</p>
<label style="font-size:11pt; font-weight:bold;">Select trapping program: </label>
<select id="Program">
<option value="--Select--">--Select--</option>
<option value="">(no value)</option>
<option value="Apanteles">Apanteles</option>
<option value="AshBorer">Ash (or Lilac) Borer</option>
<option value="EBB-Banded">Banded Elm Bark Beetle</option>
<option value="EBB">Elm Bark Beetle</option>
<option value="EmeraldAshBorer">Emerald Ash Borer</option>
<option value="GypsyMoth">Gypsy Moth</option>
<option value="InvasiveAliens">Invasive Alien Species</option>
<option value="MountainPineBeetle">Mountain Pine Beetle</option>
<option value="Sirix">Sirix</option>
<option value="UglynestCaterpillar">Uglynest Caterpillar</option>
<option value="Other:">Other Program</option>
</select>
<label style="font-size:11pt; font-weight:bold;">Select trap route: </label>
<select id="TrapRteList">
<option value="--Select--">--Select--</option>
<option value="">(no value)</option>
<option value="NE">Northeast</option>
<option value="NW">Northwest</option>
<option value="SE">Southeast</option>
<option value="SW">Southwest</option>
<option value="OuterCommunity">Outer Community</option>
<option value="Other:">Other</option>
</select>
<div id="map-canvas"></div>
</body>
</html>
This should be sufficient:
function updateMap(pointsLayer, pointTableID, pointColumn) {
var o={
Program : document.getElementById('Program').value,
TrapRteList : document.getElementById('TrapRteList').value
},where=[];
for(var k in o){
if(o[k]){
where.push(k+"='"+o[k]+"'");
}
}
pointsLayer.setOptions({
query: {
select: pointColumn,
from: pointTableID,
where: where.join(' and ')
}
});
}
Note: all options that shouldn't be used for filtering must have an value which evaluates to false , e.g. a empty string.
I need to implement a select similar to this http://www.erichynds.com/examples/jquery-ui-multiselect-widget/demos/
I want to use select2 for this, but I haven't been able to find anything from the creator of the select2 that would support this style of dropdown with checkboxes in it. Does anyone know a way to do this?
I've faced a similar need but was not able to find it.
The solution I've came across was using the flag closeOnSelect set to false
$("#yadayada").select2({closeOnSelect:false});
http://jsfiddle.net/jEADR/521/
Seems this is old post, but as it is very common issue, I`m posting this here.
I found that the author already added a plugin to select2 for this feature to have checkbox-like selection and the dropdown does not hide on click:
https://github.com/wasikuss/select2-multi-checkboxes
Example:
$('.select2-multiple').select2MultiCheckboxes({
placeholder: "Choose multiple elements",
})
http://jsfiddle.net/wasikuss/gx93rwnk/
All other features of select2 are preserved. There are few more predefined options set to work properly.
I managed to put something together, not perfect, but it works.
https://jsfiddle.net/Lkkm2L48/7/
jQuery(function($) {
$.fn.select2.amd.require([
'select2/selection/single',
'select2/selection/placeholder',
'select2/selection/allowClear',
'select2/dropdown',
'select2/dropdown/search',
'select2/dropdown/attachBody',
'select2/utils'
], function (SingleSelection, Placeholder, AllowClear, Dropdown, DropdownSearch, AttachBody, Utils) {
var SelectionAdapter = Utils.Decorate(
SingleSelection,
Placeholder
);
SelectionAdapter = Utils.Decorate(
SelectionAdapter,
AllowClear
);
var DropdownAdapter = Utils.Decorate(
Utils.Decorate(
Dropdown,
DropdownSearch
),
AttachBody
);
var base_element = $('.select2-multiple2')
$(base_element).select2({
placeholder: 'Select multiple items',
selectionAdapter: SelectionAdapter,
dropdownAdapter: DropdownAdapter,
allowClear: true,
templateResult: function (data) {
if (!data.id) { return data.text; }
var $res = $('<div></div>');
$res.text(data.text);
$res.addClass('wrap');
return $res;
},
templateSelection: function (data) {
if (!data.id) { return data.text; }
var selected = ($(base_element).val() || []).length;
var total = $('option', $(base_element)).length;
return "Selected " + selected + " of " + total;
}
})
});
});
CSS:
.select2-results__option .wrap:before{
font-family:fontAwesome;
color:#999;
content:"\f096";
width:25px;
height:25px;
padding-right: 10px;
}
.select2-results__option[aria-selected=true] .wrap:before{
content:"\f14a";
}
Add just two emoji with css
.select2-results__options {
&[aria-multiselectable=true] {
.select2-results__option {
&[aria-selected=true]:before {
content: '☑';
padding: 0 0 0 4px;
}
&:before {
content: '◻';
padding: 0 0 0 4px;
}
}
}
}
You see this sample a RTL select2 with emoji based checkbox
Here is very simple snippet, without strange modyfing of js - pure and simple css (with "Font Awesome")
$('.select2[multiple]').select2({
width: '100%',
closeOnSelect: false
})
#body{
padding: 30px
}
.select2-results__options[aria-multiselectable="true"] li {
padding-left: 30px;
position: relative
}
.select2-results__options[aria-multiselectable="true"] li:before {
position: absolute;
left: 8px;
opacity: .6;
top: 6px;
font-family: "FontAwesome";
content: "\f0c8";
}
.select2-results__options[aria-multiselectable="true"] li[aria-selected="true"]:before {
content: "\f14a";
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.10/css/select2.min.css" rel="stylesheet"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.11.2/css/all.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.10/js/select2.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.11.2/js/all.min.js"></script>
<div id="body">
<select name="fabric_color_en[]" id="fabric_color_en[]" multiple="multiple" class="form-control select2">
<option value="Beige">
Beige
</option>
<option value="Red">
Red
</option>
<option value="Petrol">
Petrol
</option>
<option value="Royal Blue">
Royal Blue
</option>
<option value="Dark Blue">
Dark Blue
</option>
<option value="Bottle Green">
Bottle Green
</option>
<option value="Light Grey">
Light Grey
</option>
</select>
</div>
Now the code is ready to use for you to implement the multiple checkboxes select2 dropdown.
Enjoy :)
//===============================================
//Start - Select 2 Multi-Select Code======================================================
var Select2MultiCheckBoxObj = [];
var id_selectElement = 'id_SelectElement';
var staticWordInID = 'state_';
function AddItemInSelect2MultiCheckBoxObj(id, IsChecked) {
if (Select2MultiCheckBoxObj.length > 0) {
let index = Select2MultiCheckBoxObj.findIndex(x => x.id == id);
if (index > -1) {
Select2MultiCheckBoxObj[index]["IsChecked"] = IsChecked;
}
else {
Select2MultiCheckBoxObj.push({ "id": id, "IsChecked": IsChecked });
}
}
else {
Select2MultiCheckBoxObj.push({ "id": id, "IsChecked": IsChecked });
}
}
function IsCheckedAllOption(trueOrFalse) {
$.map($('#' + id_selectElement + ' option'), function (option) {
AddItemInSelect2MultiCheckBoxObj(option.value, trueOrFalse);
});
$('#' + id_selectElement + " > option").not(':first').prop("selected", trueOrFalse); //This will select all options and adds in Select2
$("#" + id_selectElement).trigger("change");//This will effect the changes
$(".select2-results__option").not(':first').attr("aria-selected", trueOrFalse); //This will make grey color of selected options
$("input[id^='" + staticWordInID + "']").prop("checked", trueOrFalse);
}
$(document).ready(function () {
//Begin - Select 2 Multi-Select Code
$.map($('#' + id_selectElement + ' option'), function (option) {
AddItemInSelect2MultiCheckBoxObj(option.value, false);
});
function formatResult(state) {
if (Select2MultiCheckBoxObj.length > 0) {
var stateId = staticWordInID + state.id;
let index = Select2MultiCheckBoxObj.findIndex(x => x.id == state.id);
if (index > -1) {
var checkbox = $('<div class="checkbox"><input class="select2Checkbox" id="' + stateId + '" type="checkbox" ' + (Select2MultiCheckBoxObj[index]["IsChecked"] ? 'checked' : '') +
'><label for="checkbox' + stateId + '">' + state.text + '</label></div>', { id: stateId });
return checkbox;
}
}
}
let optionSelect2 = {
templateResult: formatResult,
closeOnSelect: false,
width: '100%'
};
let $select2 = $("#" + id_selectElement).select2(optionSelect2);
//var scrollTop;
//$select2.on("select2:selecting", function (event) {
// var $pr = $('#' + event.params.args.data._resultId).parent();
// scrollTop = $pr.prop('scrollTop');
// let xxxx = 2;
//});
$select2.on("select2:select", function (event) {
$("#" + staticWordInID + event.params.data.id).prop("checked", true);
AddItemInSelect2MultiCheckBoxObj(event.params.data.id, true);
//If all options are slected then selectAll option would be also selected.
if (Select2MultiCheckBoxObj.filter(x => x.IsChecked === false).length === 1) {
AddItemInSelect2MultiCheckBoxObj(0, true);
$("#" + staticWordInID + "0").prop("checked", true);
}
});
$select2.on("select2:unselect", function (event) {
$("#" + staticWordInID + "0").prop("checked", false);
AddItemInSelect2MultiCheckBoxObj(0, false);
$("#" + staticWordInID + event.params.data.id).prop("checked", false);
AddItemInSelect2MultiCheckBoxObj(event.params.data.id, false);
});
$(document).on("click", "#" + staticWordInID + "0", function () {
//var b = !($("#state_SelectAll").is(':checked'));
var b = $("#" + staticWordInID + "0").is(':checked');
IsCheckedAllOption(b);
//state_CheckAll = b;
//$(window).scroll();
});
$(document).on("click", ".select2Checkbox", function (event) {
let selector = "#" + this.id;
let isChecked = Select2MultiCheckBoxObj[Select2MultiCheckBoxObj.findIndex(x => x.id == this.id.replaceAll(staticWordInID, ''))]['IsChecked'];
$(selector).prop("checked", isChecked);
});
});
//====End - Select 2 Multi-Select Code==
<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/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#4.6.0/dist/js/bootstrap.bundle.min.js" integrity="undefined" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/js/select2.min.js"></script>
<div class="container-fluid">
<hr/>
<p>Here, you can select any item by clicking on row or checked in on checkbox and can unselect in reverse way.</p>
<p>But I didn't give the option to select "SelectAll" option by clicking on his row, you can select-all and unselect-all by click on checkbox only rather than row.</p>
<div class="row" style="width:50%">
<label for="id_SelectElement" class="col-sm-2">Part Name: </label>
<div class="col-sm-4">
<select id="id_SelectElement" placeholder="Select Text" multiple>
<option value="0" disabled>Select All</option>
<option value="11">Php</option>
<option value="22">Bootstrap</option>
<option value="33">sql</option>
<option value="44">Node Js</option>
<option value="55">Laravel</option>
<option value="66">Jquery</option>
<option value="77">React</option>
<option value="88">Vew.JS</option>
<option value="99">MVC</option>
<option value="10">DotNetCore</option>
<option value="12">Java</option>
<option value="13">Artifical Intiligence</option>
<option value="14">Data Structure</option>
<option value="15">Data Science</option>
<option value="16">Robotics</option>
<option value="17">Node Js 2</option>
<option value="18">Laravel 23</option>
<option value="19">Jquery 3.4</option>
</select>
</div>
</div>
</div>
Another workaround is to "prepend" checkbox icons using CSS. I use bootstrap theme - your select2-container may be different.
.select2-container--bootstrap .select2-results__option[aria-selected=true]:before { content:'\e067 '; padding:0 8px 0 0px; font-family:'Glyphicons Halflings' }
.select2-container--bootstrap .select2-results__option:before { content:'\e157 '; padding:0 8px 0 0px; font-family:'Glyphicons Halflings' }
Using generated code from FusionTablesLayer Wizard, I am trying to determine how to open the info window onchange. The code below displays the marker perfectly, but I would like the info window to open when a different selection (state) is selected, rather than clicking on the marker to trigger info window. Thanks.
Followup:
Following geocodezip's remarks below, the following code works well and has given me a great start! Now to use drop down selector rather than sidebar links...
New working code
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Fusion Table Markers and Sidebar</title>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
google.load('visualization', '1', {'packages':['table']});
var map;
var markers = [];
var infoWindow = new google.maps.InfoWindow();
function initialize() {
var us = new google.maps.LatLng(38.24676420846342, -94.82073772499997);
map = new google.maps.Map(document.getElementById('map_canvas'), {
center: us,
zoom: 4,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
//sidebar to contain link to map marker - Sales Region - and Rep name
var sql = encodeURIComponent("SELECT 'State - Sales Region', 'Representative Contact', Lat, Lon FROM 5555555555 ORDER BY 'State - Sales Region'");
var query = new google.visualization.Query('http://www.google.com/fusiontables/gvizdata?tq=' + sql);
query.send(getData);
}
//simple sidebar and info window style
function getData(response) {
var dt = response.getDataTable();
var side_html = '<table style="border-collapse: collapse" border="1" \
cellpadding="5"> \
<thead> \
<tr style="background-color:#e0e0e0"> \
<th>Area</th> \
<th>Name</th> \
</tr> \
</thead> \
<tbody>';
for (var i = 0; i < dt.getNumberOfRows(); i++) {
var lat = dt.getValue(i,2);
var lng = dt.getValue(i,3);
var area = dt.getValue(i,0);
var pop = dt.getValue(i,1);
var pt = new google.maps.LatLng(lat, lng);
var html = "<strong>" + area + "</strong><br />" + pop;
side_html += '<tr> \
<td>' + area + '</td> \
<td>' + pop + '</td> \
</tr>';
createMarker(pt, html);
}
side_html += '</tbody> \
</table>';
document.getElementById("side_bar").innerHTML = side_html;
}
//use simple default marker
function createMarker(point,info) {
var marker = new google.maps.Marker({
position: point,
map: map
});
markers.push(marker);
google.maps.event.addListener(marker, 'click', function() {
infoWindow.close();
infoWindow.setContent(info);
infoWindow.open(map,marker);
});
}
function myclick(num) {
google.maps.event.trigger(markers[num], "click");
map.setCenter(markers[num].getPosition());
// map.setZoom(map.getZoom()+2);
}
</script>
</head>
<body onload="initialize()">
<div id="map_canvas" style="width: 900px; height: 600px; position: absolute; left: 10px"></div>
<div id="side_bar" style="width: 200px; height: 600px; position: absolute; left: 920px; overflow: auto;"></div>
</body>
</html>
The only way to open an InfoWindow on a FusionTablesLayer by default is to click on it. To open it from an external event, one option is to create your own InfoWindow. retrieving the content by querying the FusionTable and opening on whatever external stimulus you want.
Example/proof of concept with a sidebar
Example from the documentation