I have implemented the accepted answer to this Question. When I run the html file, the text which I'm writing over the Google Map marker is displayed in wrong location (Refer the picture error.png). Can anyone help me to display the text exactly over the marker?.
Marker.html
<html><head>
<title> Hi </title>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
function TxtOverlay(pos, txt, cls, map){
this.pos = pos;
this.txt_ = txt;
this.cls_ = cls;
this.map_ = map;
this.div_ = null;
this.setMap(map);
}
TxtOverlay.prototype = new google.maps.OverlayView();
TxtOverlay.prototype.onAdd = function(){
var div = document.createElement('DIV');
div.className = this.cls_;
div.innerHTML = this.txt_;
var overlayProjection = this.getProjection();
var position = overlayProjection.fromLatLngToDivPixel(this.pos);
div.style.left = ( position.x) + 'px';
div.style.top = ( position.y)+ 'px';
var panes = this.getPanes();
panes.floatPane.appendChild(div);
}
TxtOverlay.prototype.draw = function(){
var overlayProjection = this.getProjection();
var position = overlayProjection.fromLatLngToDivPixel(this.pos);
var div = this.div_;
div.style.left = ( position.x) + 'px';
div.style.top = ( position.y)+ 'px';
}
TxtOverlay.prototype.onRemove = function(){
this.div_.parentNode.removeChild(this.div_);
this.div_ = null;
}
TxtOverlay.prototype.hide = function(){
if (this.div_) {
this.div_.style.visibility = "hidden";
}
}
TxtOverlay.prototype.show = function(){
if (this.div_) {
this.div_.style.visibility = "visible";
}
}
TxtOverlay.prototype.toggle = function(){
if (this.div_) {
if (this.div_.style.visibility == "hidden") {
this.show();
}
else {
this.hide();
}
}
}
TxtOverlay.prototype.toggleDOM = function(){
if (this.getMap()) {
this.setMap(null);
}
else {
this.setMap(this.map_);
}
}
var map;
function init(){
var latlng = new google.maps.LatLng(37.90695894, -122.07920128);
var myOptions = {
zoom: 4,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map"), myOptions);
var marker = new google.maps.Marker({
position: latlng,
map: map,
title: "Hello World!",
icon:"./bluepin.PNG"
});
customTxt = "<div>1</div>"
txt = new TxtOverlay(latlng,customTxt,"customBox",map )
}
</script>
<style>
.customBox {
background: AARRGGBB;
border: 1px;
color:#ffffff;
position: relative;
}
</style>
</head>
<body onload="init()">
<div id="map" style="width: 600px; height: 600px;">
</div>
</body>
</html>
You need to offset the div so it appears over the marker. An offset of (-5, -30) works for this marker and the number "1".
function TxtOverlay(pos, txt, cls, map, offset){
this.pos = pos;
this.txt_ = txt;
this.cls_ = cls;
this.map_ = map;
this.offset_ = offset;
this.div_ = null;
this.setMap(map);
}
TxtOverlay.prototype.onAdd = function(){
var div = document.createElement('DIV');
div.className = this.cls_;
div.innerHTML = this.txt_;
this.div_ = div;
var overlayProjection = this.getProjection();
var position = overlayProjection.fromLatLngToDivPixel(this.pos);
div.style.left = ( position.x + this.offset_.x) + 'px';
div.style.top = ( position.y + this.offset_.y)+ 'px';
var panes = this.getPanes();
panes.floatPane.appendChild(div);
}
TxtOverlay.prototype.draw = function(){
var overlayProjection = this.getProjection();
var position = overlayProjection.fromLatLngToDivPixel(this.pos);
var div = this.div_;
div.style.left = ( position.x + this.offset_.x) + 'px';
div.style.top = ( position.y + this.offset_.y)+ 'px';
}
txt = new TxtOverlay(latlng,customTxt,"customBox",map,new google.maps.Point(-5,-30) )
Example
you might also look atthe MarkerWithLabel utility library
Example
Related
i have problem, MarkerCluster undefined content from Markers.
I used MarkerCluster in same address (location) gridSize: 1
If pressing Cluster zoomOnClick:false, Cluster must getMarkers content
and open infowindow. but I get undefined undefined .
I chink this problem on this
google.maps.event.addListener(markerCluster, 'clusterclick', function(cluster) {
var markers = cluster.getMarkers();
var content = '';
for (var i = 0; i < markers.length; i++) {
var marker = markers[i];
content += marker.name;
content += ("<br>");
}
var infowindow = new google.maps.InfoWindow();
infowindow.setPosition(cluster.getCenter());
infowindow.close();
infowindow.setContent(content);
infowindow.open(map);
google.maps.event.addListener(map, 'zoom_changed', function() {
infowindow.close();
});
});
Full code:
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
center: new google.maps.LatLng(55.7522200, 37.6155600),
zoom: 11
});
var infoWindow = new google.maps.InfoWindow;
var iconPurple = new google.maps.MarkerImage('mapimages/purple.svg', new google.maps.Size(33, 31));
var iconBlue = new google.maps.MarkerImage('mapimages/blue.svg', new google.maps.Size(33, 31));
var iconYellow = new google.maps.MarkerImage('mapimages/yellow.svg', new google.maps.Size(33, 31));
var iconGreen = new google.maps.MarkerImage('mapimages/green.svg', new google.maps.Size(33, 31));
var iconPink = new google.maps.MarkerImage('mapimages/pink.svg', new google.maps.Size(33, 31));
var iconBrown = new google.maps.MarkerImage('mapimages/brown.svg', new google.maps.Size(33, 31));
var customIcons = [];
customIcons["room1"] = iconPurple;
customIcons["room2"] = iconBlue;
customIcons["room3"] = iconYellow;
customIcons["room4"] = iconGreen;
customIcons["room5"] = iconPink;
customIcons["room6"] = iconBrown;
var options = {
gridSize: 1,
zoomOnClick:false,
imagePath: 'mapimages/m'
};
downloadUrl(markers.php', function(data) {
var xml = data.responseXML;
var markerArray = [];
var markers = xml.documentElement.getElementsByTagName('marker');
Array.prototype.forEach.call(markers, function(markerElem) {
var name = markerElem.getAttribute("name");
var address = markerElem.getAttribute("address");
var metro = markerElem.getAttribute("metro");
var type = markerElem.getAttribute("type");
var date = markerElem.getAttribute("date");
var status = markerElem.getAttribute("status");
var inrequest = markerElem.getAttribute("inrequest");
var phone = markerElem.getAttribute("phone");
var message = markerElem.getAttribute("message");
var area_room = markerElem.getAttribute("area_room");
var price = markerElem.getAttribute("price");
var floore = markerElem.getAttribute("floore");
var floors = markerElem.getAttribute("floors");
var rooms_furniture = markerElem.getAttribute("rooms_furniture");
var kitchen_furniture = markerElem.getAttribute("kitchen_furniture");
var repaint = markerElem.getAttribute("repaint");
var comment = markerElem.getAttribute("comment");
var distance = markerElem.getAttribute("distance");
var point = new google.maps.LatLng(
parseFloat(markerElem.getAttribute('lat')),
parseFloat(markerElem.getAttribute('lng')));
var html = "<h1>" + "м. " + metro + ", " + address + "</h1>"
+ "<h2>" + phone + " " + name + "</h2>"
+ "<h3>" + type + " " + area_room + " м " + price + " р. этаж " + floore + "/" + floors + "</h3>"
+ "<p>" + rooms_furniture + " " + kitchen_furniture + " " + repaint + "</p>"
+ "<h5>" + distance + " " + comment + " " + message + "</h5>" + "<h6>" + date + " " + inrequest + " " + status + "</h6>";
var marker = new google.maps.Marker({
map: map,
position: point,
icon: customIcons[type],
animation: google.maps.Animation.DROP
});
markerArray.push(marker);
marker.addListener('click', function() {
infoWindow.setContent(html);
infoWindow.open(map, marker);
});
});
var markerCluster = new MarkerClusterer(map, markerArray, options);
google.maps.event.addListener(markerCluster, 'clusterclick', function(cluster) {
var markers = cluster.getMarkers();
var content = '';
for (var i = 0; i < markers.length; i++) {
var marker = markers[i];
content += marker.name;
content += ("<br>");
}
var infowindow = new google.maps.InfoWindow();
infowindow.setPosition(cluster.getCenter());
infowindow.close();
infowindow.setContent(content);
infowindow.open(map);
google.maps.event.addListener(map, 'zoom_changed', function() {
infowindow.close();
});
});
});
}
function downloadUrl(url,callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request, request.status);//right here
}
};
request.open('GET', url, true);
request.send(null);
}
function doNothing() {}
enter image description here
The google.maps.Marker objects in the MarkerClusterer are not the same "marker" XML elements you are parsing to create the google.maps.Markers. The won't have a name property, unless you create one.
var marker = new google.maps.Marker({
map: map,
position: point,
icon: customIcons[type],
animation: google.maps.Animation.DROP,
name: name // <-- add this
});
proof of concept fiddle
This js code is for showing customized Google Maps. I want to add function to this code. URL parameter as ID and show infowindow has this ID on Google Maps. For example "http://www.tabikobo.com/newyork/map/uptown/?=2962"(this ID is 2966).ID is loaded as 'id' in XMLdata.
var uptownMap,defLng = -73.963245,defLat = 40.779438,
san ={
init :
function(){
$(document).ready(function(){
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "http://maps.googleapis.com/maps/api/js?sensor=false&callback=san.putGmap";
document.body.appendChild(script);
});
},
putGmap :
function(){
var myLatlng = new google.maps.LatLng(defLat, defLng);
var myOptions = {
zoom: 15,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
uptownMap = new google.maps.Map(document.getElementById("gmapArea"), myOptions);
san.getXmlData();
},
getXmlData : function(){
$.ajax({
type: 'GET',
cache: true,
async: true,
url: '/newyork/map_uptown_xml/',
datatype: 'xml',
success: san.parseXmlData
});
},
parseXmlData: function (xml) {
//a single infowindow for all markers
var infowindow = new google.maps.InfoWindow({
pixelOffset: new google.maps.Size(0, 10)
});
var i = 0,
id, name, url, lat, lng, copy, lead, ename, tag;
$("<ol/>")
.attr('id', 'gmapAnchor')
.appendTo('div#gmapController');
$(xml)
.find('item')
.each(function (i) {
i++;
id = $(this)
.find('description id')
.text();
name = $(this)
.find('description name')
.text();
url = $(this)
.find('description path')
.text();
lat = $(this)
.find('description lat')
.text();
lng = $(this)
.find('description lng')
.text();
tag = $(this)
.find('description tag')
.text();
tag = tag.slice(5, 20);
console.log(tag)
var customIcons = {
hotel:
{
icon: 'http://www.tabikobo.com/newyork/img/icon_hotel.png'
},
var icon = customIcons[tag] || {};
var myLatLng = new google.maps.LatLng(lat, lng);
var beachMarker = new google.maps.Marker({
position: myLatLng,
map: uptownMap,
icon: icon.icon,
});
var htmlTmpl = {
hotel:
{
content: '<div class="infoWinWrapper"><strong><a href="' +
url + '">' + name +
'</a></strong><br />' + ename +
'<br />' + lead + '</div>'
},
};
var htmlTmpl = htmlTmpl[tag] || {};
//click-listener for marker
google.maps.event.addListener(beachMarker, 'click',
function () {
//update the content
infowindow.setContent(
'<div class="hook">' + htmlTmpl
.content + '</div>');
infowindow.open(uptownMap, this);
google.maps.event.addListenerOnce(
infowindow, 'domready',
function () {
var l = $('.hook')
.parent()
.parent()
.parent()
.siblings()
.addClass("infoBox");
});
});
//Creat a Tag
san.putData(name, url, lat, lng, i);
});
},
putData : function(name, url, lat, lng, num){
var x = num;
x += '';
if(x.length == 1){
var y = '0' + x;
}else {
y = x;
}
san.setEvent();
},
setEvent : function(){
$("ul#area_list li a").bind('mouseover', function(){
$(this).parent().find('span.lat').text();
var point = new google.maps.LatLng(
$(this).parent().find('span.lat').text(),
$(this).parent().find('span.lng').text()
);
uptownMap.setZoom(17);
uptownMap.setCenter(point);
});
$("#btnResetZoom a").bind('click', function(){
var point = new google.maps.LatLng(defLat, defLng);
uptownMap.setZoom(15);
uptownMap.setCenter(point);
return false;
});
}
}
window.onload = san.init();
I solived myself! thanks.
var PageMapID = location.href.split('?=');
var PageMapID2 = PageMapID[PageMapID.length -1];
if (id == PageMapID2) {
$(document).ready(function(){
infowindow.open(uptownMap,beachMarker);
infowindow.setContent('<div class="hook">' + htmlTmpl.content + '</div>');
var latlng = new google.maps.LatLng(lat, lng);
uptownMap.setCenter(latlng);
});
}
How do I return a latLng value from a given percentage along a polyLine?
I have spent a day on this using interpolate and individual nodes. Is their an easier function out there that does the grunt work?
Google maps API v3
thanks!
http://www.geocodezip.com/scripts/v3_epoly.js
written for the Google Maps Javascript API v2 ported to v3. Documentation for the v2 version
Has these two methods:
.Distance() returns the length of the poly path
.GetPointAtDistance() returns a GLatLng at the specified distance
along the path.
The distance is specified in metres
Returns null if the path is shorter than that
This should work (if you include that script and your polyline variable is "polyline"):
var latlng = polyline.GetPointAtDistance(polyline.Distance()*(desired percentage)/100);
of course if you polyline isn't changing in length, it would be more efficient to compute the length once an use it each time you want to find a point on the polyline.
var polylength = polyline.Distance();
var latlng = polylength*(desired percentage)/100);
live example
code snippet:
var directionDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
var polyline = null;
var marker;
var infowindow;
function createMarker(latlng, label, html) {
// alert("createMarker("+latlng+","+label+","+html+","+color+")");
var contentString = '<b>' + label + '</b><br>' + html;
var marker = new google.maps.Marker({
position: latlng,
map: map,
title: label,
zIndex: Math.round(latlng.lat() * -100000) << 5,
contentString: contentString
});
marker.myname = label;
// gmarkers.push(marker);
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(this.contentString);
infowindow.open(map, marker);
});
return marker;
}
var myLatLng = null;
var lat;
var lng;
var zoom = 2;
var maptype;
function initialize() {
infowindow = new google.maps.InfoWindow();
myLatLng = new google.maps.LatLng(37.422104808, -122.0838851);
maptype = google.maps.MapTypeId.ROADMAP;
// If there are any parameters at eh end of the URL, they will be in location.search
// looking something like "?marker=3"
// skip the first character, we are not interested in the "?"
var query = location.search.substring(1);
// split the rest at each "&" character to give a list of "argname=value" pairs
var pairs = query.split("&");
for (var i = 0; i < pairs.length; i++) {
// break each pair at the first "=" to obtain the argname and value
var pos = pairs[i].indexOf("=");
var argname = pairs[i].substring(0, pos).toLowerCase();
var value = pairs[i].substring(pos + 1);
// process each possible argname - use unescape() if theres any chance of spaces
if (argname == "filename") {
filename = unescape(value);
}
if (argname == "lat") {
lat = parseFloat(value);
}
if (argname == "lng") {
lng = parseFloat(value);
}
if (argname == "start") {
document.getElementById("start").value = decodeURI(value);
}
if (argname == "end") {
document.getElementById("end").value = decodeURI(value);
}
if (argname == "time") {
document.getElementById("time").value = decodeURI(value);
// putMarkerOnRoute(parseFloat(document.getElementById('time').value));
}
if (argname == "zoom") {
zoom = parseInt(value);
}
if (argname == "type") {
// from the v3 documentation 8/24/2010
// HYBRID This map type displays a transparent layer of major streets on satellite images.
// ROADMAP This map type displays a normal street map.
// SATELLITE This map type displays satellite images.
// TERRAIN This map type displays maps with physical features such as terrain and vegetation.
if (value == "m") {
maptype = google.maps.MapTypeId.ROADMAP;
}
if (value == "k") {
maptype = google.maps.MapTypeId.SATELLITE;
}
if (value == "h") {
maptype = google.maps.MapTypeId.HYBRID;
}
if (value == "t") {
maptype = google.maps.MapTypeId.TERRAIN;
}
}
}
if (!isNaN(lat) && !isNaN(lng)) {
myLatLng = new google.maps.LatLng(lat, lng);
}
var myOptions = {
zoom: zoom,
center: myLatLng,
mapTypeId: maptype
};
directionsDisplay = new google.maps.DirectionsRenderer({
suppressMarkers: true
});
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
polyline = new google.maps.Polyline({
path: [],
strokeColor: '#FF0000',
strokeWeight: 3
});
directionsDisplay.setMap(map);
calcRoute();
}
function calcRoute() {
var start = document.getElementById("start").value;
var end = document.getElementById("end").value;
var travelMode = google.maps.DirectionsTravelMode.DRIVING
var request = {
origin: start,
destination: end,
travelMode: travelMode
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
polyline.setPath([]);
var bounds = new google.maps.LatLngBounds();
startLocation = new Object();
endLocation = new Object();
directionsDisplay.setDirections(response);
var route = response.routes[0];
var summaryPanel = document.getElementById("directions_panel");
summaryPanel.innerHTML = "";
// For each route, display summary information.
var path = response.routes[0].overview_path;
var legs = response.routes[0].legs;
for (i = 0; i < legs.length; i++) {
if (i == 0) {
startLocation.latlng = legs[i].start_location;
startLocation.address = legs[i].start_address;
// marker = google.maps.Marker({map:map,position: startLocation.latlng});
// marker = createMarker(legs[i].start_location,"start",legs[i].start_address,"green");
}
endLocation.latlng = legs[i].end_location;
endLocation.address = legs[i].end_address;
var steps = legs[i].steps;
for (j = 0; j < steps.length; j++) {
var nextSegment = steps[j].path;
for (k = 0; k < nextSegment.length; k++) {
polyline.getPath().push(nextSegment[k]);
bounds.extend(nextSegment[k]);
}
}
}
polyline.setMap(map);
computeTotalDistance(response);
putMarkerOnRoute(parseFloat(document.getElementById('percent').value));
} else {
alert("directions response " + status);
}
});
}
var totalDist = 0;
var totalTime = 0;
function computeTotalDistance(result) {
totalDist = 0;
totalTime = 0;
var myroute = result.routes[0];
for (i = 0; i < myroute.legs.length; i++) {
totalDist += myroute.legs[i].distance.value;
totalTime += myroute.legs[i].duration.value;
}
totalDist = totalDist / 1000.
document.getElementById("total").innerHTML = "total distance is: " + totalDist + " km<br>total time is: " + (totalTime / 60).toFixed(2) + " minutes<br>average speed is: " + (totalDist / (totalTime / 3600)).toFixed(2) + " kph";
document.getElementById("totalTime").value = (totalTime / 60.).toFixed(2);
}
function putMarkerOnRoute(percent) {
if (percent > 100) {
percent = 100;
document.getElementById('percent').value = percent;
}
var distance = percent / 100 * totalDist * 1000;
// time = ((percentage/100) * totalTIme/60).toFixed(2);
// alert("Time:"+time+" totalTime:"+totalTime+" totalDist:"+totalDist+" dist:"+distance);
if (!marker) {
marker = createMarker(polyline.GetPointAtDistance(distance), "percent: " + percent, "marker");
} else {
marker.setPosition(polyline.GetPointAtDistance(distance));
marker.setTitle("percent:" + percent);
marker.contentString = "<b>percent: " + percent + "</b><br>distance: " + (distance / 1000).toFixed(2) + " km<br>marker";
google.maps.event.trigger(marker, "click");
}
}
google.maps.event.addDomListener(window, 'load', initialize);
// from epoly_v3.js
// modified to use geometry library for length of line segments
// === A method which returns a GLatLng of a point a given distance along the path ===
// === Returns null if the path is shorter than the specified distance ===
google.maps.Polyline.prototype.GetPointAtDistance = function(metres) {
// some awkward special cases
if (metres == 0) return this.getPath().getAt(0);
if (metres < 0) return null;
if (this.getPath().getLength() < 2) return null;
var dist = 0;
var olddist = 0;
for (var i = 1;
(i < this.getPath().getLength() && dist < metres); i++) {
olddist = dist;
dist += google.maps.geometry.spherical.computeDistanceBetween(this.getPath().getAt(i), this.getPath().getAt(i - 1));
}
if (dist < metres) {
return null;
}
var p1 = this.getPath().getAt(i - 2);
var p2 = this.getPath().getAt(i - 1);
var m = (metres - olddist) / (dist - olddist);
return new google.maps.LatLng(p1.lat() + (p2.lat() - p1.lat()) * m, p1.lng() + (p2.lng() - p1.lng()) * m);
}
html {
height: 100%
}
body {
height: 100%;
margin: 0px;
padding: 0px
}
<!-- Replace the value of the key parameter with your own API key. -->
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&libraries=geometry"></script>
<div id="tools">
start:
<input type="text" name="start" id="start" value="Hyderabad" /> end:
<input type="text" name="end" id="end" value="Bangalore" />
<input type="submit" onclick="calcRoute();" /><br /> percentage:
<input type="text" name="percent" id="percent" value="0" />
<input type="submit" onclick="putMarkerOnRoute(parseFloat(document.getElementById('percent').value));" /> total time:<input type="text" name="totalTime" id="totalTime" value="0" />
</div>
<div id="map_canvas" style="float:left;width:70%;height:100%;"></div>
<div id="control_panel" style="float:right;width:30%;text-align:left;padding-top:20px">
<div id="directions_panel" style="margin:20px;background-color:#FFEE77;"></div>
<div id="total"></div>
</div>
I'm having problems with fitBounds in my code. Whether I put extend.bounds and fitBounds in the createMarker function or the getData function I keep getting "bounds not defined". Right now I have the bounds statements commented out but you can see where I tried them.
google.load('visualization', '1', {'packages':['table']});
console.log("right after google load")
var map;
var markers = [];
var infoWindow = new google.maps.InfoWindow();
var bounds = new google.maps.LatLngBounds ();
var gicons = [];
gicons[1] = new google.maps.MarkerImage('http://6tango.com/MLH/Map_Icons/flower_blue_shadow.png');
gicons[2] = new google.maps.MarkerImage('http://6tango.com/MLH/Map_Icons/flower_yellow_shadow.png');
gicons[3] = new google.maps.MarkerImage('http://6tango.com/MLH/Map_Icons/flower_green_shadow.png');
var tinyicon = [];
tinyicon[1] = 'http://6tango.com/MLH/Map_Icons/flower_blue_small.png';
tinyicon[2] = 'http://6tango.com/MLH/Map_Icons/flower_yellow_small.png';
tinyicon[3] = 'http://6tango.com/MLH/Map_Icons/flower_green_small.png';
function initialize(bounds) {
console.log("initialize function")
var ca = new google.maps.LatLng(33.75,-117.9);
map = new google.maps.Map(document.getElementById('map'), {
center: ca,
zoom: 10,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: true,
overviewMapControl: false,
overviewMapControlOptions: {
opened: true
}
});
var sql = encodeURIComponent("SELECT * FROM 1O8mQ6csgl4gapp6uzW- OjUtRK05eTRiB8oCc5DY");
var query = new google.visualization.Query('http://www.google.com/fusiontables/gvizdata?tq=' + sql);
query.send(getData);
}
function getData(response,bounds) {
console.log("function getData")
var dt = response.getDataTable();
var side_html = '<table >';
for (var i = 0; i < dt.getNumberOfRows(); i++) {
var lat = dt.getValue(i,5);
var lng = dt.getValue(i,6);
var icontype = dt.getValue(i,0);
var name = dt.getValue(i,1);
var a1 = dt.getValue(i,2);
var a2 = dt.getValue(i,3);
var address = dt.getValue(i,4);
var cross = dt.getValue(i,7);
var map = dt.getValue(i,8);
var photo = dt.getValue(i,9);
var t1 = dt.getValue(i,10);
var t2 = dt.getValue(i,11);
var t3 = dt.getValue(i,12);
var t4 = dt.getValue(i,13);
var t5 = dt.getValue(i,14);
var t6 = dt.getValue(i,15);
var handicap = dt.getValue(i,16);
var pt = new google.maps.LatLng(lat, lng);
//bounds.extend(pt);
//map.fitBounds(bounds);
var html = [
'<div style="width:500px;height:100%;border:1px solid;background-color:#f0f0f0"><div style="float:left;width:188px;padding:3px"><p><b>',
name + '</b><br>',
a1 + '<br>',
a2 + '</p><p><b>C/S - Directions:</b><br>',
cross + '</p><p><b>Thomas Guide: </b>',
map + '</p><p><img src="http://kk6t.com/images/handicap_mlh.png">',
handicap + '</p></div>',
'<div style="float:left;padding:5px 5px 2px 5px;margin:2px 2px 0 0;border:1px solid black;background-color:#ffffff"><img src="',
photo + '" width="292"></div>',
'<div style="clear:both;padding:0 5px;height:200px;overflow:auto;background-color:white;margin:5px 2px;border:1px solid black">',
'<p style="padding-bottom:5px">',
t1 + '</p><p>' + t2 + '</p><p>' + t3 + '</p><p>' + t4 + '</p><p>' + t5 + '</p><p>' + t6 + '</p>/div></div>'
].join('');
if (icontype < 1)
{
side_html += '<tr><td style="padding:5px 0 5px 10px" bgcolor="#83f859"><span>' + name + '</span></td></tr>';
}
else
{
side_html += '<tr><td ><img src=' + tinyicon[icontype] + '> ' + name + '</td></tr>';
}
createMarker(pt, html, name, icontype, bounds);
}
console.log("finished with markers")
side_html += '</tbody> \
</table>';
document.getElementById("side_bar").innerHTML = side_html;
}
function createMarker(point,info,name,icontype,bounds) {
console.log("function createMarker")
var marker = new google.maps.Marker({
position: point,
map: map,
title: name,
icon: gicons[icontype]
});
//bounds.extend(point);
markers.push(marker);
google.maps.event.addListener(marker, 'click', function() {
infoWindow.close();
infoWindow.setContent(info);
infoWindow.open(map,marker);
});
}
function myclick(num) {
console.log("function myclick")
google.maps.event.trigger(markers[num], "click");
}
You have naming faults with code.
First
var bounds = new google.maps.LatLngBounds ();
later
bounds.extend(pt);
map.fitBounds(bounds);
then
bounds.extend(point);
I would remove the first constructor from GLOBAL and place it in getData() before the loop.The bounds.extend(pt); after createMarker() without bounds parameter. Finally map.fitBounds(bounds); after loop.
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < dt.getNumberOfRows(); i++) {
...
...
var pt = new google.maps.LatLng(lat, lng);
...
...
createMarker(pt, html, name, icontype);//no bounds
bounds.extend(pt);
...
...
}
map.fitBounds(bounds);
I want to fix(Freeze) gridview header while vertical scrolling.
I also want to fix first column while horizontal scrolling.
I want this in both chrome and IE.
It is possible to apply the specific GridView / Table layout via custom CSS rules (as it was discussed in the <table><tbody> scrollable? thread) to fix GridView's Header. However, this approach will not work in all browsers. The 3-rd ASP.NET GridView controls (such as the ASPxGridView from DevExpress component vendor provide this functionality.
Check also the following CodeProject solutions:
Fixed header Grid
Gridview with fixed header
Gridview Fixed Header
I was looking for a solution for this for a long time and found most of the answers are not working or not suitable for my situation i also find most of the java script code for that they worked but only with the vertical scroll not with the horizontal scroll and also combination of header and rows doesn't match.
Finally i have found a solution with javascript here is the link bellow :-
scrollable horizontal and vertical grid view with fixed headers
Refer Here which is 100% working
https://stackoverflow.com/a/59357398/11863405
Static Header for Gridview Control
You can try overflow css property.
// create this Js and add reference
var GridViewScrollOptions = /** #class */ (function () {
function GridViewScrollOptions() {
}
return GridViewScrollOptions;
}());
var GridViewScroll = /** #class */ (function ()
{
function GridViewScroll(options) {
this._initialized = false;
if (options.elementID == null)
options.elementID = "";
if (options.width == null)
options.width = "700";
if (options.height == null)
options.height = "350";
if (options.freezeColumnCssClass == null)
options.freezeColumnCssClass = "";
if (options.freezeFooterCssClass == null)
options.freezeFooterCssClass = "";
if (options.freezeHeaderRowCount == null)
options.freezeHeaderRowCount = 1;
if (options.freezeColumnCount == null)
options.freezeColumnCount = 1;
this.initializeOptions(options);
}
GridViewScroll.prototype.initializeOptions = function (options) {
this.GridID = options.elementID;
this.GridWidth = options.width;
this.GridHeight = options.height;
this.FreezeColumn = options.freezeColumn;
this.FreezeFooter = options.freezeFooter;
this.FreezeColumnCssClass = options.freezeColumnCssClass;
this.FreezeFooterCssClass = options.freezeFooterCssClass;
this.FreezeHeaderRowCount = options.freezeHeaderRowCount;
this.FreezeColumnCount = options.freezeColumnCount;
};
GridViewScroll.prototype.enhance = function ()
{
this.FreezeCellWidths = [];
this.IsVerticalScrollbarEnabled = false;
this.IsHorizontalScrollbarEnabled = false;
if (this.GridID == null || this.GridID == "")
{
return;
}
this.ContentGrid = document.getElementById(this.GridID);
if (this.ContentGrid == null) {
return;
}
if (this.ContentGrid.rows.length < 2) {
return;
}
if (this._initialized) {
this.undo();
}
this._initialized = true;
this.Parent = this.ContentGrid.parentNode;
this.ContentGrid.style.display = "none";
if (typeof this.GridWidth == 'string' && this.GridWidth.indexOf("%") > -1) {
var percentage = parseInt(this.GridWidth);
this.Width = this.Parent.offsetWidth * percentage / 100;
}
else {
this.Width = parseInt(this.GridWidth);
}
if (typeof this.GridHeight == 'string' && this.GridHeight.indexOf("%") > -1) {
var percentage = parseInt(this.GridHeight);
this.Height = this.Parent.offsetHeight * percentage / 100;
}
else {
this.Height = parseInt(this.GridHeight);
}
this.ContentGrid.style.display = "";
this.ContentGridHeaderRows = this.getGridHeaderRows();
this.ContentGridItemRow = this.ContentGrid.rows.item(this.FreezeHeaderRowCount);
var footerIndex = this.ContentGrid.rows.length - 1;
this.ContentGridFooterRow = this.ContentGrid.rows.item(footerIndex);
this.Content = document.createElement('div');
this.Content.id = this.GridID + "_Content";
this.Content.style.position = "relative";
this.Content = this.Parent.insertBefore(this.Content, this.ContentGrid);
this.ContentFixed = document.createElement('div');
this.ContentFixed.id = this.GridID + "_Content_Fixed";
this.ContentFixed.style.overflow = "auto";
this.ContentFixed = this.Content.appendChild(this.ContentFixed);
this.ContentGrid = this.ContentFixed.appendChild(this.ContentGrid);
this.ContentFixed.style.width = String(this.Width) + "px";
if (this.ContentGrid.offsetWidth > this.Width) {
this.IsHorizontalScrollbarEnabled = true;
}
if (this.ContentGrid.offsetHeight > this.Height) {
this.IsVerticalScrollbarEnabled = true;
}
this.Header = document.createElement('div');
this.Header.id = this.GridID + "_Header";
this.Header.style.backgroundColor = "#F0F0F0";
this.Header.style.position = "relative";
this.HeaderFixed = document.createElement('div');
this.HeaderFixed.id = this.GridID + "_Header_Fixed";
this.HeaderFixed.style.overflow = "hidden";
this.Header = this.Parent.insertBefore(this.Header, this.Content);
this.HeaderFixed = this.Header.appendChild(this.HeaderFixed);
this.ScrollbarWidth = this.getScrollbarWidth();
this.prepareHeader();
this.calculateHeader();
this.Header.style.width = String(this.Width) + "px";
if (this.IsVerticalScrollbarEnabled) {
this.HeaderFixed.style.width = String(this.Width - this.ScrollbarWidth) + "px";
if (this.IsHorizontalScrollbarEnabled) {
this.ContentFixed.style.width = this.HeaderFixed.style.width;
if (this.isRTL()) {
this.ContentFixed.style.paddingLeft = String(this.ScrollbarWidth) + "px";
}
else {
this.ContentFixed.style.paddingRight = String(this.ScrollbarWidth) + "px";
}
}
this.ContentFixed.style.height = String(this.Height - this.Header.offsetHeight) + "px";
}
else {
this.HeaderFixed.style.width = this.Header.style.width;
this.ContentFixed.style.width = this.Header.style.width;
}
if (this.FreezeColumn && this.IsHorizontalScrollbarEnabled) {
this.appendFreezeHeader();
this.appendFreezeContent();
}
if (this.FreezeFooter && this.IsVerticalScrollbarEnabled) {
this.appendFreezeFooter();
if (this.FreezeColumn && this.IsHorizontalScrollbarEnabled) {
this.appendFreezeFooterColumn();
}
}
var self = this;
this.ContentFixed.onscroll = function (event) {
self.HeaderFixed.scrollLeft = self.ContentFixed.scrollLeft;
if (self.ContentFreeze != null)
self.ContentFreeze.scrollTop = self.ContentFixed.scrollTop;
if (self.FooterFreeze != null)
self.FooterFreeze.scrollLeft = self.ContentFixed.scrollLeft;
};
};
GridViewScroll.prototype.getGridHeaderRows = function () {
var gridHeaderRows = new Array();
for (var i = 0; i < this.FreezeHeaderRowCount; i++) {
gridHeaderRows.push(this.ContentGrid.rows.item(i));
}
return gridHeaderRows;
};
GridViewScroll.prototype.prepareHeader = function () {
this.HeaderGrid = this.ContentGrid.cloneNode(false);
this.HeaderGrid.id = this.GridID + "_Header_Fixed_Grid";
this.HeaderGrid = this.HeaderFixed.appendChild(this.HeaderGrid);
this.prepareHeaderGridRows();
for (var i = 0; i < this.ContentGridItemRow.cells.length; i++) {
this.appendHelperElement(this.ContentGridItemRow.cells.item(i));
this.appendHelperElement(this.HeaderGridHeaderCells[i]);
}
};
GridViewScroll.prototype.prepareHeaderGridRows = function () {
this.HeaderGridHeaderRows = new Array();
for (var i = 0; i < this.FreezeHeaderRowCount; i++) {
var gridHeaderRow = this.ContentGridHeaderRows[i];
var headerGridHeaderRow = gridHeaderRow.cloneNode(true);
this.HeaderGridHeaderRows.push(headerGridHeaderRow);
this.HeaderGrid.appendChild(headerGridHeaderRow);
}
this.prepareHeaderGridCells();
};
GridViewScroll.prototype.prepareHeaderGridCells = function () {
this.HeaderGridHeaderCells = new Array();
for (var i = 0; i < this.ContentGridItemRow.cells.length; i++) {
for (var rowIndex in this.HeaderGridHeaderRows) {
var cgridHeaderRow = this.HeaderGridHeaderRows[rowIndex];
var fixedCellIndex = 0;
for (var cellIndex = 0; cellIndex < cgridHeaderRow.cells.length; cellIndex++) {
var cgridHeaderCell = cgridHeaderRow.cells.item(cellIndex);
if (cgridHeaderCell.colSpan == 1 && i == fixedCellIndex) {
this.HeaderGridHeaderCells.push(cgridHeaderCell);
}
else {
fixedCellIndex += cgridHeaderCell.colSpan - 1;
}
fixedCellIndex++;
}
}
}
};
GridViewScroll.prototype.calculateHeader = function () {
for (var i = 0; i < this.ContentGridItemRow.cells.length; i++) {
var gridItemCell = this.ContentGridItemRow.cells.item(i);
var helperElement = gridItemCell.firstChild;
var helperWidth = parseInt(String(helperElement.offsetWidth));
this.FreezeCellWidths.push(helperWidth);
helperElement.style.width = helperWidth + "px";
helperElement = this.HeaderGridHeaderCells[i].firstChild;
helperElement.style.width = helperWidth + "px";
}
for (var i = 0; i < this.FreezeHeaderRowCount; i++) {
this.ContentGridHeaderRows[i].style.display = "none";
}
};
GridViewScroll.prototype.appendFreezeHeader = function () {
this.HeaderFreeze = document.createElement('div');
this.HeaderFreeze.id = this.GridID + "_Header_Freeze";
this.HeaderFreeze.style.position = "absolute";
this.HeaderFreeze.style.overflow = "hidden";
this.HeaderFreeze.style.top = "0px";
this.HeaderFreeze.style.left = "0px";
this.HeaderFreeze.style.width = "";
this.HeaderFreezeGrid = this.HeaderGrid.cloneNode(false);
this.HeaderFreezeGrid.id = this.GridID + "_Header_Freeze_Grid";
this.HeaderFreezeGrid = this.HeaderFreeze.appendChild(this.HeaderFreezeGrid);
this.HeaderFreezeGridHeaderRows = new Array();
for (var i = 0; i < this.HeaderGridHeaderRows.length; i++) {
var headerFreezeGridHeaderRow = this.HeaderGridHeaderRows[i].cloneNode(false);
this.HeaderFreezeGridHeaderRows.push(headerFreezeGridHeaderRow);
var columnIndex = 0;
var columnCount = 0;
while (columnCount < this.FreezeColumnCount) {
var freezeColumn = this.HeaderGridHeaderRows[i].cells.item(columnIndex).cloneNode(true);
headerFreezeGridHeaderRow.appendChild(freezeColumn);
columnCount += freezeColumn.colSpan;
columnIndex++;
}
this.HeaderFreezeGrid.appendChild(headerFreezeGridHeaderRow);
}
this.HeaderFreeze = this.Header.appendChild(this.HeaderFreeze);
};
GridViewScroll.prototype.appendFreezeContent = function () {
this.ContentFreeze = document.createElement('div');
this.ContentFreeze.id = this.GridID + "_Content_Freeze";
this.ContentFreeze.style.position = "absolute";
this.ContentFreeze.style.overflow = "hidden";
this.ContentFreeze.style.top = "0px";
this.ContentFreeze.style.left = "0px";
this.ContentFreeze.style.width = "";
this.ContentFreezeGrid = this.HeaderGrid.cloneNode(false);
this.ContentFreezeGrid.id = this.GridID + "_Content_Freeze_Grid";
this.ContentFreezeGrid = this.ContentFreeze.appendChild(this.ContentFreezeGrid);
var freezeCellHeights = [];
var paddingTop = this.getPaddingTop(this.ContentGridItemRow.cells.item(0));
var paddingBottom = this.getPaddingBottom(this.ContentGridItemRow.cells.item(0));
for (var i = 0; i < this.ContentGrid.rows.length; i++) {
var gridItemRow = this.ContentGrid.rows.item(i);
var gridItemCell = gridItemRow.cells.item(0);
var helperElement = void 0;
if (gridItemCell.firstChild.className == "gridViewScrollHelper") {
helperElement = gridItemCell.firstChild;
}
else {
helperElement = this.appendHelperElement(gridItemCell);
}
var helperHeight = parseInt(String(gridItemCell.offsetHeight - paddingTop - paddingBottom));
freezeCellHeights.push(helperHeight);
var cgridItemRow = gridItemRow.cloneNode(false);
var cgridItemCell = gridItemCell.cloneNode(true);
if (this.FreezeColumnCssClass != null || this.FreezeColumnCssClass != "")
cgridItemRow.className = this.FreezeColumnCssClass;
var columnIndex = 0;
var columnCount = 0;
while (columnCount < this.FreezeColumnCount) {
var freezeColumn = gridItemRow.cells.item(columnIndex).cloneNode(true);
cgridItemRow.appendChild(freezeColumn);
columnCount += freezeColumn.colSpan;
columnIndex++;
}
this.ContentFreezeGrid.appendChild(cgridItemRow);
}
for (var i = 0; i < this.ContentGrid.rows.length; i++) {
var gridItemRow = this.ContentGrid.rows.item(i);
var gridItemCell = gridItemRow.cells.item(0);
var cgridItemRow = this.ContentFreezeGrid.rows.item(i);
var cgridItemCell = cgridItemRow.cells.item(0);
var helperElement = gridItemCell.firstChild;
helperElement.style.height = String(freezeCellHeights[i]) + "px";
helperElement = cgridItemCell.firstChild;
helperElement.style.height = String(freezeCellHeights[i]) + "px";
}
if (this.IsVerticalScrollbarEnabled) {
this.ContentFreeze.style.height = String(this.Height - this.Header.offsetHeight - this.ScrollbarWidth) + "px";
}
else {
this.ContentFreeze.style.height = String(this.ContentFixed.offsetHeight - this.ScrollbarWidth) + "px";
}
this.ContentFreeze = this.Content.appendChild(this.ContentFreeze);
};
GridViewScroll.prototype.appendFreezeFooter = function () {
this.FooterFreeze = document.createElement('div');
this.FooterFreeze.id = this.GridID + "_Footer_Freeze";
this.FooterFreeze.style.position = "absolute";
this.FooterFreeze.style.overflow = "hidden";
this.FooterFreeze.style.left = "0px";
this.FooterFreeze.style.width = String(this.ContentFixed.offsetWidth - this.ScrollbarWidth) + "px";
this.FooterFreezeGrid = this.HeaderGrid.cloneNode(false);
this.FooterFreezeGrid.id = this.GridID + "_Footer_Freeze_Grid";
this.FooterFreezeGrid = this.FooterFreeze.appendChild(this.FooterFreezeGrid);
this.FooterFreezeGridHeaderRow = this.ContentGridFooterRow.cloneNode(true);
if (this.FreezeFooterCssClass != null || this.FreezeFooterCssClass != "")
this.FooterFreezeGridHeaderRow.className = this.FreezeFooterCssClass;
for (var i = 0; i < this.FooterFreezeGridHeaderRow.cells.length; i++) {
var cgridHeaderCell = this.FooterFreezeGridHeaderRow.cells.item(i);
var helperElement = this.appendHelperElement(cgridHeaderCell);
helperElement.style.width = String(this.FreezeCellWidths[i]) + "px";
}
this.FooterFreezeGridHeaderRow = this.FooterFreezeGrid.appendChild(this.FooterFreezeGridHeaderRow);
this.FooterFreeze = this.Content.appendChild(this.FooterFreeze);
var footerFreezeTop = this.ContentFixed.offsetHeight - this.FooterFreeze.offsetHeight;
if (this.IsHorizontalScrollbarEnabled) {
footerFreezeTop -= this.ScrollbarWidth;
}
this.FooterFreeze.style.top = String(footerFreezeTop) + "px";
};
GridViewScroll.prototype.appendFreezeFooterColumn = function () {
this.FooterFreezeColumn = document.createElement('div');
this.FooterFreezeColumn.id = this.GridID + "_Footer_FreezeColumn";
this.FooterFreezeColumn.style.position = "absolute";
this.FooterFreezeColumn.style.overflow = "hidden";
this.FooterFreezeColumn.style.left = "0px";
this.FooterFreezeColumn.style.width = "";
this.FooterFreezeColumnGrid = this.HeaderGrid.cloneNode(false);
this.FooterFreezeColumnGrid.id = this.GridID + "_Footer_FreezeColumn_Grid";
this.FooterFreezeColumnGrid = this.FooterFreezeColumn.appendChild(this.FooterFreezeColumnGrid);
this.FooterFreezeColumnGridHeaderRow = this.FooterFreezeGridHeaderRow.cloneNode(false);
this.FooterFreezeColumnGridHeaderRow = this.FooterFreezeColumnGrid.appendChild(this.FooterFreezeColumnGridHeaderRow);
if (this.FreezeFooterCssClass != null)
this.FooterFreezeColumnGridHeaderRow.className = this.FreezeFooterCssClass;
var columnIndex = 0;
var columnCount = 0;
while (columnCount < this.FreezeColumnCount) {
var freezeColumn = this.FooterFreezeGridHeaderRow.cells.item(columnIndex).cloneNode(true);
this.FooterFreezeColumnGridHeaderRow.appendChild(freezeColumn);
columnCount += freezeColumn.colSpan;
columnIndex++;
}
var footerFreezeTop = this.ContentFixed.offsetHeight - this.FooterFreeze.offsetHeight;
if (this.IsHorizontalScrollbarEnabled) {
footerFreezeTop -= this.ScrollbarWidth;
}
this.FooterFreezeColumn.style.top = String(footerFreezeTop) + "px";
this.FooterFreezeColumn = this.Content.appendChild(this.FooterFreezeColumn);
};
GridViewScroll.prototype.appendHelperElement = function (gridItemCell) {
var helperElement = document.createElement('div');
helperElement.className = "gridViewScrollHelper";
while (gridItemCell.hasChildNodes()) {
helperElement.appendChild(gridItemCell.firstChild);
}
return gridItemCell.appendChild(helperElement);
};
GridViewScroll.prototype.getScrollbarWidth = function () {
var innerElement = document.createElement('p');
innerElement.style.width = "100%";
innerElement.style.height = "200px";
var outerElement = document.createElement('div');
outerElement.style.position = "absolute";
outerElement.style.top = "0px";
outerElement.style.left = "0px";
outerElement.style.visibility = "hidden";
outerElement.style.width = "200px";
outerElement.style.height = "150px";
outerElement.style.overflow = "hidden";
outerElement.appendChild(innerElement);
document.body.appendChild(outerElement);
var innerElementWidth = innerElement.offsetWidth;
outerElement.style.overflow = 'scroll';
var outerElementWidth = innerElement.offsetWidth;
if (innerElementWidth === outerElementWidth)
outerElementWidth = outerElement.clientWidth;
document.body.removeChild(outerElement);
return innerElementWidth - outerElementWidth;
};
GridViewScroll.prototype.isRTL = function () {
var direction = "";
if (window.getComputedStyle) {
direction = window.getComputedStyle(this.ContentGrid, null).getPropertyValue('direction');
}
else {
direction = this.ContentGrid.currentStyle.direction;
}
return direction === "rtl";
};
GridViewScroll.prototype.getPaddingTop = function (element) {
var value = "";
if (window.getComputedStyle) {
value = window.getComputedStyle(element, null).getPropertyValue('padding-Top');
}
else {
value = element.currentStyle.paddingTop;
}
return parseInt(value);
};
GridViewScroll.prototype.getPaddingBottom = function (element) {
var value = "";
if (window.getComputedStyle) {
value = window.getComputedStyle(element, null).getPropertyValue('padding-Bottom');
}
else {
value = element.currentStyle.paddingBottom;
}
return parseInt(value);
};
GridViewScroll.prototype.undo = function () {
this.undoHelperElement();
for (var _i = 0, _a = this.ContentGridHeaderRows; _i < _a.length; _i++) {
var contentGridHeaderRow = _a[_i];
contentGridHeaderRow.style.display = "";
}
this.Parent.insertBefore(this.ContentGrid, this.Header);
this.Parent.removeChild(this.Header);
this.Parent.removeChild(this.Content);
this._initialized = false;
};
GridViewScroll.prototype.undoHelperElement = function () {
for (var i = 0; i < this.ContentGridItemRow.cells.length; i++) {
var gridItemCell = this.ContentGridItemRow.cells.item(i);
var helperElement = gridItemCell.firstChild;
while (helperElement.hasChildNodes()) {
gridItemCell.appendChild(helperElement.firstChild);
}
gridItemCell.removeChild(helperElement);
}
if (this.FreezeColumn) {
for (var i = 2; i < this.ContentGrid.rows.length; i++) {
var gridItemRow = this.ContentGrid.rows.item(i);
var gridItemCell = gridItemRow.cells.item(0);
var helperElement = gridItemCell.firstChild;
while (helperElement.hasChildNodes()) {
gridItemCell.appendChild(helperElement.firstChild);
}
gridItemCell.removeChild(helperElement);
}
}
};
return GridViewScroll;
}());
//add On Head
<head runat="server">
<title></title>
<script src="client/js/jquery-3.1.1.min.js"></script>
<script src="js/gridviewscroll.js"></script>
<script type="text/javascript">
window.onload = function () {
var gridViewScroll = new GridViewScroll({
elementID: "GridView1" // [Header is fix column will be Freeze ][1]Target Control
});
gridViewScroll.enhance();
}
</script>
</head>
//Add on Body
<body>
<form id="form1" runat="server">
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="true">
// <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
<%-- <Columns>
<asp:BoundField DataField="SHIPMENT_ID" HeaderText="SHIPMENT_ID"
ReadOnly="True" SortExpression="SHIPMENT_ID" />
<asp:BoundField DataField="TypeValue" HeaderText="TypeValue"
SortExpression="TypeValue" />
<asp:BoundField DataField="CHAId" HeaderText="CHAId"
SortExpression="CHAId" />
<asp:BoundField DataField="Status" HeaderText="Status"
SortExpression="Status" />
</Columns>--%>
</asp:GridView>
<script type="text/javascript">
$(document).ready(function () {
var gridHeader = $('#<%=grdSiteWiseEmpAttendance.ClientID%>').clone(true); // Here Clone Copy of Gridview with style
$(gridHeader).find("tr:gt(0)").remove(); // Here remove all rows except first row (header row)
$('#<%=grdSiteWiseEmpAttendance.ClientID%> tr th').each(function (i) {
// Here Set Width of each th from gridview to new table(clone table) th
$("th:nth-child(" + (i + 1) + ")", gridHeader).css('width', ($(this).width()).toString() + "px");
});
$("#GHead1").append(gridHeader);
$('#GHead1').css('position', 'top');
$('#GHead1').css('top', $('#<%=grdSiteWiseEmpAttendance.ClientID%>').offset().top);
});
</script>
<div class="row">
<div class="col-lg-12" style="width: auto;">
<div id="GHead1"></div>
<div id="divGridViewScroll1" style="height: 600px; overflow: auto">
<div class="table-responsive">
<asp:GridView ID="grdSiteWiseEmpAttendance" CssClass="table table-small-font table-bordered table-striped" Font-Size="Smaller" EmptyDataRowStyle-ForeColor="#cc0000" HeaderStyle-Font-Size="8" HeaderStyle-Font-Names="Calibri" HeaderStyle-Font-Italic="true" runat="server" AutoGenerateColumns="false"
BackColor="#f0f5f5" OnRowDataBound="grdSiteWiseEmpAttendance_RowDataBound" HeaderStyle-ForeColor="#990000">
<Columns>
</Columns>
<HeaderStyle HorizontalAlign="Justify" VerticalAlign="Top" />
<RowStyle Font-Names="Calibri" ForeColor="#000000" />
</asp:GridView>
</div>
</div>
</div>
</div>
Acheived by using java script...
Copy and paste given below javascript code inside the head tag.
<script language="javascript" type="text/javascript">
function MakeStaticHeader(gridId, height, width, headerHeight, isFooter) {
var tbl = document.getElementById(gridId);
if (tbl) {
var DivHR = document.getElementById('DivHeaderRow');
var DivMC = document.getElementById('DivMainContent');
var DivFR = document.getElementById('DivFooterRow');
//*** Set divheaderRow Properties ****
DivHR.style.height = headerHeight + 'px';
DivHR.style.width = (parseInt(width) - 16) + 'px';
DivHR.style.position = 'relative';
DivHR.style.top = '0px';
DivHR.style.zIndex = '10';
DivHR.style.verticalAlign = 'top';
//*** Set divMainContent Properties ****
DivMC.style.width = width + 'px';
DivMC.style.height = height + 'px';
DivMC.style.position = 'relative';
DivMC.style.top = -headerHeight + 'px';
DivMC.style.zIndex = '1';
//*** Set divFooterRow Properties ****
DivFR.style.width = (parseInt(width) - 16) + 'px';
DivFR.style.position = 'relative';
DivFR.style.top = -headerHeight + 'px';
DivFR.style.verticalAlign = 'top';
DivFR.style.paddingtop = '2px';
if (isFooter) {
var tblfr = tbl.cloneNode(true);
tblfr.removeChild(tblfr.getElementsByTagName('tbody')[0]);
var tblBody = document.createElement('tbody');
tblfr.style.width = '100%';
tblfr.cellSpacing = "0";
tblfr.border = "0px";
tblfr.rules = "none";
//*****In the case of Footer Row *******
tblBody.appendChild(tbl.rows[tbl.rows.length - 1]);
tblfr.appendChild(tblBody);
DivFR.appendChild(tblfr);
}
//****
DivHR.appendChild(tbl.cloneNode(true));
}
}
function OnScrollDiv(Scrollablediv) {
document.getElementById('DivHeaderRow').scrollLeft = Scrollablediv.scrollLeft;
document.getElementById('DivFooterRow').scrollLeft = Scrollablediv.scrollLeft;
}
</script>
Then Copy this code and paste and place your Grid View inside DivMainContent.
HTML Code:-
<div id="DivRoot" align="left">
<div style="overflow: hidden;" id="DivHeaderRow">
</div>
<div style="overflow:scroll;" onscroll="OnScrollDiv(this)" id="DivMainContent">
<%-- ***Place Your GridView Here***
<asp:GridView runat="server" ID="gridshow" Width="100%"
AutoGenerateColumns="False"ShowFooter="True">
<Columns>
//...................
</Columns>
</asp:GridView>
--%>
</div>
<div id="DivFooterRow" style="overflow:hidden">
</div>
</div>
Then Call function MakeStaticHeader in Aspx.CS File at the time of binding Gridview and pass the Some parameters.
ClientId of Gridview(Change GrdDisplay.ClientID as your gridview clientid).
Height of Scrollable div.
Width of Scrollable div.
Height of Table Header Row.
IsFooter (true/false) If you want to Make footer static or not.
-->After binding the Gridview, place below code
ScriptManager.RegisterStartupScript(Page, this.GetType(), "Key", "<script>MakeStaticHeader('" + GrdDisplay.ClientID + "', 400, 950 , 40 ,true); </script>", false);
Hope this will work for sure...