d3 putting multi pie chart on map - dictionary

I want to put multi pie chart on d3 map but I'm confused how to do it.
I'm noob at d3 so I searched about the issue and made below code.
Someone suggested that I should make two seperate svgs so I did it.
There are two svgs. one has a map, and the other has multiple pie chart.
Now I have a problem with mapping these pies on map.
I don't know how to map these pies with geo coordinates...
It's just browser(?) coordinates so I want to change it.
and I want to zoom and pan map correctly with pies...
hope your help...
summary
I have two problems
putting multiple pie charts on right map place
zoom and pan correctly
<script src="http://d3js.org/d3.v3.min.js"></script>
<script src="http://d3js.org/topojson.v0.min.js"></script>
<script>
var width = 960, height = 500;
var projection = d3.geo.mercator().center([ 127.46, 36.00 ])
.scale(4000).translate([ width / 2, height / 2 ]);
var color = d3.scale.category20();
//first svg
var svg = d3.select("body").append("svg").attr("width", width).attr(
"height", height);
var path = d3.geo.path().projection(projection);
var radius = 30;
var arc = d3.svg.arc().innerRadius(radius - 100).outerRadius(
radius - 20);
var g = svg.append("g");
var rawFile = new XMLHttpRequest();
rawFile.open("GET", "/tourdata.txt", false);
var allText;
rawFile.onreadystatechange = function() {
if (rawFile.readyState === 4) {
if (rawFile.status === 200 || rawFile.status == 0) {
allText = rawFile.responseText;
}
}
}
rawFile.send(null);
var lines = allText.split('\n');
var timeTable = new Array();
var res = lines[0].split(", ");
var currentTime = res[1];
var currentDate = res[0];
var timeInformation = new Array();
var corInformation = new Array();
var timeCorTable = new Array();
for ( var i = 0; i < lines.length; i++) {
var res = lines[i].split(", ");
if (currentDate != res[0] || currentTime != res[1]) {
currentDate = res[0];
currentTime = res[1];
timeTable[currentDate + ":" + currentTime] = timeInformation;
timeCorTable[currentDate + ":" + currentTime] = timeCorTable;
timeInformation = new Array();
corInformation = new Array();
}
if (timeInformation[res[2] + "," + res[3]] == undefined) {
corInformation.push(res[2] + "," + res[3]);
timeInformation.push([ res[4], res[5], res[6], res[7], res[8],
res[9], res[10], res[11], res[12], res[13] ]);
}
}
timeTable.push(timeInformation);
timeCorTable.push(corInformation);
var data = timeTable;
console.log(timeCorTable[0]);
// load and display the World
d3.json("kor.json",
function(error, topology) {
// load and display the cities
var geo = topojson.object(topology,
topology.objects['kor.geo']).geometries;
g.selectAll('path').data(geo).enter().append('path').attr(
'd', path)
});
console.log(data[0]);
//second svg that has multiple pies
var svgSvg = d3.select("body").select("svg").selectAll("g").data(timeTable[0]).enter().append("svg:svg").attr(
"width", width).attr("height", height).append("svg:g").style(//svg:g make pie group
"opacity", 0.8).attr("transform", function(d, i) {
var split = timeCorTable[0][i].split(",");
//console.log(split[0]);
var point = [split[0], split[1]];
console.log(projection(point[0], point[1])[0]);
return ("translate(" + projection(point[0], point[1])[0] + "," + projection(point[0], point[1])[1] + ")");
});
svgSvg.selectAll("path").data(d3.layout.pie()).enter().append(
"svg:path").attr("d",
d3.svg.arc().innerRadius(10).outerRadius(30)).style("fill", function(d, i) { return color(i); });
// zoom and pan
var zoom = d3.behavior.zoom().on(
"zoom",
function() {
g.attr("transform", "translate("
+ d3.event.translate.join(",") + ")scale("
+ d3.event.scale + ")");
g.selectAll("path").attr("d", path.projection(projection));
svgSvg.attr("transform", "translate("
+ d3.event.translate.join(",") + ")scale("
+ d3.event.scale + ")");
});
svg.call(zoom)
</script>

