I am struggling to get a Google Gauge Chart to center align.
I would like to have a row with a centered gauge char and one row with a centered line chart.
I have tried various options and using "display: inline-block" but does not work.
The row with the line chart behaves as expected.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages':['gauge', 'corechart']});
google.charts.setOnLoadCallback(drawCharts);
function drawCharts() {
drawChart();
drawGauges();
}
function drawGauges() {
var data = google.visualization.arrayToDataTable([
['Label', 'Value'],
['Memory', 80],
['CPU', 55],
]);
var w = $( window ).width();
var x = Math.floor(w * 0.3);
console.log("width: " + w + ", x = " + x);
var h = $( window ).height();
var y = Math.floor(h * 0.3)
console.log("height: " + h + ", y = " + y);
var options = {
redFrom: 90, redTo: 100,
yellowFrom:75, yellowTo: 90,
minorTicks: 5,
width: x,
height: y,
};
var chart = new google.visualization.Gauge(document.getElementById('chart_div'));
chart.draw(data, options);
}
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Year', 'Sales', 'Expenses'],
['2004', 1000, 400],
['2005', 1170, 460],
['2006', 660, 1120],
['2007', 1030, 540]
]);
var options = {
title: 'Company Performance',
curveType: 'function',
legend: { position: 'bottom' }
};
var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));
chart.draw(data, options);
}
$(window).resize(function(){
drawCharts();
});
</script>
<style>
.container {
display: flex;
flex-flow: row wrap;
justify-content: center;
align-items: center;
}
.row {
height:30%;
width: 100%;
}
#chart_div {
display: inline-block
margin: 0 auto;
}
</style>
</head>
<body>
<div class="container">
<div class="row">
<div id="chart_div"></div>
</div>
<div class="row">
<div id="curve_chart" ></div>
</div>
</div>
</body>
</html>
add text-align: center; to .container
.container {
display: flex;
flex-flow: row wrap;
justify-content: center;
align-items: center;
text-align: center;
}
see following working snippet...
google.charts.load('current', {
callback: drawCharts,
packages:['corechart', 'gauge']
});
function drawCharts() {
drawChart();
drawGauges();
}
function drawGauges() {
var data = google.visualization.arrayToDataTable([
['Label', 'Value'],
['Memory', 80],
['CPU', 55],
]);
var w = $( window ).width();
var x = Math.floor(w * 0.3);
console.log("width: " + w + ", x = " + x);
var h = $( window ).height();
var y = Math.floor(h * 0.3)
console.log("height: " + h + ", y = " + y);
var options = {
redFrom: 90, redTo: 100,
yellowFrom:75, yellowTo: 90,
minorTicks: 5,
width: x,
height: y,
};
var chart = new google.visualization.Gauge(document.getElementById('chart_div'));
chart.draw(data, options);
}
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Year', 'Sales', 'Expenses'],
['2004', 1000, 400],
['2005', 1170, 460],
['2006', 660, 1120],
['2007', 1030, 540]
]);
var options = {
title: 'Company Performance',
curveType: 'function',
legend: { position: 'bottom' }
};
var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));
chart.draw(data, options);
}
$(window).resize(function(){
drawCharts();
});
.container {
display: flex;
flex-flow: row wrap;
justify-content: center;
align-items: center;
text-align: center;
}
.row {
height: 30%;
width: 100%;
}
#chart_div {
display: inline-block;
margin: 0 auto;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div class="container">
<div class="row">
<div id="chart_div"></div>
</div>
<div class="row">
<div id="curve_chart" ></div>
</div>
</div>
Related
I need your help
I have this html code :
<!DOCTYPE html>
<html>
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
#more {display: none;}
</style>
</head>
<body>
<h2>Read More Read Less Button</h2>
<p><img src=""/><span id="image"><img src=""/></span><span id="more">Lorem Ipsum </span></p>
<button onclick="myFunction()" id="myBtn">Read more</button>
<script>
function myFunction() {
var dots = document.getElementById("image");
var moreText = document.getElementById("more");
var btnText = document.getElementById("myBtn");
if (dots.style.display === "none") {
dots.style.display = "inline";
btnText.innerHTML = "Read more";
moreText.style.display = "none";
} else {
dots.style.display = "none";
btnText.innerHTML = "Read less";
moreText.style.display = "inline";
}
}
</script>
</body>
</html>
This finally would be working. I have used a file from my github repo to make the example working. But you can always that path.
// You can replace your whole JS with this code
fetch("https://raw.githubusercontent.com/ArunBohra33/json-data/main/clickable-pic") //file json objects
.then(function (response) {
return response.json();
})
.then(function (data) {
appendData(data);
})
.catch(function (err) {
console.log("error: " + err);
});
function appendData(data) {
var mainContainer = document.getElementById("myData");
for (var i = 0; i < data.results.length; i++) {
var img = document.createElement("img");
// New code
// Add a id to the image
img.setAttribute("id", "popup-image" + (i + 1));
img.src = data.results[i].picture.large;
img.classList.add("popup-img");
img.setAttribute("data-data", JSON.stringify(data.results[i]));
mainContainer.appendChild(img);
// Old code
var div = document.createElement("div");
div.innerHTML = "first: " + data.results[i].name.first + " First Name :" + data.results[i].name.last;
mainContainer.appendChild(div);
// if (i == data.results.length - 1) clickOnImg();
}
for (let i = 0; i < data.results.length; i++) {
document.querySelector(`#popup-image${i + 1}`).addEventListener("click", function () {
var firstName = data.results[i].name.first;
var lastName = data.results[i].name.last;
showData(firstName, lastName, i + 1);
});
}
}
// This function shows the modal with data in it
function showData(firstName, lastName, index) {
var popupBox = document.createElement("div");
popupBox.style.display = "flex";
popupBox.setAttribute("id", "popupBoxOverlay_{i}");
popupBox.classList.add("popupBox");
popupBox.innerHTML = `<div class="modal">
<span class="cross-btn-${index - 1}">×</span>
<div class="fname">
<label>FirstName: </label>
<span class="firstName${index - 1}">${firstName}</span>
</div>
<div class="lname">
<label>LastName: </label>
<span id="lastName${index - 1}">${lastName}</span>
</div>
</div>`;
document.body.prepend(popupBox);
var crossBtn = document.querySelector(".cross-btn-" + (index - 1));
crossBtn.addEventListener("click", function () {
popupBox.remove();
});
}
/* // CSS CODE */
img {
width: 200px;
}
.popupBox {
position: fixed;
top: 0;
left: 0;
background: rgba(0, 0, 0, .5);
height: 100vh;
width: 100vw;
/* z-index: 100000; */
display: flex;
justify-content: center;
align-items: center;
}
.modal {
display: flex;
flex-direction: column;
min-width: 60%;
background: #fff;
border-radius: 8px;
position: relative;
padding: 2rem;
}
[class^=cross-btn] {
position: absolute;
top: 10px;
right: 10px;
cursor: pointer;
}
<div class="album py-5 bg-light">
<div class="container">
<br>
<h1>Persons</h1><br>
<div class="row">
<div class="card-group">
<div id="myData"></div>
</div>
</div>
</div>
</div>
I created following simple website. I have Starfield and galaxy pictures. Starfield is animated by JS code. Stars are moving. But when I place Galaxy over starfield with CSS code stars stop moving.
Below I placed JS code and HTML code without placing galaxy over starfield. How can I place one over another with stars moving?
Regards
Piotr
<head>
<meta charset ="utf-8">
<title> Galaktyka</title>
<script src ="Code17.js"></script>
<style>
#galaxy{
display: block;
margin-left: 0;
margin-top: 0;
}
#star{
position: relative;
}
</style>
</head>
<body>
<script>
window.onscroll = function () {
window.scrollTo(0,0);
}
</script>
<style type="text/css">
body {
overflow: hidden;
}
</style>
<img id="galaxy" src="Galaktyka.jpg" style="width: 70%">
<img id="star" src="starfield.jpg">
</body>
And below JS
window.onload = function(){
let image = document.getElementById("star");
imageLeft = -175;
setInterval(move, 100, image);
}
var motion = true;
function move() {
if(motion) {
let image = document.getElementById("star");
imageLeft = imageLeft + 1;
image.style.left = imageLeft + "px";
if (imageLeft == 0) {
motion = false;
} else {
let image = document.getElementById("star");
imageLeft = imageLeft - 1;
image.style.left = imageLeft + "px";
}
if (imageLeft == -175){
motion = true;
}
}
}
Our videos use the lower third of the page for introductions, etc. much like TV News stations do. When captions are on, they're blocking all of that, thus creating a LOT of complaints from the communities that need the captions. I've tried tinkering with the CSS, but with a responsive layout, resizing the player wreaks havoc, often putting them out of sight altogether.
Is there a setting that can be changed, or technique to use, that will keep the captions at the top and in view when resized, OR in an external container?
Problem: the JW player 608 live captions are not formatted cleanly.
To solve this, disable the JW caption display and format our own window, named "ccbuffer"
<style type="text/css">
.jw-captions {
display: none !important;
}
#ccbuffer {
border: 2px solid white !important;
border-radius: 4px;
background-color: black !important;
display: flex;
height: 120px;
margin-top: 6px;
font: 22px bold arial, sans-serif;
color: white;
justify-content: center;
align-items: center;
}
</style>
Here is where I show the player, and ccbuffer is a div right below it
<div id="myPlayer">
<p style="color: #FFFFFF; font-weight: bold; font-size: x-large; border-style: solid; border-color: #E2AA4F">
Loading video...
</p>
</div>
<div id="ccbuffer" />
DOMSubtreeModified is deprecated. Use MutationObserver, which is less stressful on the client.
Let's hook the 'captionsChanged' event from JW. if track is 0 then no captions are selected and we disconnect the observer. If captions are selected, then we use jquery to pull the text out of the jw-text-track-cue element, and format it into a nice 3 line display in our ccbuffer window.
<script>
var observer;
jwplayer().on('captionsChanged', function (event) {
if (event.track == 0) {
observer.disconnect();
$('#ccbuffer').hide('slow');
}
else {
$('#ccbuffer').show('slow');
// select the target node
var target = document.querySelector('.jw-captions');
// create an observer instance
observer = new MutationObserver(function(mutations) {
$('.jw-text-track-cue').each(function(i) {
if (i == 0)
$('#ccbuffer').html( $(this).text() );
else
$('#ccbuffer').append("<br/>" + $(this).text() );
});
});
// configuration of the observer:
var config = { attributes: true, childList: true, characterData: true }
// pass in the target node, as well as the observer options
observer.observe(target, config);
}
});
$(document).ready(function () {
$('#ccbuffer').hide();
});
</script>
So when the user enables captions, the ccbuffer window will slide open and display a clean 3 line representation of the CC text.
Final Solution: External Captions that are draggable/resizable
All credit to #Basildane, I worked out how to extenalize the captions with VOD, and to make them draggable and resizable, with CSS experimentation for ADA consideration:
<!DOCTYPE html>
<html>
<head>
<title>JW External Captions</title>
<meta http-equiv="Expires" content="Fri, Jan 01 1900 00:00:00 GMT">
<meta http-equiv="Pragma" content="no-cache">
<meta http-equiv="Cache-Control" content="no-cache">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta http-equiv="Lang" content="en">
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet">
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
<script src="/jwplayer/v8.10/jwplayer.js"></script>
<style type="text/css">
#myPlayer {
margin-bottom:5px;
}
.jw-captions {
display: none !important;
}
#ccbuffer {
color: white;
background-color: black;
opacity:.7;
font: 22px bold san-serif;
width: 100%;
padding: 15px;
height: 100%;
position:relative;
}
.night {
color:silver !important;
background-color: black !important;
opacity:1 !important;
border-color:silver !important;
}
.highcontrast {
color:white ! important;
background-color: black !important;
opacity:1 !important;
border-color:white !important;
}
.highcontrast2 {
color:black !important;
background-color: yellow !important;
opacity:1 !important;
border-color:black !important;
}
.highcontrast3 {
color:yellow !important;
background-color: black !important;
opacity:1 !important;
border-color:yellow !important;
}
#ccContainer {
position: absolute;
z-index: 9;
border: 1px solid inherit;
overflow: hidden;
resize: both;
width: 640px;
height: 180px;
min-width: 120px;
min-height: 90px;
max-width: 960px;
max-height: 300px;
}
#ccContainerheader {
padding: 3px;
cursor: move;
z-index: 10;
background-color: #2196F3;
color: #fff;
border:1px solid;
}
</style>
</head>
<body>
<h3>JW Draggable Captions Container</h3>
<div id="PlayerContainer" style="width:401px;">
<div id="myPlayer">Loading video...</div>
</div>
<div id="ccContainer">
<!-- Include a header DIV with the same name as the draggable DIV, followed by "header" -->
<div style="float:right;">
<form id="myform">
<select id="ccFontFamily">
<option value="sans-serif">Default Font</option>
<option value="serif">Serif</option>
<option value="monospace">Monospace</option>
<option value="cursive">Cursive </option>
</select>
<select id="ccFontSize" style="">
<option value="22">Default Size</option>
<option value="14">14</option>
<option value="18">18</option>
<option value="24">24</option>
<option value="32">32</option>
</select>
<select id="ccContrast" style="">
<option value="ccdefault">Default Contrast</option>
<option value="night">Night</option>
<option value="highcontrast">High Contrast</option>
<option value="highcontrast2">Black/Yellow</option>
<option value="highcontrast3">Yellow/Black</option>
</select>
<button id="ccFontReset">Reset</button>
</form>
</div>
<div id="ccContainerheader">
Captions (click to move)
</div>
<div id="ccbuffer"></div>
</div>
<script type="text/javascript">
$(document).ready(function() {
jwplayer.key = 'xxxxxxxxxxxxxxxxxxx';
jwplayer('myPlayer').setup({
width: '100%', aspectratio: '16:9', repeat: 'false', autostart: 'false',
playlist: [{
sources: [ { file: 'https:www.example.com/video.mp4'}],
tracks: [ { file: 'https:www.example.com/video-captions.vtt', kind: 'captions', label: 'English', 'default': true } ]
}]
})
// External CC Container
$('#ccContainer').hide();
var position = $('#myPlayer').position();
var width = $('#PlayerContainer').outerWidth();
ccTop = position.top;
ccLeft = (width+50)+'px'
$('#ccContainer').css({'top':ccTop, left:ccLeft });
var observer;
jwplayer().on('captionsList', function (event) {
ccObserver(event);
});
jwplayer().on('captionsChanged', function (event) {
ccObserver(event);
});
videoplayer.on('fullscreen', function(event){
if(event.fullscreen){
$('.jw-captions').css('display','block');
}else{
$('.jw-captions').css('display','none');
}
});
$("#ccFontFamily").change(function() {
$('#ccbuffer').css("font-family", $(this).val());
});
$("#ccFontSize").change(function() {
$('#ccbuffer').css("font-size", $(this).val() + "px");
});
$("#ccContrast").change(function() {
$('#ccContainer').removeClass("night highcontrast highcontrast2 highcontrast3").addClass( $(this).val() );
$('#ccContainerheader').removeClass("night highcontrast highcontrast2 highcontrast3").addClass( $(this).val() );
$('#ccbuffer').removeClass("night highcontrast highcontrast2 highcontrast3").addClass( $(this).val() );
$('select').removeClass("night highcontrast highcontrast2 highcontrast3").addClass( $(this).val() );
$('#ccFontReset').removeClass("night highcontrast highcontrast2 highcontrast3").addClass( $(this).val() );
});
$('#ccFontReset').click(function() {
ccFontReset();
});
function ccFontReset(){
$("#ccFontFamily").val($("#ccFontFamily option:first").val()).trigger('change');
$("#ccFontSize").val($("#ccFontSize option:first").val()).trigger('change');
$("#ccContrast").val($("#ccContrast option:first").val()).trigger('change');
}
ccFontReset();
});
function ccObserver(event){
if (event.track == 0) {
$('#ccContainer').hide('slow');
$('.jw-captions').css('display','block'); // VERY important
if (observer != null){
observer.disconnect();
}
}
else {
$('#ccContainer').show('slow');
$('.jw-captions').css('display','none'); // VERY important
var target = document.querySelector('.jw-captions');
observer = new MutationObserver(function(mutations) {
$('.jw-text-track-cue').each(function(i) {
if (i == 0)
$('#ccbuffer').html( $(this).text() );
else
$('#ccbuffer').append("<br/>" + $(this).text() );
});
});
var config = { attributes: true, childList: true, characterData: true }
observer.observe(target, config);
}
}
// External CC Container - Make the DIV element draggable:
dragElement(document.getElementById("ccContainer"));
function dragElement(elmnt) {
var pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0;
if (document.getElementById(elmnt.id + "header")) {
document.getElementById(elmnt.id + "header").onmousedown = dragMouseDown;
} else {
elmnt.onmousedown = dragMouseDown;
}
function dragMouseDown(e) {
e = e || window.event;
e.preventDefault();
pos3 = e.clientX;
pos4 = e.clientY;
document.onmouseup = closeDragElement;
document.onmousemove = elementDrag;
}
function elementDrag(e) {
e = e || window.event;
e.preventDefault();
pos1 = pos3 - e.clientX;
pos2 = pos4 - e.clientY;
pos3 = e.clientX;
pos4 = e.clientY;
elmnt.style.top = (elmnt.offsetTop - pos2) + "px";
elmnt.style.left = (elmnt.offsetLeft - pos1) + "px";
}
function closeDragElement() {
document.onmouseup = null;
document.onmousemove = null;
}
}
</script>
</body>
</html>
I'm having difficulty centering my D3 map on the webpage. The map is in a map class and within a div, but CSS won't appear to center it.
Any margins I apply to the class ".map", which the SVG is in, doesn't appear to work either. I'm not sure why I'm unable to apply any CSS to the map, but maybe I'm supposed to do something in the actual D3 code? Unsure. Thanks!
Here's my code:
<!DOCTYPE html>
<html>
<head>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/d3-tip/0.7.1/d3-tip.js'></script>
<meta charset='utf-8'>
<meta name="viewport" content='width=device-width, initial-scale=1.0'>
<title></title>
<style>
.d3-tip {
line-height: 1;
font-weight: bold;
padding: 10px;
background: rgba(0, 0, 0, 0.8);
color: #fff;
border-radius: 10px;
}
.active {
fill: rgba(149, 165, 166, 0.8);
}
body {
background: rgba(32, 32, 32, 1);
color: rgba(255, 255, 255, 0.8);
}
h1 {
font-family: Impact, Charcoal, sans-serif;
text-align: center;
}
h2 {
font-family: Impact, Charcoal, sans-serif;
text-align: center;
}
p {
font-family: "Arial Black", Gadget, sans-serif;
text-align: center;
}
#box {
border: 10px solid black;
margin: auto;
padding: 10px;
width: 75%;
border-radius: 10px;
}
.map {
margin-left: auto;
margin-right: auto;
}
</style>
<script>
function draw(geo_data) {
var margin = 0,
width = 2000 - margin,
height = 700 - margin;
var centered;
var svg = d3.select('#map')
.append('svg')
.attr('width', width + margin)
.attr('height', height + margin)
.append('g')
.attr('class', 'map');
var formatComma = d3.format(",")
var projection = d3.geoAlbersUsa();
var path = d3.geoPath().projection(projection);
var map = svg.selectAll('path')
.data(geo_data.features)
.enter()
.append('path')
.attr('d', path)
.attr('fill', 'rgba(105, 105, 105, 1)')
.attr('stroke', 'rgba(0, 0, 0, 1)')
.attr('stroke-width', 0.5)
.on('mouseover', function(d) {
d3.select(this).attr('fill', 'rgba(108, 122, 137, 0.5)')
})
.on('mouseout', function() {
if (d3.select(this).classed('clicked')) {
console.log('is clicked')
d3.select(this).attr('fill', 'rgba(105, 105, 105, 1)')
} else {
console.log('is not clicked')
d3.select(this).attr('fill', 'rgba(105, 105, 105, 1)')
}
})
// Calls click-to-zoom function defined below.
.on('click', clicked);
var tip = d3.tip()
.attr('class', 'd3-tip')
.offset([-10, 0])
.html(function(d) {
return "<p><font size='4rem'>" + d.city + ", " + d.state + "</p></font>" + "<p><font size='3rem'><strong>Guns Manufactured: </strong>" + formatComma(d.guns) + "</p>" +
"<p><strong>Top Manufacturer:</strong> " + d.manufacturer +
"</p></font>";
})
svg.call(tip);
// Click-to-zoom function adapted from Mike Bostock's code: https://bl.ocks.org/mbostock/2206590
function clicked(d) {
d3.select(this).attr('fill', 'rgba(108, 122, 137, 0.5)');
if (d3.select(this).classed('clicked')) {
d3.select(this).attr('clicked', false);
} else {
d3.select(this).attr('clicked', true);
}
var x, y, k;
if (d && centered !== d) {
var centroid = path.centroid(d);
x = centroid[0];
y = centroid[1];
k = 4;
centered = d;
} else {
x = width / 2;
y = height / 2;
k = 1;
centered = null;
}
map.selectAll('path')
.classed('active', centered && function(d) {
return d === centered;
});
map.transition()
.duration(1000)
.attr('transform', 'translate(' + width / 2 + ',' + height / 2 + ')scale(' + k + ')translate(' + -x + ',' + -y + ')')
.style('stroke-width', 1 / k + 'px');
// Transitions circles upon zoom.
svg.selectAll('circle')
.transition()
.duration(1000)
.attr('transform', 'translate(' + width / 2 + ',' + height / 2 + ')scale(' + k + ')translate(' + -x + ',' + -y + ')')
.style('stroke-width', 1 / k + 'px');
}
d3.csv('https://raw.githubusercontent.com/dieterholger/US-Gun-Manufacturing-Interactive/master/top100cities.csv', function(error, data) {
// Converts strings in csv to integers so they can be used.
data.forEach(function(d) {
return d.guns = +d.guns;
})
// This returns the max number of guns.
var guns = data.map(function(d) {
return d.guns;
});
var guns_extent = d3.extent(data, function(d) {
return d.guns;
});
var radius = d3.scaleSqrt()
.domain(guns_extent)
.range([2, 40]);
svg.append('g')
.attr('class', 'bubble')
.selectAll('circle')
.data(data)
.enter()
.append('circle')
.attr('cx', function(d) {
return projection([d.lon, d.lat])[0];
})
.attr('cy', function(d) {
return projection([d.lon, d.lat])[1];
})
.attr('r', function(d) {
return radius(d.guns);
})
.attr('fill', 'rgba(248, 148, 6, 0.5)')
.attr('stroke', 'black')
.on('mouseover', function(d) {
tip.show(d);
return d3.select(this).attr('fill', 'rgba(248, 148, 6, 0.9)');
})
.on('mouseout', function(d) {
tip.hide(d);
return d3.select(this).attr('fill', 'rgba(248, 148, 6, 0.5)');
})
});
};
</script>
</head>
<body>
<div id='box'>
</div>
<div id='map'>
<h2>Hover your mouse to see data on the cities and click a state to zoom in.</h2>
</div>
<div id='box'>
</div>
<script>
d3.json('https://raw.githubusercontent.com/dieterholger/US-Gun-Manufacturing-Interactive/master/us_states.json', draw);
</script>
</body>
Enclose the map in another div, which has the same width as the box above it (75%). You may want to move the div style to a CSS class, if it works the way you want.
<div style="display:block; margin-left:auto; margin-right:auto; width:75%">
<div id="map">
...
</div>
</div>
UPDATE
I just found the real problem. Your css definition for map is for a class, not for an id. And... if you want to use auto margins, you need to define a width.
Change your css to match the following:
#map {
width: 75%;
margin-left: auto;
margin-right: auto;
}
I want to highlight a area like on the image below which is taken from Google Maps. Is this possible to accomplish with the current version of their API (v3)? If yes, how?
Thanks in advance.
You need to know the vertices of the area and create a polygon based on them.
But dashed strokes currently are not supported by polygons, if you require to have a dashed stroke you must create a sequence of polylines with different stroke-colors based on the vertices.
A built-in method to highlight an area currently doesn't exist.
You can automatically highlight an area with Google Maps Javascript API, here is an example:
<!DOCTYPE html>
<html>
<head>
<title>Place ID Finder</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<style>
#map {
height: 100%;
}
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#ggg
{
position: absolute;
left:20%;
top:5%;
}
.controls {
background-color: #fff;
border-radius: 2px;
border: 1px solid transparent;
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
box-sizing: border-box;
font-family: Roboto;
font-size: 15px;
font-weight: 300;
height: 29px;
margin-left: 17px;
margin-top: 10px;
outline: none;
padding: 0 11px 0 13px;
text-overflow: ellipsis;
width: 400px;
}
.controls:focus {
border-color: #4d90fe;
}
.title {
font-weight: bold;
}
#infowindow-content {
display: none;
}
#map #infowindow-content {
display: inline;
}
</style>
</head>
<body>
<div style="display: none">
<input id="pac-input" class="controls" type="text" placeholder="Enter a location">
</div>
<div id="map"></div>
<div id="infowindow-content">
<span id="place-name" class="title"></span><br>
<strong>Place ID:</strong> <span id="place-id"></span><br>
<span id="place-address"></span>
</div>
<script>
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 37.9989746, lng: 23.6413698},
zoom: 11
});
var input = document.getElementById('pac-input');
var autocomplete = new google.maps.places.Autocomplete(input);
autocomplete.bindTo('bounds', map);
autocomplete.setFields(
['place_id', 'geometry', 'name', 'formatted_address']);
map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
var infowindow = new google.maps.InfoWindow();
var infowindowContent = document.getElementById('infowindow-content');
infowindow.setContent(infowindowContent);
var marker = new google.maps.Marker({map: map});
marker.addListener('click', function() {
infowindow.open(map, marker);
});
autocomplete.addListener('place_changed', function() {
infowindow.close();
var place = autocomplete.getPlace();
if (!place.geometry) {
return;
}
if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
} else {
map.setCenter(place.geometry.location);
map.setZoom(17);
}
marker.setPlace({
placeId: place.place_id,
location: place.geometry.location,
});
marker.setVisible(true);
infowindowContent.children['place-name'].textContent = place.name;
infowindowContent.children['place-id'].textContent = place.place_id;
infowindowContent.children['place-address'].textContent = place.formatted_address;
infowindow.open(map, marker);
var frame = document.getElementById("map");
frame.innerHTML = '<iframe width="100%" height="100%" frameborder="0" style="border:0" src="https://www.google.com/maps/embed/v1/place?q=place_id:'.concat(place.place_id).concat('&key=XXXXXXX" allowfullscreen></iframe>');
frame.innerHTML += '<p id="ggg"><button type="button" onclick="location.reload()">Try again!</button></p>';
});
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=XXXXXXXXX&libraries=places&callback=initMap" async defer></script>
</body>
</html>
You will need to replace API KEY with your API KEY. Try e.g."Nea Smyrni 171 21, Greece" in the input and then select the first drop down option and notice that it automatically highlights the area!