Related

First page is blackened after adding watermark

Page is blackened after adding watermark in case of some pdf files . Please see attached image.
What could be the reason , and possible fix.
see the blacked out page image
It does not happen for all the files but for some files only.
Code is here in dotnetfiddle.
var _pdfInBytes = File.ReadAllBytes("c:\\test\\test123.pdf");
string watermarkText = "This watermark text on left side";
var coordinates = new Point(25, 200);
using (var pdfNewDoc = new PdfDocument())
{
using (var pdfImport = PdfReader.Open(new MemoryStream(_pdfInBytes, true), PdfDocumentOpenMode.Import))
{
if (pdfImport.PageCount == 0)
{
return;
}
foreach (var pg in pdfImport.Pages)
{
pdfNewDoc.AddPage(pg);
}
var page = pdfNewDoc.Pages[0];
// overlapping trick #165910
var xOffset = 100.0;
for (var index = 0; index < page.Contents.Elements.Count; index++)
{
var stream = page.Contents.Elements.GetDictionary(index).Stream;
var x = GetMinXOffsetDraft(stream.ToString());
if (xOffset > x)
{
xOffset = x;
}
}
xOffset *= 0.6; // magic number :)
// blank page trick #165910
if (page.CropBox.IsEmpty && !page.MediaBox.IsEmpty)
{
page.CropBox = page.MediaBox;
}
// Get an XGraphics object for drawing beneath the existing content
var gfx = XGraphics.FromPdfPage(page, XGraphicsPdfPageOptions.Prepend);
var tf = new XTextFormatter(gfx);
var xFont = new XFont("Arial", 10, XFontStyle.Regular);
// Get watermark text size
var wmSize = gfx.MeasureString(watermarkText, xFont);
// Middle Y coordinate
var wmY = (gfx.PageSize.Height - wmSize.Width) / 2;
var coords = new XPoint(page.CropBox.Location.X + (xOffset < coordinates.X ? xOffset : coordinates.X),
page.CropBox.Location.Y + (coordinates.Y > wmY ? coordinates.Y : wmY));
// Define a rotation transformation at the center of the page
gfx.TranslateTransform(coordinates.X, coordinates.Y);
gfx.RotateTransform(90);
gfx.TranslateTransform(-coordinates.X, -coordinates.Y);
// Create brush
var brushColor = Color.Red;
var brush1= new XSolidBrush(XColor.FromArgb(brushColor.A, brushColor.R, brushColor.G, brushColor.B));
brush1.Overprint = false;
XBrush brush =
new XSolidBrush(XColor.FromArgb(brushColor.A, brushColor.R, brushColor.G, brushColor.B));
var rect = new XRect(coordinates.X, coordinates.Y, gfx.PageSize.Height - coordinates.Y,
coordinates.X);
tf.DrawString(watermarkText, xFont, brush, rect);
byte[] outputBytes = null;
using (var outStream = new MemoryStream())
{
pdfNewDoc.Save(outStream, false);
outputBytes = outStream.ToArray();
}
File.WriteAllBytes("c:\\test\\test-"+DateTime.Now.ToString("ddmmyyyyhhmmss") +".pdf", outputBytes);
private double GetMinXOffsetDraft(string v)
{
var result = 100.0;
using (var str = new StringReader(v))
{
var s = str.ReadLine();
do
{
var sarr = s?.Split(' ');
if (sarr?.Length == 7 && sarr[6] == "Tm")
{
var x = double.Parse(sarr[4]);
x = x < 0 ? 200 : x;
result = result > x ? x : result;
}
s = str.ReadLine();
} while (s != null);
}
return result;
} var _pdfInBytes = File.ReadAllBytes("c:\\test\\test123.pdf");
string watermarkText = "This watermark text on left side";
var coordinates = new Point(25, 200);
using (var pdfNewDoc = new PdfDocument())
{
using (var pdfImport = PdfReader.Open(new MemoryStream(_pdfInBytes, true), PdfDocumentOpenMode.Import))
{
if (pdfImport.PageCount == 0)
{
return;
}
foreach (var pg in pdfImport.Pages)
{
pdfNewDoc.AddPage(pg);
}
var page = pdfNewDoc.Pages[0];
// overlapping trick #165910
var xOffset = 100.0;
for (var index = 0; index < page.Contents.Elements.Count; index++)
{
var stream = page.Contents.Elements.GetDictionary(index).Stream;
var x = GetMinXOffsetDraft(stream.ToString());
if (xOffset > x)
{
xOffset = x;
}
}
xOffset *= 0.6; // magic number :)
// blank page trick #165910
if (page.CropBox.IsEmpty && !page.MediaBox.IsEmpty)
{
page.CropBox = page.MediaBox;
}
// Get an XGraphics object for drawing beneath the existing content
var gfx = XGraphics.FromPdfPage(page, XGraphicsPdfPageOptions.Prepend);
var tf = new XTextFormatter(gfx);
var xFont = new XFont("Arial", 10, XFontStyle.Regular);
// Get watermark text size
var wmSize = gfx.MeasureString(watermarkText, xFont);
// Middle Y coordinate
var wmY = (gfx.PageSize.Height - wmSize.Width) / 2;
var coords = new XPoint(page.CropBox.Location.X + (xOffset < coordinates.X ? xOffset : coordinates.X),
page.CropBox.Location.Y + (coordinates.Y > wmY ? coordinates.Y : wmY));
// Define a rotation transformation at the center of the page
gfx.TranslateTransform(coordinates.X, coordinates.Y);
gfx.RotateTransform(90);
gfx.TranslateTransform(-coordinates.X, -coordinates.Y);
// Create brush
var brushColor = Color.Red;
var brush1= new XSolidBrush(XColor.FromArgb(brushColor.A, brushColor.R, brushColor.G, brushColor.B));
brush1.Overprint = false;
XBrush brush =
new XSolidBrush(XColor.FromArgb(brushColor.A, brushColor.R, brushColor.G, brushColor.B));
var rect = new XRect(coordinates.X, coordinates.Y, gfx.PageSize.Height - coordinates.Y,
coordinates.X);
tf.DrawString(watermarkText, xFont, brush, rect);
byte[] outputBytes = null;
using (var outStream = new MemoryStream())
{
pdfNewDoc.Save(outStream, false);
outputBytes = outStream.ToArray();
}
File.WriteAllBytes("c:\\test\\test-"+DateTime.Now.ToString("ddmmyyyyhhmmss") +".pdf", outputBytes);
private double GetMinXOffsetDraft(string v)
{
var result = 100.0;
using (var str = new StringReader(v))
{
var s = str.ReadLine();
do
{
var sarr = s?.Split(' ');
if (sarr?.Length == 7 && sarr[6] == "Tm")
{
var x = double.Parse(sarr[4]);
x = x < 0 ? 200 : x;
result = result > x ? x : result;
}
s = str.ReadLine();
} while (s != null);
}
return result;
}

GoogleMaps Markerclusterer InfoWindow same location, Cluster get content from Markers

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 + "&nbspм " + 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

Google Sheets Google Analytics Data by Channel

I have a Google Sheets file which calls Google Analytics and pulls metrics. This works great. What I want to do is pull metrics by channel so that the far left column is a collection of channels (PPC, Display, Organic, Social, Email, Referral, Affiliate, Direct). Do I need to use the Multi-Channel Funnel setup? Or is there a better way to do this?
function getGAData() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("test Data");
// var startDate = dateToYMD(sheet.getRange(3,3).getValue());
// var endDate = dateToYMD(sheet.getRange(3,4).getValue());
var dateRanges = readDateRanges(sheet);
var profileIds = readProfileIds(sheet);
var GAMetrics = readGAMetrics(sheet);
var results = [];
var metrics = [];
var optArgs = [];
var filterCount = 0;
var prevFilter = '**NONE**';
var i, j, k;
var profileResults;
var tempResults;
for (i = 0; i < GAMetrics[0].length; i++) {
// Utilities.sleep(100);
if (prevFilter != GAMetrics[1][i]) {
metrics[filterCount] = GAMetrics[0][i];
optArgs[filterCount] = {
'start-index': '1',
'max-results': '10' // Display the first 250 results.
};
if (GAMetrics[1][i] != '')
optArgs[filterCount].filters = GAMetrics[1][i];
if (GAMetrics[2][i] != '')
optArgs[filterCount].segment = GAMetrics[2][i];
filterCount++;
} else {
metrics[filterCount-1] = metrics[filterCount-1] + ',' + GAMetrics[0][i];
}
prevFilter = GAMetrics[1][i];
}
for (i = 0; i < profileIds.length; i++) { // get GA data for each of the rows of input
profileResults = [];
var tableId = 'ga:' + profileIds[i][0];
var startDate = dateToYMD(dateRanges[i][0]);
var endDate = dateToYMD(dateRanges[i][1]);
for (j = 0; j < metrics.length; j++) {
var metric = metrics[j];
var options = optArgs[j];
//var options = {
// 'dimensions': 'ga:source',
//};
try {
// Make a request to the API.
tempResults = Analytics.Data.Ga.get(
'ga:' + profileIds[i][0], // Table id (format ga:xxxxxx).
dateToYMD(dateRanges[i][0]), // Start-date (format yyyy-MM-dd).
dateToYMD(dateRanges[i][1]), // End-date (format yyyy-MM-dd).
metrics[j], // Comma seperated list of metrics.
optArgs[j]);
var report = Analytics.Data.Ga.get(tableId, startDate, endDate, metric,
options);
if (typeof tempResults.getRows() != 'undefined')
appendArray(profileResults, tempResults.getRows()[0]);
} catch (e) {
Logger.log(e + ' - Profile ID: ' + profileIds[i][0] + ' - Metrics: ' + metrics[j] );
}
}
//append Profile results to the set
for (k = profileResults.length; k < GAMetrics[0].length; k++)
profileResults[k] = '0';
results.push(profileResults);
// Utilities.sleep(200);
}
sheet.getRange(6, 13, results.length, GAMetrics[0].length).setValues(results); // populate results on spreadsheet
emailLog('don#test.com','startDate');
}
function readDateRanges(sheet){
var rowStart = 6;
var columnStart = 1;
var numRows = sheet.getLastRow() - rowStart + 1;
return sheet.getRange(rowStart, columnStart, numRows, 2).getValues();
}
function readProfileIds(sheet) {
var rowStart = 6;
var columnStart = 3;
var numRows = sheet.getLastRow() - rowStart + 1;
return sheet.getRange(rowStart, columnStart, numRows, 1).getValues();
}
function readGAMetrics(sheet) {
var rowStart = 2;
var columnStart = 13;
var numColumns = sheet.getLastColumn() - columnStart + 1;
return sheet.getRange(rowStart, columnStart, 3, numColumns).getValues();
}
function dateToYMD(date) {
var d = date.getDate();
var m = date.getMonth() + 1;
var y = date.getFullYear();
return '' + y + '-' + (m<=9 ? '0' + m : m) + '-' + (d <= 9 ? '0' + d : d);
}
function appendArray(a1,a2) {
var startSize = a1.length;
for (var i = 0; i < a2.length; i++)
a1[startSize + i] = a2[i];
}
function emailLog(emailAddress,reportDate) {
var recipient = emailAddress; // Session.getActiveUser().getEmail();
var subject = 'GA Data Pull - extract for ' + reportDate;
var body = Logger.getLog();
MailApp.sendEmail(recipient, subject, body);
}

latLng from polyLine Percentage

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>

Errors with fitBounds in Google Maps

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);

Resources